diff --git a/Cargo.lock b/Cargo.lock index d3c6be59b75df..63a84f1fc2adc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2780,6 +2780,7 @@ name = "rustc_data_structures" version = "0.0.0" dependencies = [ "cfg-if 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", "ena 0.13.0 (registry+https://github.com/rust-lang/crates.io-index)", "graphviz 0.0.0", "indexmap 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", diff --git a/src/bootstrap/bin/rustc.rs b/src/bootstrap/bin/rustc.rs index f5fb6f0b4d008..ff8253de3f40c 100644 --- a/src/bootstrap/bin/rustc.rs +++ b/src/bootstrap/bin/rustc.rs @@ -312,7 +312,8 @@ fn main() { { cmd.arg("-Dwarnings"); cmd.arg("-Dbare_trait_objects"); - cmd.arg("-Drust_2018_idioms"); + // FIXME(@Zoxc): Turn back on + //cmd.arg("-Drust_2018_idioms"); } if verbose > 1 { diff --git a/src/librustc/arena.rs b/src/librustc/arena.rs index e8c3914e695ad..2cccb2d0cbc28 100644 --- a/src/librustc/arena.rs +++ b/src/librustc/arena.rs @@ -31,6 +31,12 @@ macro_rules! arena_types { rustc::hir::def_id::DefId, rustc::ty::subst::SubstsRef<$tcx> )>, + [] lits: syntax::source_map::Spanned, + [] attrs: syntax::ast::Attribute, + [few] token_streams: syntax::tokenstream::TokenStream, + [few] inline_asm: rustc::hir::InlineAsm, + [few] lowered_hir: rustc::hir::LoweredHir<$tcx>, + [few] hir_map: rustc::hir::map::Map<$tcx>, [few, decode] mir_keys: rustc::util::nodemap::DefIdSet, [decode] specialization_graph: rustc::traits::specialization_graph::Graph, [] region_scope_tree: rustc::middle::region::ScopeTree, diff --git a/src/librustc/cfg/construct.rs b/src/librustc/cfg/construct.rs index 139c144fbcf4e..7b31d707bc4c1 100644 --- a/src/librustc/cfg/construct.rs +++ b/src/librustc/cfg/construct.rs @@ -1,9 +1,9 @@ use crate::cfg::*; use crate::middle::region; use rustc_data_structures::graph::implementation as graph; -use syntax::ptr::P; use crate::ty::{self, TyCtxt}; +use crate::hir::ptr::P; use crate::hir::{self, PatKind}; use crate::hir::def_id::DefId; @@ -66,7 +66,7 @@ pub fn construct<'tcx>(tcx: TyCtxt<'tcx>, body: &hir::Body) -> CFG { } impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { - fn block(&mut self, blk: &hir::Block, pred: CFGIndex) -> CFGIndex { + fn block(&mut self, blk: &hir::Block<'_>, pred: CFGIndex) -> CFGIndex { if blk.targeted_by_break { let expr_exit = self.add_ast_node(blk.hir_id.local_id, &[]); @@ -97,7 +97,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { } } - fn stmt(&mut self, stmt: &hir::Stmt, pred: CFGIndex) -> CFGIndex { + fn stmt(&mut self, stmt: &hir::Stmt<'_>, pred: CFGIndex) -> CFGIndex { let exit = match stmt.node { hir::StmtKind::Local(ref local) => { let init_exit = self.opt_expr(&local.init, pred); @@ -114,7 +114,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { self.add_ast_node(stmt.hir_id.local_id, &[exit]) } - fn pat(&mut self, pat: &hir::Pat, pred: CFGIndex) -> CFGIndex { + fn pat(&mut self, pat: &hir::Pat<'_>, pred: CFGIndex) -> CFGIndex { match pat.node { PatKind::Binding(.., None) | PatKind::Path(_) | @@ -149,16 +149,14 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { } } - fn pats_all<'b, I: Iterator>>( - &mut self, - pats: I, - pred: CFGIndex - ) -> CFGIndex { + fn pats_all<'b, 'h: 'b, I: Iterator>>>(&mut self, + pats: I, + pred: CFGIndex) -> CFGIndex { //! Handles case where all of the patterns must match. pats.fold(pred, |pred, pat| self.pat(&pat, pred)) } - fn expr(&mut self, expr: &hir::Expr, pred: CFGIndex) -> CFGIndex { + fn expr(&mut self, expr: &hir::Expr<'_>, pred: CFGIndex) -> CFGIndex { match expr.node { hir::ExprKind::Block(ref blk, _) => { let blk_exit = self.block(&blk, pred); @@ -297,7 +295,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { hir::ExprKind::Index(ref l, ref r) | hir::ExprKind::Binary(_, ref l, ref r) if self.tables.is_method_call(expr) => { - self.call(expr, pred, &l, Some(&**r).into_iter()) + self.call(expr, pred, &l, Some(&***r).into_iter()) } hir::ExprKind::Unary(_, ref e) if self.tables.is_method_call(expr) => { @@ -309,18 +307,18 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { } hir::ExprKind::Struct(_, ref fields, ref base) => { - let field_cfg = self.straightline(expr, pred, fields.iter().map(|f| &*f.expr)); + let field_cfg = self.straightline(expr, pred, fields.iter().map(|f| &**f.expr)); self.opt_expr(base, field_cfg) } hir::ExprKind::Assign(ref l, ref r) | hir::ExprKind::AssignOp(_, ref l, ref r) => { - self.straightline(expr, pred, [r, l].iter().map(|&e| &**e)) + self.straightline(expr, pred, [r, l].iter().map(|&e| &***e)) } hir::ExprKind::Index(ref l, ref r) | hir::ExprKind::Binary(_, ref l, ref r) => { // N.B., && and || handled earlier - self.straightline(expr, pred, [l, r].iter().map(|&e| &**e)) + self.straightline(expr, pred, [l, r].iter().map(|&e| &***e)) } hir::ExprKind::Box(ref e) | @@ -332,7 +330,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { hir::ExprKind::Field(ref e, _) | hir::ExprKind::Yield(ref e) | hir::ExprKind::Repeat(ref e, _) => { - self.straightline(expr, pred, Some(&**e).into_iter()) + self.straightline(expr, pred, Some(&***e).into_iter()) } hir::ExprKind::InlineAsm(_, ref outputs, ref inputs) => { @@ -350,10 +348,10 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { } } - fn call<'b, I: Iterator>(&mut self, - call_expr: &hir::Expr, + fn call<'b, 'h: 'b, I: Iterator>>(&mut self, + call_expr: &hir::Expr<'_>, pred: CFGIndex, - func_or_rcvr: &hir::Expr, + func_or_rcvr: &hir::Expr<'_>, args: I) -> CFGIndex { let func_or_rcvr_exit = self.expr(func_or_rcvr, pred); let ret = self.straightline(call_expr, func_or_rcvr_exit, args); @@ -365,7 +363,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { } } - fn exprs<'b, I: Iterator>(&mut self, + fn exprs<'b, 'h: 'b, I: Iterator>>(&mut self, exprs: I, pred: CFGIndex) -> CFGIndex { //! Constructs graph for `exprs` evaluated in order @@ -373,14 +371,14 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { } fn opt_expr(&mut self, - opt_expr: &Option>, + opt_expr: &Option>>, pred: CFGIndex) -> CFGIndex { //! Constructs graph for `opt_expr` evaluated, if Some opt_expr.iter().fold(pred, |p, e| self.expr(&e, p)) } - fn straightline<'b, I: Iterator>(&mut self, - expr: &hir::Expr, + fn straightline<'b, 'h: 'b, I: Iterator>>(&mut self, + expr: &hir::Expr<'_>, pred: CFGIndex, subexprs: I) -> CFGIndex { //! Handles case of an expression that evaluates `subexprs` in order @@ -389,8 +387,8 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { self.add_ast_node(expr.hir_id.local_id, &[subexprs_exit]) } - fn match_(&mut self, id: hir::ItemLocalId, discr: &hir::Expr, - arms: &[hir::Arm], pred: CFGIndex) -> CFGIndex { + fn match_(&mut self, id: hir::ItemLocalId, discr: &hir::Expr<'_>, + arms: &[hir::Arm<'_>], pred: CFGIndex) -> CFGIndex { // The CFG for match expression is quite complex, so no ASCII // art for it (yet). // @@ -495,7 +493,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { } fn add_exiting_edge(&mut self, - from_expr: &hir::Expr, + from_expr: &hir::Expr<'_>, from_index: CFGIndex, target_scope: region::Scope, to_index: CFGIndex) { @@ -513,7 +511,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { } fn add_returning_edge(&mut self, - _from_expr: &hir::Expr, + _from_expr: &hir::Expr<'_>, from_index: CFGIndex) { let data = CFGEdgeData { exiting_scopes: self.loop_scopes.iter() @@ -525,7 +523,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { } fn find_scope_edge(&self, - expr: &hir::Expr, + expr: &hir::Expr<'_>, destination: hir::Destination, scope_cf_kind: ScopeCfKind) -> (region::Scope, CFGIndex) { diff --git a/src/librustc/dep_graph/dep_node.rs b/src/librustc/dep_graph/dep_node.rs index f7647167a7578..674f861361c5d 100644 --- a/src/librustc/dep_graph/dep_node.rs +++ b/src/librustc/dep_graph/dep_node.rs @@ -310,8 +310,7 @@ macro_rules! define_dep_nodes { pub fn extract_def_id(&self, tcx: TyCtxt<'_>) -> Option { if self.kind.can_reconstruct_query_key() { let def_path_hash = DefPathHash(self.hash); - tcx.def_path_hash_to_def_id.as_ref()? - .get(&def_path_hash).cloned() + tcx.def_path_hash_to_def_id()?.get(&def_path_hash).cloned() } else { None } @@ -445,6 +444,12 @@ pub trait RecoverKey<'tcx>: Sized { fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option; } +impl RecoverKey<'tcx> for () { + fn recover(_: TyCtxt<'tcx>, _: &DepNode) -> Option { + Some(()) + } +} + impl RecoverKey<'tcx> for CrateNum { fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { dep_node.extract_def_id(tcx).map(|id| id.krate) @@ -539,6 +544,18 @@ impl<'tcx> DepNodeParams<'tcx> for CrateNum { } } +impl<'tcx> DepNodeParams<'tcx> for () { + const CAN_RECONSTRUCT_QUERY_KEY: bool = true; + + fn to_fingerprint(&self, _: TyCtxt<'_>) -> Fingerprint { + Fingerprint::ZERO + } + + fn to_debug_str(&self, _: TyCtxt<'tcx>) -> String { + "".to_string() + } +} + impl<'tcx> DepNodeParams<'tcx> for (DefId, DefId) { const CAN_RECONSTRUCT_QUERY_KEY: bool = false; diff --git a/src/librustc/dep_graph/graph.rs b/src/librustc/dep_graph/graph.rs index c2e3c12cea8ed..3ead14208cdc6 100644 --- a/src/librustc/dep_graph/graph.rs +++ b/src/librustc/dep_graph/graph.rs @@ -79,14 +79,14 @@ struct DepGraphData { loaded_from_cache: Lock>, } -pub fn hash_result(hcx: &mut StableHashingContext<'_>, result: &R) -> Option +pub fn hash_result(hcx: &mut StableHashingContext<'_>, result: &R) -> Fingerprint where R: for<'a> HashStable>, { let mut stable_hasher = StableHasher::new(); result.hash_stable(hcx, &mut stable_hasher); - Some(stable_hasher.finish()) + stable_hasher.finish() } impl DepGraph { @@ -193,7 +193,7 @@ impl DepGraph { cx: C, arg: A, task: fn(C, A) -> R, - hash_result: impl FnOnce(&mut StableHashingContext<'_>, &R) -> Option, + hash_result: Option, &R) -> Fingerprint>, ) -> (R, DepNodeIndex) where C: DepGraphSafe + StableHashingContextProvider<'a>, @@ -229,7 +229,8 @@ impl DepGraph { |data, key, fingerprint, _| { data.borrow_mut().alloc_node(key, SmallVec::new(), fingerprint) }, - hash_result::) + Some(hash_result::) + ) } fn with_task_impl<'a, C, A, R>( @@ -244,7 +245,7 @@ impl DepGraph { DepNode, Fingerprint, Option) -> DepNodeIndex, - hash_result: impl FnOnce(&mut StableHashingContext<'_>, &R) -> Option, + hash_result: Option, &R) -> Fingerprint>, ) -> (R, DepNodeIndex) where C: DepGraphSafe + StableHashingContextProvider<'a>, @@ -252,16 +253,13 @@ impl DepGraph { if let Some(ref data) = self.data { let task_deps = create_task(key).map(|deps| Lock::new(deps)); - // In incremental mode, hash the result of the task. We don't - // do anything with the hash yet, but we are computing it - // anyway so that - // - we make sure that the infrastructure works and - // - we can get an idea of the runtime cost. - let mut hcx = cx.get_stable_hashing_context(); - - if cfg!(debug_assertions) { - profq_msg(hcx.sess(), ProfileQueriesMsg::TaskBegin(key.clone())) - }; + let hcx = hash_result.as_ref().map(|_| { + let hcx = cx.get_stable_hashing_context(); + if cfg!(debug_assertions) { + profq_msg(hcx.sess(), ProfileQueriesMsg::TaskBegin(key.clone())) + }; + hcx + }); let result = if no_tcx { task(cx, arg) @@ -279,10 +277,12 @@ impl DepGraph { }; if cfg!(debug_assertions) { - profq_msg(hcx.sess(), ProfileQueriesMsg::TaskEnd) + hcx.as_ref().map(|hcx| profq_msg(hcx.sess(), ProfileQueriesMsg::TaskEnd)); }; - let current_fingerprint = hash_result(&mut hcx, &result); + let current_fingerprint = hash_result.map(|hash_result| { + hash_result(&mut hcx.unwrap(), &result) + }); let dep_node_index = finish_task_and_alloc_depnode( &data.current, @@ -291,7 +291,9 @@ impl DepGraph { task_deps.map(|lock| lock.into_inner()), ); - let print_status = cfg!(debug_assertions) && hcx.sess().opts.debugging_opts.dep_tasks; + let print_status = cfg!(debug_assertions) && ty::tls::with_opt(|tcx| { + tcx.map(|tcx| tcx.sess.opts.debugging_opts.dep_tasks).unwrap_or(false) + }); // Determine the color of the new DepNode. if let Some(prev_index) = data.previous.node_to_index_opt(&key) { @@ -378,7 +380,7 @@ impl DepGraph { cx: C, arg: A, task: fn(C, A) -> R, - hash_result: impl FnOnce(&mut StableHashingContext<'_>, &R) -> Option, + hash_result: Option, &R) -> Fingerprint>, ) -> (R, DepNodeIndex) where C: DepGraphSafe + StableHashingContextProvider<'a>, @@ -674,8 +676,6 @@ impl DepGraph { } } else { match dep_dep_node.kind { - DepKind::Hir | - DepKind::HirBody | DepKind::CrateMetadata => { if dep_dep_node.extract_def_id(tcx).is_none() { // If the node does not exist anymore, we @@ -719,7 +719,7 @@ impl DepGraph { None => { if !tcx.sess.has_errors() { bug!("try_mark_previous_green() - Forcing the DepNode \ - should have set its color") + should have set its color - dep node {:?}", dep_dep_node) } else { // If the query we just forced has resulted // in some kind of compilation error, we diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index f4f9d6261de48..a7fbaf907276b 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -40,10 +40,10 @@ use super::itemlikevisit::DeepVisitor; #[derive(Copy, Clone)] pub enum FnKind<'a> { /// `#[xxx] pub async/const/extern "Abi" fn foo()` - ItemFn(Ident, &'a Generics, FnHeader, &'a Visibility, &'a [Attribute]), + ItemFn(Ident, &'a Generics<'a>, FnHeader, &'a Visibility<'a>, &'a [Attribute]), /// `fn foo(&self)` - Method(Ident, &'a MethodSig, Option<&'a Visibility>, &'a [Attribute]), + Method(Ident, &'a MethodSig<'a>, Option<&'a Visibility<'a>>, &'a [Attribute]), /// `|x, y| {}` Closure(&'a [Attribute]), @@ -212,11 +212,11 @@ pub trait Visitor<'v> : Sized { /// Visits the top-level item and (optionally) nested items / impl items. See /// `visit_nested_item` for details. - fn visit_item(&mut self, i: &'v Item) { + fn visit_item(&mut self, i: &'v Item<'v>) { walk_item(self, i) } - fn visit_body(&mut self, b: &'v Body) { + fn visit_body(&mut self, b: &'v Body<'v>) { walk_body(self, b); } @@ -241,100 +241,100 @@ pub trait Visitor<'v> : Sized { fn visit_ident(&mut self, ident: Ident) { walk_ident(self, ident) } - fn visit_mod(&mut self, m: &'v Mod, _s: Span, n: HirId) { + fn visit_mod(&mut self, m: &'v Mod<'v>, _s: Span, n: HirId) { walk_mod(self, m, n) } - fn visit_foreign_item(&mut self, i: &'v ForeignItem) { + fn visit_foreign_item(&mut self, i: &'v ForeignItem<'v>) { walk_foreign_item(self, i) } - fn visit_local(&mut self, l: &'v Local) { + fn visit_local(&mut self, l: &'v Local<'v>) { walk_local(self, l) } - fn visit_block(&mut self, b: &'v Block) { + fn visit_block(&mut self, b: &'v Block<'v>) { walk_block(self, b) } - fn visit_stmt(&mut self, s: &'v Stmt) { + fn visit_stmt(&mut self, s: &'v Stmt<'v>) { walk_stmt(self, s) } - fn visit_arm(&mut self, a: &'v Arm) { + fn visit_arm(&mut self, a: &'v Arm<'v>) { walk_arm(self, a) } - fn visit_pat(&mut self, p: &'v Pat) { + fn visit_pat(&mut self, p: &'v Pat<'v>) { walk_pat(self, p) } fn visit_anon_const(&mut self, c: &'v AnonConst) { walk_anon_const(self, c) } - fn visit_expr(&mut self, ex: &'v Expr) { + fn visit_expr(&mut self, ex: &'v Expr<'v>) { walk_expr(self, ex) } - fn visit_ty(&mut self, t: &'v Ty) { + fn visit_ty(&mut self, t: &'v Ty<'v>) { walk_ty(self, t) } - fn visit_generic_param(&mut self, p: &'v GenericParam) { + fn visit_generic_param(&mut self, p: &'v GenericParam<'v>) { walk_generic_param(self, p) } - fn visit_generics(&mut self, g: &'v Generics) { + fn visit_generics(&mut self, g: &'v Generics<'v>) { walk_generics(self, g) } - fn visit_where_predicate(&mut self, predicate: &'v WherePredicate) { + fn visit_where_predicate(&mut self, predicate: &'v WherePredicate<'v>) { walk_where_predicate(self, predicate) } - fn visit_fn_decl(&mut self, fd: &'v FnDecl) { + fn visit_fn_decl(&mut self, fd: &'v FnDecl<'v>) { walk_fn_decl(self, fd) } - fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl, b: BodyId, s: Span, id: HirId) { + fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl<'v>, b: BodyId, s: Span, id: HirId) { walk_fn(self, fk, fd, b, s, id) } - fn visit_use(&mut self, path: &'v Path, hir_id: HirId) { + fn visit_use(&mut self, path: &'v Path<'v>, hir_id: HirId) { walk_use(self, path, hir_id) } - fn visit_trait_item(&mut self, ti: &'v TraitItem) { + fn visit_trait_item(&mut self, ti: &'v TraitItem<'v>) { walk_trait_item(self, ti) } fn visit_trait_item_ref(&mut self, ii: &'v TraitItemRef) { walk_trait_item_ref(self, ii) } - fn visit_impl_item(&mut self, ii: &'v ImplItem) { + fn visit_impl_item(&mut self, ii: &'v ImplItem<'v>) { walk_impl_item(self, ii) } - fn visit_impl_item_ref(&mut self, ii: &'v ImplItemRef) { + fn visit_impl_item_ref(&mut self, ii: &'v ImplItemRef<'v>) { walk_impl_item_ref(self, ii) } - fn visit_trait_ref(&mut self, t: &'v TraitRef) { + fn visit_trait_ref(&mut self, t: &'v TraitRef<'v>) { walk_trait_ref(self, t) } - fn visit_param_bound(&mut self, bounds: &'v GenericBound) { + fn visit_param_bound(&mut self, bounds: &'v GenericBound<'v>) { walk_param_bound(self, bounds) } - fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef, m: TraitBoundModifier) { + fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef<'v>, m: TraitBoundModifier) { walk_poly_trait_ref(self, t, m) } fn visit_variant_data(&mut self, - s: &'v VariantData, + s: &'v VariantData<'v>, _: Name, - _: &'v Generics, + _: &'v Generics<'v>, _parent_id: HirId, _: Span) { walk_struct_def(self, s) } - fn visit_struct_field(&mut self, s: &'v StructField) { + fn visit_struct_field(&mut self, s: &'v StructField<'v>) { walk_struct_field(self, s) } fn visit_enum_def(&mut self, enum_definition: &'v EnumDef, - generics: &'v Generics, + generics: &'v Generics<'v>, item_id: HirId, _: Span) { walk_enum_def(self, enum_definition, generics, item_id) } - fn visit_variant(&mut self, v: &'v Variant, g: &'v Generics, item_id: HirId) { + fn visit_variant(&mut self, v: &'v Variant<'v>, g: &'v Generics<'v>, item_id: HirId) { walk_variant(self, v, g, item_id) } fn visit_label(&mut self, label: &'v Label) { walk_label(self, label) } - fn visit_generic_arg(&mut self, generic_arg: &'v GenericArg) { + fn visit_generic_arg(&mut self, generic_arg: &'v GenericArg<'v>) { match generic_arg { GenericArg::Lifetime(lt) => self.visit_lifetime(lt), GenericArg::Type(ty) => self.visit_ty(ty), @@ -347,21 +347,21 @@ pub trait Visitor<'v> : Sized { fn visit_qpath(&mut self, qpath: &'v QPath, id: HirId, span: Span) { walk_qpath(self, qpath, id, span) } - fn visit_path(&mut self, path: &'v Path, _id: HirId) { + fn visit_path(&mut self, path: &'v Path<'v>, _id: HirId) { walk_path(self, path) } - fn visit_path_segment(&mut self, path_span: Span, path_segment: &'v PathSegment) { + fn visit_path_segment(&mut self, path_span: Span, path_segment: &'v PathSegment<'v>) { walk_path_segment(self, path_span, path_segment) } - fn visit_generic_args(&mut self, path_span: Span, generic_args: &'v GenericArgs) { + fn visit_generic_args(&mut self, path_span: Span, generic_args: &'v GenericArgs<'v>) { walk_generic_args(self, path_span, generic_args) } - fn visit_assoc_type_binding(&mut self, type_binding: &'v TypeBinding) { + fn visit_assoc_type_binding(&mut self, type_binding: &'v TypeBinding<'v>) { walk_assoc_type_binding(self, type_binding) } fn visit_attribute(&mut self, _attr: &'v Attribute) { } - fn visit_macro_def(&mut self, macro_def: &'v MacroDef) { + fn visit_macro_def(&mut self, macro_def: &'v MacroDef<'v>) { walk_macro_def(self, macro_def) } fn visit_vis(&mut self, vis: &'v Visibility) { @@ -376,26 +376,26 @@ pub trait Visitor<'v> : Sized { } /// Walks the contents of a crate. See also `Crate::visit_all_items`. -pub fn walk_crate<'v, V: Visitor<'v>>(visitor: &mut V, krate: &'v Crate) { +pub fn walk_crate<'v, V: Visitor<'v>>(visitor: &mut V, krate: &'v Crate<'v>) { visitor.visit_mod(&krate.module, krate.span, CRATE_HIR_ID); walk_list!(visitor, visit_attribute, &krate.attrs); walk_list!(visitor, visit_macro_def, &krate.exported_macros); } -pub fn walk_macro_def<'v, V: Visitor<'v>>(visitor: &mut V, macro_def: &'v MacroDef) { +pub fn walk_macro_def<'v, V: Visitor<'v>>(visitor: &mut V, macro_def: &'v MacroDef<'v>) { visitor.visit_id(macro_def.hir_id); visitor.visit_name(macro_def.span, macro_def.name); walk_list!(visitor, visit_attribute, ¯o_def.attrs); } -pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod, mod_hir_id: HirId) { +pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod<'v>, mod_hir_id: HirId) { visitor.visit_id(mod_hir_id); for &item_id in &module.item_ids { visitor.visit_nested_item(item_id); } } -pub fn walk_body<'v, V: Visitor<'v>>(visitor: &mut V, body: &'v Body) { +pub fn walk_body<'v, V: Visitor<'v>>(visitor: &mut V, body: &'v Body<'v>) { for argument in &body.arguments { visitor.visit_id(argument.hir_id); visitor.visit_pat(&argument.pat); @@ -403,7 +403,7 @@ pub fn walk_body<'v, V: Visitor<'v>>(visitor: &mut V, body: &'v Body) { visitor.visit_expr(&body.value); } -pub fn walk_local<'v, V: Visitor<'v>>(visitor: &mut V, local: &'v Local) { +pub fn walk_local<'v, V: Visitor<'v>>(visitor: &mut V, local: &'v Local<'v>) { // Intentionally visiting the expr first - the initialization expr // dominates the local's definition. walk_list!(visitor, visit_expr, &local.init); @@ -437,7 +437,7 @@ pub fn walk_lifetime<'v, V: Visitor<'v>>(visitor: &mut V, lifetime: &'v Lifetime } pub fn walk_poly_trait_ref<'v, V>(visitor: &mut V, - trait_ref: &'v PolyTraitRef, + trait_ref: &'v PolyTraitRef<'v>, _modifier: TraitBoundModifier) where V: Visitor<'v> { @@ -445,14 +445,14 @@ pub fn walk_poly_trait_ref<'v, V>(visitor: &mut V, visitor.visit_trait_ref(&trait_ref.trait_ref); } -pub fn walk_trait_ref<'v, V>(visitor: &mut V, trait_ref: &'v TraitRef) +pub fn walk_trait_ref<'v, V>(visitor: &mut V, trait_ref: &'v TraitRef<'v>) where V: Visitor<'v> { visitor.visit_id(trait_ref.hir_ref_id); visitor.visit_path(&trait_ref.path, trait_ref.hir_ref_id) } -pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { +pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) { visitor.visit_vis(&item.vis); visitor.visit_ident(item.ident); match item.node { @@ -548,15 +548,15 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { } pub fn walk_use<'v, V: Visitor<'v>>(visitor: &mut V, - path: &'v Path, + path: &'v Path<'v>, hir_id: HirId) { visitor.visit_id(hir_id); visitor.visit_path(path, hir_id); } pub fn walk_enum_def<'v, V: Visitor<'v>>(visitor: &mut V, - enum_definition: &'v EnumDef, - generics: &'v Generics, + enum_definition: &'v EnumDef<'v>, + generics: &'v Generics<'v>, item_id: HirId) { visitor.visit_id(item_id); walk_list!(visitor, @@ -567,8 +567,8 @@ pub fn walk_enum_def<'v, V: Visitor<'v>>(visitor: &mut V, } pub fn walk_variant<'v, V: Visitor<'v>>(visitor: &mut V, - variant: &'v Variant, - generics: &'v Generics, + variant: &'v Variant<'v>, + generics: &'v Generics<'v>, parent_item_id: HirId) { visitor.visit_ident(variant.node.ident); visitor.visit_id(variant.node.id); @@ -630,7 +630,12 @@ pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty) { } } -pub fn walk_qpath<'v, V: Visitor<'v>>(visitor: &mut V, qpath: &'v QPath, id: HirId, span: Span) { +pub fn walk_qpath<'v, V: Visitor<'v>>( + visitor: &mut V, + qpath: &'v QPath<'v>, + id: HirId, + span: Span +) { match *qpath { QPath::Resolved(ref maybe_qself, ref path) => { if let Some(ref qself) = *maybe_qself { @@ -645,7 +650,7 @@ pub fn walk_qpath<'v, V: Visitor<'v>>(visitor: &mut V, qpath: &'v QPath, id: Hir } } -pub fn walk_path<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path) { +pub fn walk_path<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path<'v>) { for segment in &path.segments { visitor.visit_path_segment(path.span, segment); } @@ -653,7 +658,7 @@ pub fn walk_path<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path) { pub fn walk_path_segment<'v, V: Visitor<'v>>(visitor: &mut V, path_span: Span, - segment: &'v PathSegment) { + segment: &'v PathSegment<'v>) { visitor.visit_ident(segment.ident); if let Some(id) = segment.hir_id { visitor.visit_id(id); @@ -665,13 +670,13 @@ pub fn walk_path_segment<'v, V: Visitor<'v>>(visitor: &mut V, pub fn walk_generic_args<'v, V: Visitor<'v>>(visitor: &mut V, _path_span: Span, - generic_args: &'v GenericArgs) { + generic_args: &'v GenericArgs<'v>) { walk_list!(visitor, visit_generic_arg, &generic_args.args); walk_list!(visitor, visit_assoc_type_binding, &generic_args.bindings); } pub fn walk_assoc_type_binding<'v, V: Visitor<'v>>(visitor: &mut V, - type_binding: &'v TypeBinding) { + type_binding: &'v TypeBinding<'v>) { visitor.visit_id(type_binding.hir_id); visitor.visit_ident(type_binding.ident); match type_binding.kind { @@ -684,7 +689,7 @@ pub fn walk_assoc_type_binding<'v, V: Visitor<'v>>(visitor: &mut V, } } -pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat) { +pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat<'v>) { visitor.visit_id(pattern.hir_id); match pattern.node { PatKind::TupleStruct(ref qpath, ref children, _) => { @@ -727,7 +732,7 @@ pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat) { } } -pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, foreign_item: &'v ForeignItem) { +pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, foreign_item: &'v ForeignItem<'v>) { visitor.visit_id(foreign_item.hir_id); visitor.visit_vis(&foreign_item.vis); visitor.visit_ident(foreign_item.ident); @@ -747,7 +752,7 @@ pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, foreign_item: &'v walk_list!(visitor, visit_attribute, &foreign_item.attrs); } -pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v GenericBound) { +pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v GenericBound<'v>) { match *bound { GenericBound::Trait(ref typ, modifier) => { visitor.visit_poly_trait_ref(typ, modifier); @@ -756,7 +761,7 @@ pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v GenericB } } -pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v GenericParam) { +pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v GenericParam<'v>) { visitor.visit_id(param.hir_id); walk_list!(visitor, visit_attribute, ¶m.attrs); match param.name { @@ -771,7 +776,7 @@ pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v Generi walk_list!(visitor, visit_param_bound, ¶m.bounds); } -pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics) { +pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics<'v>) { walk_list!(visitor, visit_generic_param, &generics.params); visitor.visit_id(generics.where_clause.hir_id); walk_list!(visitor, visit_where_predicate, &generics.where_clause.predicates); @@ -807,13 +812,13 @@ pub fn walk_where_predicate<'v, V: Visitor<'v>>( } } -pub fn walk_fn_ret_ty<'v, V: Visitor<'v>>(visitor: &mut V, ret_ty: &'v FunctionRetTy) { +pub fn walk_fn_ret_ty<'v, V: Visitor<'v>>(visitor: &mut V, ret_ty: &'v FunctionRetTy<'v>) { if let Return(ref output_ty) = *ret_ty { visitor.visit_ty(output_ty) } } -pub fn walk_fn_decl<'v, V: Visitor<'v>>(visitor: &mut V, function_declaration: &'v FnDecl) { +pub fn walk_fn_decl<'v, V: Visitor<'v>>(visitor: &mut V, function_declaration: &'v FnDecl<'v>) { for ty in &function_declaration.inputs { visitor.visit_ty(ty) } @@ -842,7 +847,7 @@ pub fn walk_fn<'v, V: Visitor<'v>>(visitor: &mut V, visitor.visit_nested_body(body_id) } -pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v TraitItem) { +pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v TraitItem<'v>) { visitor.visit_ident(trait_item.ident); walk_list!(visitor, visit_attribute, &trait_item.attrs); visitor.visit_generics(&trait_item.generics); @@ -886,7 +891,7 @@ pub fn walk_trait_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, trait_item_ref: visitor.visit_defaultness(defaultness); } -pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplItem) { +pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplItem<'v>) { // N.B., deliberately force a compilation error if/when new fields are added. let ImplItem { hir_id: _, @@ -931,7 +936,7 @@ pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplIt } } -pub fn walk_impl_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, impl_item_ref: &'v ImplItemRef) { +pub fn walk_impl_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, impl_item_ref: &'v ImplItemRef<'v>) { // N.B., deliberately force a compilation error if/when new fields are added. let ImplItemRef { id, ident, ref kind, span: _, ref vis, ref defaultness } = *impl_item_ref; visitor.visit_nested_impl_item(id); @@ -941,14 +946,17 @@ pub fn walk_impl_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, impl_item_ref: &' visitor.visit_defaultness(defaultness); } -pub fn walk_struct_def<'v, V: Visitor<'v>>(visitor: &mut V, struct_definition: &'v VariantData) { +pub fn walk_struct_def<'v, V: Visitor<'v>>( + visitor: &mut V, + struct_definition: &'v VariantData<'v> +) { if let Some(ctor_hir_id) = struct_definition.ctor_hir_id() { visitor.visit_id(ctor_hir_id); } walk_list!(visitor, visit_struct_field, struct_definition.fields()); } -pub fn walk_struct_field<'v, V: Visitor<'v>>(visitor: &mut V, struct_field: &'v StructField) { +pub fn walk_struct_field<'v, V: Visitor<'v>>(visitor: &mut V, struct_field: &'v StructField<'v>) { visitor.visit_id(struct_field.hir_id); visitor.visit_vis(&struct_field.vis); visitor.visit_ident(struct_field.ident); @@ -956,13 +964,13 @@ pub fn walk_struct_field<'v, V: Visitor<'v>>(visitor: &mut V, struct_field: &'v walk_list!(visitor, visit_attribute, &struct_field.attrs); } -pub fn walk_block<'v, V: Visitor<'v>>(visitor: &mut V, block: &'v Block) { +pub fn walk_block<'v, V: Visitor<'v>>(visitor: &mut V, block: &'v Block<'v>) { visitor.visit_id(block.hir_id); walk_list!(visitor, visit_stmt, &block.stmts); walk_list!(visitor, visit_expr, &block.expr); } -pub fn walk_stmt<'v, V: Visitor<'v>>(visitor: &mut V, statement: &'v Stmt) { +pub fn walk_stmt<'v, V: Visitor<'v>>(visitor: &mut V, statement: &'v Stmt<'v>) { visitor.visit_id(statement.hir_id); match statement.node { StmtKind::Local(ref local) => visitor.visit_local(local), @@ -979,7 +987,7 @@ pub fn walk_anon_const<'v, V: Visitor<'v>>(visitor: &mut V, constant: &'v AnonCo visitor.visit_nested_body(constant.body); } -pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) { +pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>) { visitor.visit_id(expression.hir_id); walk_list!(visitor, visit_attribute, expression.attrs.iter()); match expression.node { @@ -1096,7 +1104,7 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) { } } -pub fn walk_arm<'v, V: Visitor<'v>>(visitor: &mut V, arm: &'v Arm) { +pub fn walk_arm<'v, V: Visitor<'v>>(visitor: &mut V, arm: &'v Arm<'v>) { visitor.visit_id(arm.hir_id); walk_list!(visitor, visit_pat, &arm.pats); if let Some(ref g) = arm.guard { @@ -1108,7 +1116,7 @@ pub fn walk_arm<'v, V: Visitor<'v>>(visitor: &mut V, arm: &'v Arm) { walk_list!(visitor, visit_attribute, &arm.attrs); } -pub fn walk_vis<'v, V: Visitor<'v>>(visitor: &mut V, vis: &'v Visibility) { +pub fn walk_vis<'v, V: Visitor<'v>>(visitor: &mut V, vis: &'v Visibility<'v>) { if let VisibilityKind::Restricted { ref path, hir_id } = vis.node { visitor.visit_id(hir_id); visitor.visit_path(path, hir_id) diff --git a/src/librustc/hir/itemlikevisit.rs b/src/librustc/hir/itemlikevisit.rs index bfc9e8f06e235..64dbe15451d5c 100644 --- a/src/librustc/hir/itemlikevisit.rs +++ b/src/librustc/hir/itemlikevisit.rs @@ -46,9 +46,9 @@ use super::intravisit::Visitor; /// existing `fn visit_nested` methods to see where changes are /// needed. pub trait ItemLikeVisitor<'hir> { - fn visit_item(&mut self, item: &'hir Item); - fn visit_trait_item(&mut self, trait_item: &'hir TraitItem); - fn visit_impl_item(&mut self, impl_item: &'hir ImplItem); + fn visit_item(&mut self, item: &'hir Item<'hir>); + fn visit_trait_item(&mut self, trait_item: &'hir TraitItem<'hir>); + fn visit_impl_item(&mut self, impl_item: &'hir ImplItem<'hir>); } pub struct DeepVisitor<'v, V: 'v> { diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 5a548ce8d9ff4..55a09f2705a2c 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -32,13 +32,15 @@ //! get confused if the spans from leaf AST nodes occur in multiple places //! in the HIR, especially for multiple identifiers. +use crate::arena::Arena; use crate::dep_graph::DepGraph; use crate::hir::{self, ParamName}; -use crate::hir::HirVec; +use crate::hir::{HirVec, ThinHirVec}; use crate::hir::map::{DefKey, DefPathData, Definitions}; use crate::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX}; use crate::hir::def::{Res, DefKind, PartialRes, PerNS}; use crate::hir::{GenericArg, ConstArg}; +use crate::hir::ptr::{P, IteratorExt}; use crate::lint::builtin::{self, PARENTHESIZED_PARAMS_IN_TYPES_AND_MODULES, ELIDED_LIFETIMES_IN_PATHS}; use crate::middle::cstore::CrateStore; @@ -49,7 +51,6 @@ use crate::util::nodemap::{DefIdMap, NodeMap}; use errors::Applicability; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::indexed_vec::IndexVec; -use rustc_data_structures::thin_vec::ThinVec; use rustc_data_structures::sync::Lrc; use std::collections::{BTreeSet, BTreeMap}; @@ -61,7 +62,6 @@ use syntax::ast::*; use syntax::errors; use syntax::ext::hygiene::{Mark, SyntaxContext}; use syntax::print::pprust; -use syntax::ptr::P; use syntax::source_map::{self, respan, CompilerDesugaringKind, Spanned}; use syntax::source_map::CompilerDesugaringKind::IfTemporary; use syntax::std_inject; @@ -73,7 +73,31 @@ use syntax_pos::{DUMMY_SP, edition, Span}; const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF; -pub struct LoweringContext<'a> { +macro_rules! p { + ($this:expr, $e:expr) => ({ + P::alloc($this.arena, $e) + }) +} + +macro_rules! hir_vec { + ($this:expr; $elem:expr; $n:expr) => ( + $crate::hir::HirVec::from_slice($this.arena, &[$elem; $n]) + ); + ($this:expr; $($x:expr),*) => ( + $crate::hir::HirVec::from_slice($this.arena, &[$($x),*]) + ); + () => ( + $crate::hir::HirVec::new() + ); +} + +macro_rules! thin_hir_vec { + () => ( + P::empty_thin() + ); +} + +pub struct LoweringContext<'r, 'a> { crate_root: Option, /// Used to assign ids to HIR nodes that do not directly correspond to an AST node. @@ -81,15 +105,17 @@ pub struct LoweringContext<'a> { cstore: &'a dyn CrateStore, - resolver: &'a mut dyn Resolver, + arena: &'a Arena<'a>, + + resolver: &'r mut dyn Resolver<'a>, /// The items being lowered are collected here. - items: BTreeMap, + items: BTreeMap>, - trait_items: BTreeMap, - impl_items: BTreeMap, - bodies: BTreeMap, - exported_macros: Vec, + trait_items: BTreeMap>, + impl_items: BTreeMap>, + bodies: BTreeMap>, + exported_macros: Vec>, trait_impls: BTreeMap>, @@ -144,13 +170,14 @@ pub struct LoweringContext<'a> { node_id_to_hir_id: IndexVec, } -pub trait Resolver { +pub trait Resolver<'hir> { /// Resolve a path generated by the lowerer when expanding `for`, `if let`, etc. fn resolve_hir_path( &mut self, + arena: &'hir Arena<'hir>, path: &ast::Path, is_value: bool, - ) -> hir::Path; + ) -> hir::Path<'hir>; /// Obtain resolution for a `NodeId` with a single resolution. fn get_partial_res(&mut self, id: NodeId) -> Option; @@ -169,23 +196,24 @@ pub trait Resolver { /// resolves it based on `is_value`. fn resolve_str_path( &mut self, + arena: &'hir Arena<'hir>, span: Span, crate_root: Option, components: &[Symbol], is_value: bool, - ) -> hir::Path; + ) -> hir::Path<'hir>; } /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree, /// and if so, what meaning it has. #[derive(Debug)] -enum ImplTraitContext<'a> { +enum ImplTraitContext<'a, 'hir> { /// Treat `impl Trait` as shorthand for a new universal generic parameter. /// Example: `fn foo(x: impl Debug)`, where `impl Debug` is conceptually /// equivalent to a fresh universal parameter like `fn foo(x: T)`. /// /// Newly generated parameters should be inserted into the given `Vec`. - Universal(&'a mut Vec), + Universal(&'a mut Vec>), /// Treat `impl Trait` as shorthand for a new existential parameter. /// Example: `fn foo() -> impl Debug`, where `impl Debug` is conceptually @@ -210,13 +238,13 @@ enum ImplTraitPosition { Other, } -impl<'a> ImplTraitContext<'a> { +impl<'a, 'hir> ImplTraitContext<'a, 'hir> { #[inline] fn disallowed() -> Self { ImplTraitContext::Disallowed(ImplTraitPosition::Other) } - fn reborrow(&'b mut self) -> ImplTraitContext<'b> { + fn reborrow(&'b mut self) -> ImplTraitContext<'b, 'hir> { use self::ImplTraitContext::*; match self { Universal(params) => Universal(params), @@ -226,19 +254,21 @@ impl<'a> ImplTraitContext<'a> { } } -pub fn lower_crate( - sess: &Session, - cstore: &dyn CrateStore, +pub fn lower_crate<'a>( + sess: &'a Session, + cstore: &'a dyn CrateStore, + arena: &'a Arena<'a>, dep_graph: &DepGraph, krate: &Crate, - resolver: &mut dyn Resolver, -) -> hir::Crate { + resolver: &mut dyn Resolver<'a>, +) -> hir::Crate<'a> { // 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. dep_graph.assert_ignored(); LoweringContext { + arena, crate_root: std_inject::injected_crate_name().map(Symbol::intern), sess, cstore, @@ -408,19 +438,19 @@ impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> { } } -impl<'a> LoweringContext<'a> { - fn lower_crate(mut self, c: &Crate) -> hir::Crate { +impl<'a> LoweringContext<'_, 'a> { + fn lower_crate(mut self, c: &Crate) -> hir::Crate<'a> { /// Full-crate AST visitor that inserts into a fresh /// `LoweringContext` any information that may be /// needed from arbitrary locations in the crate, /// e.g., the number of lifetime generic parameters /// declared for every type and trait definition. - struct MiscCollector<'tcx, 'interner: 'tcx> { - lctx: &'tcx mut LoweringContext<'interner>, + struct MiscCollector<'l, 'tcx, 'interner> { + lctx: &'l mut LoweringContext<'tcx, 'interner>, hir_id_owner: Option, } - impl MiscCollector<'_, '_> { + impl MiscCollector<'_, '_, '_> { fn allocate_use_tree_hir_id_counters( &mut self, tree: &UseTree, @@ -460,8 +490,8 @@ impl<'a> LoweringContext<'a> { } } - impl<'tcx, 'interner> Visitor<'tcx> for MiscCollector<'tcx, 'interner> { - fn visit_pat(&mut self, p: &'tcx Pat) { + impl<'a, 'l, 'tcx, 'interner> Visitor<'a> for MiscCollector<'l, 'tcx, 'interner> { + fn visit_pat(&mut self, p: &'a Pat) { match p.node { // Doesn't generate a HIR node PatKind::Paren(..) => {}, @@ -475,7 +505,7 @@ impl<'a> LoweringContext<'a> { visit::walk_pat(self, p) } - fn visit_item(&mut self, item: &'tcx Item) { + fn visit_item(&mut self, item: &'a Item) { let hir_id = self.lctx.allocate_hir_id_counter(item.id); match item.node { @@ -507,7 +537,7 @@ impl<'a> LoweringContext<'a> { }); } - fn visit_trait_item(&mut self, item: &'tcx TraitItem) { + fn visit_trait_item(&mut self, item: &'a TraitItem) { self.lctx.allocate_hir_id_counter(item.id); match item.node { @@ -523,21 +553,21 @@ impl<'a> LoweringContext<'a> { } } - fn visit_impl_item(&mut self, item: &'tcx ImplItem) { + fn visit_impl_item(&mut self, item: &'a ImplItem) { self.lctx.allocate_hir_id_counter(item.id); self.with_hir_id_owner(Some(item.id), |this| { visit::walk_impl_item(this, item); }); } - fn visit_foreign_item(&mut self, i: &'tcx ForeignItem) { + fn visit_foreign_item(&mut self, i: &'a ForeignItem) { // Ignore patterns in foreign items self.with_hir_id_owner(None, |this| { visit::walk_foreign_item(this, i) }); } - fn visit_ty(&mut self, t: &'tcx Ty) { + fn visit_ty(&mut self, t: &'a Ty) { match t.node { // Mirrors the case in visit::walk_ty TyKind::BareFn(ref f) => { @@ -561,11 +591,11 @@ impl<'a> LoweringContext<'a> { } } - struct ItemLowerer<'tcx, 'interner: 'tcx> { - lctx: &'tcx mut LoweringContext<'interner>, + struct ItemLowerer<'l, 'tcx, 'interner: 'tcx> { + lctx: &'l mut LoweringContext<'tcx, 'interner>, } - impl<'tcx, 'interner> ItemLowerer<'tcx, 'interner> { + impl<'l, 'tcx, 'interner> ItemLowerer<'l, 'tcx, 'interner> { fn with_trait_impl_ref(&mut self, trait_impl_ref: &Option, f: F) where F: FnOnce(&mut Self), @@ -581,8 +611,8 @@ impl<'a> LoweringContext<'a> { } } - impl<'tcx, 'interner> Visitor<'tcx> for ItemLowerer<'tcx, 'interner> { - fn visit_mod(&mut self, m: &'tcx Mod, _s: Span, _attrs: &[Attribute], n: NodeId) { + impl<'a, 'l, 'tcx, 'interner> Visitor<'a> for ItemLowerer<'l, 'tcx, 'interner> { + fn visit_mod(&mut self, m: &'a Mod, _s: Span, _attrs: &[Attribute], n: NodeId) { self.lctx.modules.insert(n, hir::ModuleItems { items: BTreeSet::new(), trait_items: BTreeSet::new(), @@ -595,7 +625,7 @@ impl<'a> LoweringContext<'a> { self.lctx.current_module = old; } - fn visit_item(&mut self, item: &'tcx Item) { + fn visit_item(&mut self, item: &'a Item) { let mut item_hir_id = None; self.lctx.with_hir_id_owner(item.id, |lctx| { if let Some(hir_item) = lctx.lower_item(item) { @@ -626,7 +656,7 @@ impl<'a> LoweringContext<'a> { } } - fn visit_trait_item(&mut self, item: &'tcx TraitItem) { + fn visit_trait_item(&mut self, item: &'a TraitItem) { self.lctx.with_hir_id_owner(item.id, |lctx| { let hir_item = lctx.lower_trait_item(item); let id = hir::TraitItemId { hir_id: hir_item.hir_id }; @@ -637,7 +667,7 @@ impl<'a> LoweringContext<'a> { visit::walk_trait_item(self, item); } - fn visit_impl_item(&mut self, item: &'tcx ImplItem) { + fn visit_impl_item(&mut self, item: &'a ImplItem) { self.lctx.with_hir_id_owner(item.id, |lctx| { let hir_item = lctx.lower_impl_item(item); let id = hir::ImplItemId { hir_id: hir_item.hir_id }; @@ -666,7 +696,7 @@ impl<'a> LoweringContext<'a> { module, attrs, span: c.span, - exported_macros: hir::HirVec::from(self.exported_macros), + exported_macros: P::from_slice(self.arena, &self.exported_macros), items: self.items, trait_items: self.trait_items, impl_items: self.impl_items, @@ -677,7 +707,7 @@ impl<'a> LoweringContext<'a> { } } - fn insert_item(&mut self, item: hir::Item) { + fn insert_item(&mut self, item: hir::Item<'a>) { let id = item.hir_id; // FIXME: Use `debug_asset-rt`. assert_eq!(id.local_id, hir::ItemLocalId::from_u32(0)); @@ -790,7 +820,11 @@ impl<'a> LoweringContext<'a> { }) } - fn record_body(&mut self, arguments: HirVec, value: hir::Expr) -> hir::BodyId { + fn record_body( + &mut self, + arguments: HirVec<'a, hir::Arg<'a>>, + value: hir::Expr<'a>, + ) -> hir::BodyId { if self.is_generator && self.is_async_body { span_err!( self.sess, @@ -885,9 +919,9 @@ impl<'a> LoweringContext<'a> { parent_id: DefId, anonymous_lifetime_mode: AnonymousLifetimeMode, f: F, - ) -> (Vec, T) + ) -> (Vec>, T) where - F: FnOnce(&mut LoweringContext<'_>) -> (Vec, T), + F: FnOnce(&mut LoweringContext<'_, 'a>) -> (Vec>, T), { assert!(!self.is_collecting_in_band_lifetimes); assert!(self.lifetimes_to_define.is_empty()); @@ -920,7 +954,7 @@ impl<'a> LoweringContext<'a> { span: Span, hir_name: ParamName, parent_index: DefIndex, - ) -> hir::GenericParam { + ) -> hir::GenericParam<'a> { let node_id = self.sess.next_node_id(); // Get the name we'll use to make the def-path. Note @@ -1004,7 +1038,7 @@ impl<'a> LoweringContext<'a> { // for them. fn with_in_scope_lifetime_defs(&mut self, params: &[GenericParam], f: F) -> T where - F: FnOnce(&mut LoweringContext<'_>) -> T, + F: FnOnce(&mut LoweringContext<'_, 'a>) -> T, { let old_len = self.in_scope_lifetimes.len(); let lt_def_names = params.iter().filter_map(|param| match param.kind { @@ -1028,7 +1062,7 @@ impl<'a> LoweringContext<'a> { params: &HirVec, f: F ) -> T where - F: FnOnce(&mut LoweringContext<'_>) -> T, + F: FnOnce(&mut LoweringContext<'_, 'a>) -> T, { let old_len = self.in_scope_lifetimes.len(); let lt_def_names = params.iter().filter_map(|param| match param.kind { @@ -1055,9 +1089,9 @@ impl<'a> LoweringContext<'a> { parent_id: DefId, anonymous_lifetime_mode: AnonymousLifetimeMode, f: F, - ) -> (hir::Generics, T) + ) -> (hir::Generics<'a>, T) where - F: FnOnce(&mut LoweringContext<'_>, &mut Vec) -> T, + F: FnOnce(&mut LoweringContext<'_, 'a>, &mut Vec>) -> T, { let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs( &generics.params, @@ -1081,7 +1115,7 @@ impl<'a> LoweringContext<'a> { }, ); - lowered_generics.params = lowered_generics + let mut params: SmallVec<[_; 8]> = lowered_generics .params .iter() .cloned() @@ -1092,7 +1126,7 @@ impl<'a> LoweringContext<'a> { // unsorted generic parameters at the moment, so we make sure // that they're ordered correctly here for now. (When we chain // the `in_band_defs`, we might make the order unsorted.) - lowered_generics.params.sort_by_key(|param| { + params.sort_by_key(|param| { match param.kind { hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime, hir::GenericParamKind::Type { .. } => ParamKindOrd::Type, @@ -1100,12 +1134,14 @@ impl<'a> LoweringContext<'a> { } }); + lowered_generics.params = params.into_iter().collect_hir_vec(self.arena); + (lowered_generics, res) } fn with_catch_scope(&mut self, catch_id: NodeId, f: F) -> T where - F: FnOnce(&mut LoweringContext<'_>) -> T, + F: FnOnce(&mut LoweringContext<'_, 'a>) -> T, { let len = self.catch_scopes.len(); self.catch_scopes.push(catch_id); @@ -1128,11 +1164,11 @@ impl<'a> LoweringContext<'a> { closure_node_id: NodeId, ret_ty: Option<&Ty>, span: Span, - body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr, - ) -> hir::ExprKind { + body: impl FnOnce(&mut LoweringContext<'_, 'a>) -> hir::Expr<'a>, + ) -> hir::ExprKind<'a> { let capture_clause = self.lower_capture_clause(capture_clause); let output = match ret_ty { - Some(ty) => FunctionRetTy::Ty(P(ty.clone())), + Some(ty) => FunctionRetTy::Ty(syntax::ptr::P(ty.clone())), None => FunctionRetTy::Default(span), }; let ast_decl = FnDecl { @@ -1150,7 +1186,7 @@ impl<'a> LoweringContext<'a> { node: hir::ExprKind::Closure(capture_clause, decl, body_id, span, Some(hir::GeneratorMovability::Static)), span, - attrs: ThinVec::new(), + attrs: thin_hir_vec![], }; let unstable_span = self.mark_span_with_reason( @@ -1159,13 +1195,13 @@ impl<'a> LoweringContext<'a> { Some(vec![sym::gen_future].into()), ); let gen_future = self.expr_std_path( - unstable_span, &[sym::future, sym::from_generator], None, ThinVec::new()); - hir::ExprKind::Call(P(gen_future), hir_vec![generator]) + unstable_span, &[sym::future, sym::from_generator], None, thin_hir_vec![]); + hir::ExprKind::Call(p!(self, gen_future), hir_vec![self; generator]) } fn lower_body( &mut self, - f: impl FnOnce(&mut LoweringContext<'_>) -> (HirVec, hir::Expr), + f: impl FnOnce(&mut LoweringContext<'_, 'a>) -> (HirVec<'a, hir::Arg<'a>>, hir::Expr<'a>), ) -> hir::BodyId { let prev_is_generator = mem::replace(&mut self.is_generator, false); let prev_is_async_body = mem::replace(&mut self.is_async_body, false); @@ -1179,10 +1215,11 @@ impl<'a> LoweringContext<'a> { fn lower_fn_body( &mut self, decl: &FnDecl, - body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr, + body: impl FnOnce(&mut LoweringContext<'_, 'a>) -> hir::Expr<'a>, ) -> hir::BodyId { + let arena = self.arena; self.lower_body(|this| ( - decl.inputs.iter().map(|x| this.lower_arg(x)).collect(), + decl.inputs.iter().map(|x| this.lower_arg(x)).collect_hir_vec(arena), body(this), )) } @@ -1193,7 +1230,7 @@ impl<'a> LoweringContext<'a> { fn with_loop_scope(&mut self, loop_id: NodeId, f: F) -> T where - F: FnOnce(&mut LoweringContext<'_>) -> T, + F: FnOnce(&mut LoweringContext<'_, 'a>) -> 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; @@ -1218,7 +1255,7 @@ impl<'a> LoweringContext<'a> { fn with_loop_condition_scope(&mut self, f: F) -> T where - F: FnOnce(&mut LoweringContext<'_>) -> T, + F: FnOnce(&mut LoweringContext<'_, 'a>) -> T, { let was_in_loop_condition = self.is_in_loop_condition; self.is_in_loop_condition = true; @@ -1232,7 +1269,7 @@ impl<'a> LoweringContext<'a> { fn with_dyn_type_scope(&mut self, in_scope: bool, f: F) -> T where - F: FnOnce(&mut LoweringContext<'_>) -> T, + F: FnOnce(&mut LoweringContext<'_, 'a>) -> T, { let was_in_dyn_type = self.is_in_dyn_type; self.is_in_dyn_type = in_scope; @@ -1246,7 +1283,7 @@ impl<'a> LoweringContext<'a> { fn with_new_scopes(&mut self, f: F) -> T where - F: FnOnce(&mut LoweringContext<'_>) -> T, + F: FnOnce(&mut LoweringContext<'_, 'a>) -> T, { let was_in_loop_condition = self.is_in_loop_condition; self.is_in_loop_condition = false; @@ -1300,11 +1337,22 @@ impl<'a> LoweringContext<'a> { } } - fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec { - attrs - .iter() - .map(|a| self.lower_attr(a)) - .collect() + fn copy_attrs>( + &mut self, + attrs: I + ) -> hir::ThinHirVec<'a, Attribute> { + let vec = P::from_existing(self.arena.alloc_from_iter(attrs)); + if vec.is_empty() { + P::empty_thin() + } else { + P::alloc(self.arena, vec) + } + } + + fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec<'a, Attribute> { + P::from_existing( + self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a))) + ) } fn lower_attr(&mut self, attr: &Attribute) -> Attribute { @@ -1349,16 +1397,17 @@ impl<'a> LoweringContext<'a> { } } - fn lower_arm(&mut self, arm: &Arm) -> hir::Arm { + fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'a> { + let arena = self.arena; hir::Arm { hir_id: self.next_id(), attrs: self.lower_attrs(&arm.attrs), - pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect(), + pats: arm.pats.iter().map(|x| self.lower_pat(x)).collect_hir_vec(arena), guard: match arm.guard { - Some(Guard::If(ref x)) => Some(hir::Guard::If(P(self.lower_expr(x)))), + Some(Guard::If(ref x)) => Some(hir::Guard::If(p!(self, self.lower_expr(x)))), _ => None, }, - body: P(self.lower_expr(&arm.body)), + body: p!(self, self.lower_expr(&arm.body)), span: arm.span, } } @@ -1375,8 +1424,8 @@ impl<'a> LoweringContext<'a> { /// returns a `hir::TypeBinding` representing `Item`. fn lower_assoc_ty_constraint(&mut self, c: &AssocTyConstraint, - itctx: ImplTraitContext<'_>) - -> hir::TypeBinding { + itctx: ImplTraitContext<'_, 'a>) + -> hir::TypeBinding<'a> { debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", c, itctx); let kind = match c.kind { @@ -1473,8 +1522,8 @@ impl<'a> LoweringContext<'a> { fn lower_generic_arg(&mut self, arg: &ast::GenericArg, - itctx: ImplTraitContext<'_>) - -> hir::GenericArg { + itctx: ImplTraitContext<'_, 'a>) + -> hir::GenericArg<'a> { match arg { ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)), ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)), @@ -1487,8 +1536,8 @@ impl<'a> LoweringContext<'a> { } } - fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_>) -> P { - P(self.lower_ty_direct(t, itctx)) + fn lower_ty(&mut self, t: &Ty, itctx: ImplTraitContext<'_, 'a>) -> P<'a, hir::Ty<'a>> { + p!(self, self.lower_ty_direct(t, itctx)) } fn lower_path_ty( @@ -1497,8 +1546,8 @@ impl<'a> LoweringContext<'a> { qself: &Option, path: &Path, param_mode: ParamMode, - itctx: ImplTraitContext<'_> - ) -> hir::Ty { + itctx: ImplTraitContext<'_, 'a> + ) -> hir::Ty<'a> { let id = self.lower_node_id(t.id); let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx); let ty = self.ty_path(id, t.span, qpath); @@ -1508,7 +1557,8 @@ impl<'a> LoweringContext<'a> { ty } - fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_>) -> hir::Ty { + fn lower_ty_direct(&mut self, t: &Ty, mut itctx: ImplTraitContext<'_, 'a>) -> hir::Ty<'a> { + let arena = self.arena; let kind = match t.node { TyKind::Infer => hir::TyKind::Infer, TyKind::Err => hir::TyKind::Err, @@ -1528,7 +1578,7 @@ impl<'a> LoweringContext<'a> { this.with_anonymous_lifetime_mode( AnonymousLifetimeMode::PassThrough, |this| { - hir::TyKind::BareFn(P(hir::BareFnTy { + hir::TyKind::BareFn(p!(this, hir::BareFnTy { generic_params: this.lower_generic_params( &f.generic_params, &NodeMap::default(), @@ -1547,7 +1597,7 @@ impl<'a> LoweringContext<'a> { TyKind::Tup(ref tys) => { hir::TyKind::Tup(tys.iter().map(|ty| { self.lower_ty_direct(ty, itctx.reborrow()) - }).collect()) + }).collect_hir_vec(arena)) } TyKind::Paren(ref ty) => { return self.lower_ty_direct(ty, itctx); @@ -1560,9 +1610,9 @@ impl<'a> LoweringContext<'a> { let res = self.lower_res(res); hir::TyKind::Path(hir::QPath::Resolved( None, - P(hir::Path { + p!(self, hir::Path { res, - segments: hir_vec![hir::PathSegment::from_ident( + segments: hir_vec![self; hir::PathSegment::from_ident( Ident::with_empty_ctxt(kw::SelfUpper) )], span: t.span, @@ -1592,7 +1642,7 @@ impl<'a> LoweringContext<'a> { None } }) - .collect(); + .collect_hir_vec(arena); let lifetime_bound = lifetime_bound.unwrap_or_else(|| this.elided_dyn_bound(t.span)); (bounds, lifetime_bound) @@ -1640,10 +1690,10 @@ impl<'a> LoweringContext<'a> { hir::TyKind::Path(hir::QPath::Resolved( None, - P(hir::Path { + p!(self, hir::Path { span, res: Res::Def(DefKind::TyParam, DefId::local(def_index)), - segments: hir_vec![hir::PathSegment::from_ident(ident)], + segments: hir_vec![self; hir::PathSegment::from_ident(ident)], }), )) } @@ -1693,8 +1743,8 @@ impl<'a> LoweringContext<'a> { span: Span, fn_def_id: Option, exist_ty_node_id: NodeId, - lower_bounds: impl FnOnce(&mut LoweringContext<'_>) -> hir::GenericBounds, - ) -> hir::TyKind { + lower_bounds: impl FnOnce(&mut LoweringContext<'_, 'a>) -> hir::GenericBounds<'a>, + ) -> hir::TyKind<'a> { // Make sure we know that some funky desugaring has been going on here. // This is a first: there is code in other places like for loop // desugaring that explicitly states that we don't want to track that. @@ -1755,7 +1805,7 @@ impl<'a> LoweringContext<'a> { fn generate_existential_type( &mut self, exist_ty_node_id: NodeId, - exist_ty_item: hir::ExistTy, + exist_ty_item: hir::ExistTy<'a>, span: Span, exist_ty_span: Span, ) -> hir::HirId { @@ -1784,29 +1834,29 @@ impl<'a> LoweringContext<'a> { exist_ty_id: NodeId, parent_index: DefIndex, bounds: &hir::GenericBounds, - ) -> (HirVec, HirVec) { + ) -> (HirVec<'a, hir::GenericArg<'a>>, HirVec<'a, hir::GenericParam<'a>>) { // This visitor walks over `impl Trait` bounds and creates defs for all lifetimes that // appear in the bounds, excluding lifetimes that are created within the bounds. // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`. - struct ImplTraitLifetimeCollector<'r, 'a: 'r> { - context: &'r mut LoweringContext<'a>, + struct ImplTraitLifetimeCollector<'l, 'r, 'a> { + context: &'l mut LoweringContext<'r, 'a>, parent: DefIndex, exist_ty_id: NodeId, collect_elided_lifetimes: bool, currently_bound_lifetimes: Vec, already_defined_lifetimes: FxHashSet, - output_lifetimes: Vec, - output_lifetime_params: Vec, + output_lifetimes: Vec>, + output_lifetime_params: Vec>, } - impl<'r, 'a: 'r, 'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a> { + impl<'v> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'_, '_, '_> { fn nested_visit_map<'this>( &'this mut self, ) -> hir::intravisit::NestedVisitorMap<'this, 'v> { hir::intravisit::NestedVisitorMap::None } - fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs) { + fn visit_generic_args(&mut self, span: Span, parameters: &'v hir::GenericArgs<'v>) { // Don't collect elided lifetimes used inside of `Fn()` syntax. if parameters.parenthesized { let old_collect_elided_lifetimes = self.collect_elided_lifetimes; @@ -1818,7 +1868,7 @@ impl<'a> LoweringContext<'a> { } } - fn visit_ty(&mut self, t: &'v hir::Ty) { + fn visit_ty(&mut self, t: &'v hir::Ty<'v>) { // Don't collect elided lifetimes used inside of `fn()` syntax. if let hir::TyKind::BareFn(_) = t.node { let old_collect_elided_lifetimes = self.collect_elided_lifetimes; @@ -1838,7 +1888,7 @@ impl<'a> LoweringContext<'a> { fn visit_poly_trait_ref( &mut self, - trait_ref: &'v hir::PolyTraitRef, + trait_ref: &'v hir::PolyTraitRef<'v>, modifier: hir::TraitBoundModifier, ) { // Record the "stack height" of `for<'a>` lifetime bindings @@ -1848,7 +1898,7 @@ impl<'a> LoweringContext<'a> { self.currently_bound_lifetimes.truncate(old_len); } - fn visit_generic_param(&mut self, param: &'v hir::GenericParam) { + fn visit_generic_param(&mut self, param: &'v hir::GenericParam<'v>) { // Record the introduction of 'a in `for<'a> ...`. if let hir::GenericParamKind::Lifetime { .. } = param.kind { // Introduce lifetimes one at a time so that we can handle @@ -1920,6 +1970,8 @@ impl<'a> LoweringContext<'a> { } } + let arena = self.arena; + let mut lifetime_collector = ImplTraitLifetimeCollector { context: self, parent: parent_index, @@ -1936,29 +1988,30 @@ impl<'a> LoweringContext<'a> { } ( - lifetime_collector.output_lifetimes.into(), - lifetime_collector.output_lifetime_params.into(), + P::from_slice(arena, &lifetime_collector.output_lifetimes), + P::from_slice(arena, &lifetime_collector.output_lifetime_params), ) } - fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod { + fn lower_foreign_mod(&mut self, fm: &ForeignMod) -> hir::ForeignMod<'a> { + let arena = self.arena; hir::ForeignMod { abi: fm.abi, items: fm.items .iter() .map(|x| self.lower_foreign_item(x)) - .collect(), + .collect_hir_vec(arena), } } - fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P { - P(hir::GlobalAsm { + fn lower_global_asm(&mut self, ga: &GlobalAsm) -> P<'a, hir::GlobalAsm> { + p!(self, hir::GlobalAsm { asm: ga.asm, ctxt: ga.ctxt, }) } - fn lower_variant(&mut self, v: &Variant) -> hir::Variant { + fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'a> { Spanned { node: hir::VariantKind { ident: v.node.ident, @@ -1977,8 +2030,9 @@ impl<'a> LoweringContext<'a> { qself: &Option, p: &Path, param_mode: ParamMode, - mut itctx: ImplTraitContext<'_>, - ) -> hir::QPath { + mut itctx: ImplTraitContext<'_, 'a>, + ) -> hir::QPath<'a> { + let arena = self.arena; let qself_position = qself.as_ref().map(|q| q.position); let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow())); @@ -1987,7 +2041,7 @@ impl<'a> LoweringContext<'a> { .unwrap_or_else(|| PartialRes::new(Res::Err)); let proj_start = p.segments.len() - partial_res.unresolved_segments(); - let path = P(hir::Path { + let path = p!(self, hir::Path { res: self.lower_res(partial_res.base_res()), segments: p.segments[..proj_start] .iter() @@ -2074,7 +2128,7 @@ impl<'a> LoweringContext<'a> { None, ) }) - .collect(), + .collect_hir_vec(arena), span: p.span, }); @@ -2094,7 +2148,7 @@ impl<'a> LoweringContext<'a> { // e.g., `Vec` in `Vec::new` or `::Item` in // `::Item::default`. let new_id = self.next_id(); - P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))) + p!(self, self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))) }; // Anything after the base path are associated "extensions", @@ -2108,7 +2162,7 @@ impl<'a> LoweringContext<'a> { // 3. `<>::IntoIter>::Item` // * final path is `<<>::IntoIter>::Item>::clone` for (i, segment) in p.segments.iter().enumerate().skip(proj_start) { - let segment = P(self.lower_path_segment( + let segment = p!(self, self.lower_path_segment( p.span, segment, param_mode, @@ -2126,7 +2180,7 @@ impl<'a> LoweringContext<'a> { // Wrap the associated extension in another type node. let new_id = self.next_id(); - ty = P(self.ty_path(new_id, p.span, qpath)); + ty = p!(self, self.ty_path(new_id, p.span, qpath)); } // We should've returned in the for loop above. @@ -2144,7 +2198,8 @@ impl<'a> LoweringContext<'a> { p: &Path, param_mode: ParamMode, explicit_owner: Option, - ) -> hir::Path { + ) -> hir::Path<'a> { + let arena = self.arena; hir::Path { res, segments: p.segments @@ -2160,12 +2215,12 @@ impl<'a> LoweringContext<'a> { explicit_owner, ) }) - .collect(), + .collect_hir_vec(arena), span: p.span, } } - fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path { + fn lower_path(&mut self, id: NodeId, p: &Path, param_mode: ParamMode) -> hir::Path<'a> { let res = self.expect_full_res(id); let res = self.lower_res(res); self.lower_path_extra(res, p, param_mode, None) @@ -2178,9 +2233,9 @@ impl<'a> LoweringContext<'a> { param_mode: ParamMode, expected_lifetimes: usize, parenthesized_generic_args: ParenthesizedGenericArgs, - itctx: ImplTraitContext<'_>, + itctx: ImplTraitContext<'_, 'a>, explicit_owner: Option, - ) -> hir::PathSegment { + ) -> hir::PathSegment<'a> { let (mut generic_args, infer_args) = if let Some(ref generic_args) = segment.args { let msg = "parenthesized type parameters may only be used with a `Fn` trait"; match **generic_args { @@ -2240,7 +2295,7 @@ impl<'a> LoweringContext<'a> { .into_iter() .map(|lt| GenericArg::Lifetime(lt)) .chain(generic_args.args.into_iter()) - .collect(); + .collect_hir_vec(self.arena); if expected_lifetimes > 0 && param_mode == ParamMode::Explicit { let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", "); let no_non_lt_args = generic_args.args.len() == expected_lifetimes; @@ -2314,6 +2369,7 @@ impl<'a> LoweringContext<'a> { ); hir::PathSegment::new( + self.arena, segment.ident, Some(id), Some(self.lower_res(res)), @@ -2326,8 +2382,9 @@ impl<'a> LoweringContext<'a> { &mut self, data: &AngleBracketedArgs, param_mode: ParamMode, - mut itctx: ImplTraitContext<'_>, - ) -> (hir::GenericArgs, bool) { + mut itctx: ImplTraitContext<'_, 'a>, + ) -> (hir::GenericArgs<'a>, bool) { + let arena = self.arena; let &AngleBracketedArgs { ref args, ref constraints, .. } = data; let has_non_lt_args = args.iter().any(|arg| match arg { ast::GenericArg::Lifetime(_) => false, @@ -2336,10 +2393,11 @@ impl<'a> LoweringContext<'a> { }); ( hir::GenericArgs { - args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(), + args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())) + .collect_hir_vec(arena), bindings: constraints.iter() .map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow())) - .collect(), + .collect_hir_vec(arena), parenthesized: false, }, !has_non_lt_args && param_mode == ParamMode::Optional @@ -2349,7 +2407,8 @@ impl<'a> LoweringContext<'a> { fn lower_parenthesized_parameter_data( &mut self, data: &ParenthesizedArgs, - ) -> (hir::GenericArgs, bool) { + ) -> (hir::GenericArgs<'a>, bool) { + let arena = self.arena; // Switch to `PassThrough` mode for anonymous lifetimes; this // means that we permit things like `&Ref`, where `Ref` has // a hidden lifetime parameter. This is needed for backwards @@ -2362,14 +2421,14 @@ impl<'a> LoweringContext<'a> { let inputs = inputs .iter() .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed())) - .collect(); + .collect_hir_vec(arena); let mk_tup = |this: &mut Self, tys, span| { hir::Ty { node: hir::TyKind::Tup(tys), hir_id: this.next_id(), span } }; ( hir::GenericArgs { - args: hir_vec![GenericArg::Type(mk_tup(this, inputs, span))], - bindings: hir_vec![ + args: hir_vec![this; GenericArg::Type(mk_tup(this, inputs, span))], + bindings: hir_vec![this; hir::TypeBinding { hir_id: this.next_id(), ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME), @@ -2381,7 +2440,7 @@ impl<'a> LoweringContext<'a> { ImplTraitContext::disallowed() )) .unwrap_or_else(|| - P(mk_tup(this, hir::HirVec::new(), span)) + p!(this, mk_tup(this, hir::HirVec::new(), span)) ), }, span: output.as_ref().map_or(span, |ty| ty.span), @@ -2395,7 +2454,7 @@ impl<'a> LoweringContext<'a> { ) } - fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) { + fn lower_local(&mut self, l: &Local) -> (hir::Local<'a>, SmallVec<[NodeId; 1]>) { let mut ids = SmallVec::<[NodeId; 1]>::new(); if self.sess.features_untracked().impl_trait_in_bindings { if let Some(ref ty) = l.ty { @@ -2416,9 +2475,9 @@ impl<'a> LoweringContext<'a> { } )), pat: self.lower_pat(&l.pat), - init: l.init.as_ref().map(|e| P(self.lower_expr(e))), + init: l.init.as_ref().map(|e| p!(self, self.lower_expr(e))), span: l.span, - attrs: l.attrs.clone(), + attrs: self.copy_attrs(l.attrs.iter().cloned()), source: hir::LocalSource::Normal, }, ids) } @@ -2430,21 +2489,21 @@ impl<'a> LoweringContext<'a> { } } - fn lower_arg(&mut self, arg: &Arg) -> hir::Arg { + fn lower_arg(&mut self, arg: &Arg) -> hir::Arg<'a> { hir::Arg { hir_id: self.lower_node_id(arg.id), pat: self.lower_pat(&arg.pat), } } - fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec { + fn lower_fn_args_to_names(&mut self, decl: &FnDecl) -> hir::HirVec<'a, Ident> { decl.inputs .iter() .map(|arg| match arg.pat.node { PatKind::Ident(_, ident, _) => ident, _ => Ident::new(kw::Invalid, arg.pat.span), }) - .collect() + .collect_hir_vec(self.arena) } // Lowers a function declaration. @@ -2462,10 +2521,11 @@ impl<'a> LoweringContext<'a> { fn lower_fn_decl( &mut self, decl: &FnDecl, - mut in_band_ty_params: Option<(DefId, &mut Vec)>, + mut in_band_ty_params: Option<(DefId, &mut Vec>)>, impl_trait_return_allow: bool, make_ret_async: Option, - ) -> P { + ) -> P<'a, hir::FnDecl<'a>> { + let arena = self.arena; let lt_mode = if make_ret_async.is_some() { // In `async fn`, argument-position elided lifetimes // must be transformed into fresh generic parameters so that @@ -2488,7 +2548,7 @@ impl<'a> LoweringContext<'a> { this.lower_ty_direct(&arg.ty, ImplTraitContext::disallowed()) } }) - .collect::>() + .collect_hir_vec(arena) }); let output = if let Some(ret_id) = make_ret_async { @@ -2519,7 +2579,7 @@ impl<'a> LoweringContext<'a> { } }; - P(hir::FnDecl { + p!(self, hir::FnDecl { inputs, output, c_variadic: decl.c_variadic, @@ -2567,8 +2627,9 @@ impl<'a> LoweringContext<'a> { fn_def_id: DefId, exist_ty_node_id: NodeId, elided_lt_replacement: LtReplacement, - ) -> hir::FunctionRetTy { + ) -> hir::FunctionRetTy<'a> { let span = output.span(); + let arena = self.arena; let exist_ty_span = self.mark_span_with_reason( CompilerDesugaringKind::Async, @@ -2613,7 +2674,7 @@ impl<'a> LoweringContext<'a> { .map(|(span, hir_name)| { this.lifetime_to_generic_param(span, hir_name, exist_ty_def_index) }) - .collect(); + .collect_hir_vec(arena); let exist_ty_item = hir::ExistTy { generics: hir::Generics { @@ -2624,7 +2685,7 @@ impl<'a> LoweringContext<'a> { }, span, }, - bounds: hir_vec![future_bound], + bounds: hir_vec![this; future_bound], impl_trait_fn: Some(fn_def_id), origin: hir::ExistTyOrigin::AsyncFn, }; @@ -2650,11 +2711,11 @@ impl<'a> LoweringContext<'a> { name: hir::LifetimeName::Param(hir_name), }) }) - .collect(); + .collect_hir_vec(arena); let exist_ty_ref = hir::TyKind::Def(hir::ItemId { id: exist_ty_id }, generic_args); - hir::FunctionRetTy::Return(P(hir::Ty { + hir::FunctionRetTy::Return(p!(self, hir::Ty { node: exist_ty_ref, span, hir_id: self.next_id(), @@ -2667,14 +2728,14 @@ impl<'a> LoweringContext<'a> { output: &FunctionRetTy, fn_def_id: DefId, span: Span, - ) -> hir::GenericBound { + ) -> hir::GenericBound<'a> { // Compute the `T` in `Future` from the return type. let output_ty = match output { FunctionRetTy::Ty(ty) => { self.lower_ty(ty, ImplTraitContext::Existential(Some(fn_def_id))) } FunctionRetTy::Default(ret_ty_span) => { - P(hir::Ty { + p!(self, hir::Ty { hir_id: self.next_id(), node: hir::TyKind::Tup(hir_vec![]), span: *ret_ty_span, @@ -2683,9 +2744,9 @@ impl<'a> LoweringContext<'a> { }; // "" - let future_params = P(hir::GenericArgs { + let future_params = p!(self, hir::GenericArgs { args: hir_vec![], - bindings: hir_vec![hir::TypeBinding { + bindings: hir_vec![self; hir::TypeBinding { ident: Ident::with_empty_ctxt(FN_OUTPUT_NAME), kind: hir::TypeBindingKind::Equality { ty: output_ty, @@ -2716,8 +2777,8 @@ impl<'a> LoweringContext<'a> { fn lower_param_bound( &mut self, tpb: &GenericBound, - itctx: ImplTraitContext<'_>, - ) -> hir::GenericBound { + itctx: ImplTraitContext<'_, 'a>, + ) -> hir::GenericBound<'a> { match *tpb { GenericBound::Trait(ref ty, modifier) => { hir::GenericBound::Trait( @@ -2812,18 +2873,19 @@ impl<'a> LoweringContext<'a> { &mut self, params: &[GenericParam], add_bounds: &NodeMap>, - mut itctx: ImplTraitContext<'_>, - ) -> hir::HirVec { + mut itctx: ImplTraitContext<'_, 'a>, + ) -> hir::HirVec<'a, hir::GenericParam<'a>> { + let arena = self.arena; params.iter().map(|param| { self.lower_generic_param(param, add_bounds, itctx.reborrow()) - }).collect() + }).collect_hir_vec(arena) } fn lower_generic_param(&mut self, param: &GenericParam, add_bounds: &NodeMap>, - mut itctx: ImplTraitContext<'_>) - -> hir::GenericParam { + mut itctx: ImplTraitContext<'_, 'a>) + -> hir::GenericParam<'a> { let mut bounds = self.with_anonymous_lifetime_mode( AnonymousLifetimeMode::ReportError, |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()), @@ -2869,7 +2931,7 @@ impl<'a> LoweringContext<'a> { let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter(); bounds = bounds.into_iter() .chain(params) - .collect(); + .collect_hir_vec(self.arena); } let kind = hir::GenericParamKind::Type { @@ -2905,8 +2967,8 @@ impl<'a> LoweringContext<'a> { fn lower_generics( &mut self, generics: &Generics, - itctx: ImplTraitContext<'_>) - -> hir::Generics + itctx: ImplTraitContext<'_, 'a>) + -> hir::Generics<'a> { // Collect `?Trait` bounds in where clause and move them to parameter definitions. // FIXME: this could probably be done with less rightward drift. It also looks like two @@ -2968,7 +3030,8 @@ impl<'a> LoweringContext<'a> { } } - fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause { + fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause<'a> { + let arena = self.arena; self.with_anonymous_lifetime_mode( AnonymousLifetimeMode::ReportError, |this| { @@ -2977,13 +3040,14 @@ impl<'a> LoweringContext<'a> { predicates: wc.predicates .iter() .map(|predicate| this.lower_where_predicate(predicate)) - .collect(), + .collect_hir_vec(arena), } }, ) } - fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate { + fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'a> { + let arena = self.arena; match *pred { WherePredicate::BoundPredicate(WhereBoundPredicate { ref bound_generic_params, @@ -3012,7 +3076,7 @@ impl<'a> LoweringContext<'a> { ImplTraitContext::disallowed(), )), }) - .collect(), + .collect_hir_vec(arena), span, }) }, @@ -3043,10 +3107,14 @@ impl<'a> LoweringContext<'a> { } } - fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData { + fn lower_variant_data(&mut self, vdata: &VariantData) -> hir::VariantData<'a> { + let arena = self.arena; match *vdata { VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct( - fields.iter().enumerate().map(|f| self.lower_struct_field(f)).collect(), + fields.iter() + .enumerate() + .map(|f| self.lower_struct_field(f)) + .collect_hir_vec(arena), recovered, ), VariantData::Tuple(ref fields, id) => { @@ -3055,7 +3123,7 @@ impl<'a> LoweringContext<'a> { .iter() .enumerate() .map(|f| self.lower_struct_field(f)) - .collect(), + .collect_hir_vec(arena), self.lower_node_id(id), ) }, @@ -3065,9 +3133,13 @@ impl<'a> LoweringContext<'a> { } } - fn lower_trait_ref(&mut self, p: &TraitRef, itctx: ImplTraitContext<'_>) -> hir::TraitRef { + fn lower_trait_ref( + &mut self, + p: &TraitRef, + itctx: ImplTraitContext<'_, 'a> + ) -> hir::TraitRef<'a> { let path = match self.lower_qpath(p.ref_id, &None, &p.path, ParamMode::Explicit, itctx) { - hir::QPath::Resolved(None, path) => path.and_then(|path| path), + hir::QPath::Resolved(None, path) => **path, qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath), }; hir::TraitRef { @@ -3079,8 +3151,8 @@ impl<'a> LoweringContext<'a> { fn lower_poly_trait_ref( &mut self, p: &PolyTraitRef, - mut itctx: ImplTraitContext<'_>, - ) -> hir::PolyTraitRef { + mut itctx: ImplTraitContext<'_, 'a>, + ) -> hir::PolyTraitRef<'a> { let bound_generic_params = self.lower_generic_params( &p.bound_generic_params, &NodeMap::default(), @@ -3098,7 +3170,7 @@ impl<'a> LoweringContext<'a> { } } - fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField { + fn lower_struct_field(&mut self, (index, f): (usize, &StructField)) -> hir::StructField<'a> { let ty = if let TyKind::Path(ref qself, ref path) = f.ty.node { let t = self.lower_path_ty( &f.ty, @@ -3107,7 +3179,7 @@ impl<'a> LoweringContext<'a> { ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124) ImplTraitContext::disallowed() ); - P(t) + p!(self, t) } else { self.lower_ty(&f.ty, ImplTraitContext::disallowed()) }; @@ -3125,40 +3197,42 @@ impl<'a> LoweringContext<'a> { } } - fn lower_field(&mut self, f: &Field) -> hir::Field { + fn lower_field(&mut self, f: &Field) -> hir::Field<'a> { hir::Field { hir_id: self.next_id(), ident: f.ident, - expr: P(self.lower_expr(&f.expr)), + expr: p!(self, self.lower_expr(&f.expr)), span: f.span, is_shorthand: f.is_shorthand, } } - fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy { + fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_, 'a>) -> hir::MutTy<'a> { hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: self.lower_mutability(mt.mutbl), } } - fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>) - -> hir::GenericBounds { - bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect() + fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_, 'a>) + -> hir::GenericBounds<'a> { + let arena = self.arena; + bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())) + .collect_hir_vec(arena) } fn lower_block_with_stmts( &mut self, b: &Block, targeted_by_break: bool, - mut stmts: Vec, - ) -> P { + mut stmts: Vec>, + ) -> P<'a, hir::Block<'a>> { let mut expr = None; for (index, stmt) in b.stmts.iter().enumerate() { if index == b.stmts.len() - 1 { if let StmtKind::Expr(ref e) = stmt.node { - expr = Some(P(self.lower_expr(e))); + expr = Some(p!(self, self.lower_expr(e))); } else { stmts.extend(self.lower_stmt(stmt)); } @@ -3167,9 +3241,9 @@ impl<'a> LoweringContext<'a> { } } - P(hir::Block { + p!(self, hir::Block { hir_id: self.lower_node_id(b.id), - stmts: stmts.into(), + stmts: P::from_slice(self.arena, &stmts), expr, rules: self.lower_block_check_mode(&b.rules), span: b.span, @@ -3177,7 +3251,7 @@ impl<'a> LoweringContext<'a> { }) } - fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P { + fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<'a, hir::Block<'a>> { self.lower_block_with_stmts(b, targeted_by_break, vec![]) } @@ -3191,7 +3265,7 @@ impl<'a> LoweringContext<'a> { IsAsync::Async { closure_id, .. } => closure_id, IsAsync::NotAsync => return self.lower_fn_body(&decl, |this| { let body = this.lower_block(body, false); - this.expr_block(body, ThinVec::new()) + this.expr_block(body, thin_hir_vec![]) }), }; @@ -3262,7 +3336,11 @@ impl<'a> LoweringContext<'a> { // `HirId`s are densely assigned. let expr = this.expr_ident(desugared_span, ident, new_argument_id); let stmt = this.stmt_let_pat( - desugared_span, Some(P(expr)), argument.pat, hir::LocalSource::AsyncFn); + desugared_span, + Some(p!(this, expr)), + argument.pat, + hir::LocalSource::AsyncFn + ); statements.push(stmt); } else { // If this is not the simple case, then we construct two statements: @@ -3284,13 +3362,17 @@ impl<'a> LoweringContext<'a> { desugared_span, ident, hir::BindingAnnotation::Mutable); let move_expr = this.expr_ident(desugared_span, ident, new_argument_id); let move_stmt = this.stmt_let_pat( - desugared_span, Some(P(move_expr)), move_pat, hir::LocalSource::AsyncFn); + desugared_span, + Some(p!(this, move_expr)), + move_pat, + hir::LocalSource::AsyncFn + ); // Construct the `let = __argN;` statement. We re-use the original // argument's pattern so that `HirId`s are densely assigned. let pattern_expr = this.expr_ident(desugared_span, ident, move_id); let pattern_stmt = this.stmt_let_pat( - desugared_span, Some(P(pattern_expr)), argument.pat, + desugared_span, Some(p!(this, pattern_expr)), argument.pat, hir::LocalSource::AsyncFn); statements.push(move_stmt); @@ -3304,9 +3386,10 @@ impl<'a> LoweringContext<'a> { CaptureBy::Value, closure_id, None, body.span, |this| { let body = this.lower_block_with_stmts(body, false, statements); - this.expr_block(body, ThinVec::new()) + this.expr_block(body, thin_hir_vec![]) }); - (HirVec::from(arguments), this.expr(body.span, async_expr, ThinVec::new())) + (HirVec::from_slice(this.arena, &arguments), + this.expr(body.span, async_expr, thin_hir_vec![])) }) } @@ -3314,10 +3397,11 @@ impl<'a> LoweringContext<'a> { &mut self, id: NodeId, ident: &mut Ident, - attrs: &hir::HirVec, - vis: &mut hir::Visibility, + attrs: &hir::HirVec<'a, Attribute>, + vis: &mut hir::Visibility<'a>, i: &ItemKind, - ) -> hir::ItemKind { + ) -> hir::ItemKind<'a> { + let arena = self.arena; match *i { ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name), ItemKind::Use(ref use_tree) => { @@ -3411,7 +3495,7 @@ impl<'a> LoweringContext<'a> { .variants .iter() .map(|x| self.lower_variant(x)) - .collect(), + .collect_hir_vec(arena), }, self.lower_generics(generics, ImplTraitContext::disallowed()), ) @@ -3483,7 +3567,7 @@ impl<'a> LoweringContext<'a> { impl_items .iter() .map(|item| this.lower_impl_item_ref(item)) - .collect() + .collect_hir_vec(arena) }, ); @@ -3502,7 +3586,7 @@ impl<'a> LoweringContext<'a> { let items = items .iter() .map(|item| self.lower_trait_item_ref(item)) - .collect(); + .collect_hir_vec(arena); hir::ItemKind::Trait( self.lower_is_auto(is_auto), self.lower_unsafety(unsafety), @@ -3528,10 +3612,10 @@ impl<'a> LoweringContext<'a> { tree: &UseTree, prefix: &Path, id: NodeId, - vis: &mut hir::Visibility, + vis: &mut hir::Visibility<'a>, ident: &mut Ident, - attrs: &hir::HirVec, - ) -> hir::ItemKind { + attrs: &hir::HirVec<'a, Attribute>, + ) -> hir::ItemKind<'a> { debug!("lower_use_tree(tree={:?})", tree); debug!("lower_use_tree: vis = {:?}", vis); @@ -3587,7 +3671,7 @@ impl<'a> LoweringContext<'a> { let res = this.lower_res(res); let path = this.lower_path_extra(res, &path, ParamMode::Explicit, None); - let item = hir::ItemKind::Use(P(path), hir::UseKind::Single); + let item = hir::ItemKind::Use(p!(this, path), hir::UseKind::Single); let vis_kind = match vis.node { hir::VisibilityKind::Public => hir::VisibilityKind::Public, hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar), @@ -3616,11 +3700,11 @@ impl<'a> LoweringContext<'a> { } let path = - P(self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None)); + p!(self, self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None)); hir::ItemKind::Use(path, hir::UseKind::Single) } UseTreeKind::Glob => { - let path = P(self.lower_path( + let path = p!(self, self.lower_path( id, &Path { segments, @@ -3736,7 +3820,7 @@ impl<'a> LoweringContext<'a> { let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err); let res = self.lower_res(res); - let path = P(self.lower_path_extra(res, &prefix, ParamMode::Explicit, None)); + let path = p!(self, self.lower_path_extra(res, &prefix, ParamMode::Explicit, None)); hir::ItemKind::Use(path, hir::UseKind::ListStem) } } @@ -3745,18 +3829,20 @@ impl<'a> LoweringContext<'a> { /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated /// many times in the HIR tree; for each occurrence, we need to assign distinct /// `NodeId`s. (See, e.g., #56128.) - fn renumber_segment_ids(&mut self, path: &P) -> P { + fn renumber_segment_ids(&mut self, path: &P<'a, hir::Path>) -> P<'a, hir::Path<'a>> { debug!("renumber_segment_ids(path = {:?})", path); - let mut path = path.clone(); - for seg in path.segments.iter_mut() { + let mut path = ***path; + let mut segments = path.segments.into_vec(); + for seg in &mut segments { if seg.hir_id.is_some() { seg.hir_id = Some(self.next_id()); } } - path + path.segments = P::from_slice(self.arena, &segments); + p!(self, path) } - fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem { + fn lower_trait_item(&mut self, i: &TraitItem) -> hir::TraitItem<'a> { let trait_item_def_id = self.resolver.definitions().local_def_id(i.id); let (generics, node) = match i.node { @@ -3783,7 +3869,7 @@ impl<'a> LoweringContext<'a> { TraitItemKind::Method(ref sig, Some(ref body)) => { let body_id = self.lower_fn_body(&sig.decl, |this| { let body = this.lower_block(body, false); - this.expr_block(body, ThinVec::new()) + this.expr_block(body, thin_hir_vec![]) }); let (generics, sig) = self.lower_method_sig( &i.generics, @@ -3843,7 +3929,7 @@ impl<'a> LoweringContext<'a> { } } - fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem { + fn lower_impl_item(&mut self, i: &ImplItem) -> hir::ImplItem<'a> { let impl_item_def_id = self.resolver.definitions().local_def_id(i.id); let (generics, node) = match i.node { @@ -3897,7 +3983,7 @@ impl<'a> LoweringContext<'a> { // [1] since `default impl` is not yet implemented, this is always true in impls } - fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef { + fn lower_impl_item_ref(&mut self, i: &ImplItem) -> hir::ImplItemRef<'a> { hir::ImplItemRef { id: hir::ImplItemId { hir_id: self.lower_node_id(i.id) }, ident: i.ident, @@ -3918,10 +4004,11 @@ impl<'a> LoweringContext<'a> { // [1] since `default impl` is not yet implemented, this is always true in impls } - fn lower_mod(&mut self, m: &Mod) -> hir::Mod { + fn lower_mod(&mut self, m: &Mod) -> hir::Mod<'a> { + let arena = self.arena; hir::Mod { inner: m.inner, - item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect(), + item_ids: m.items.iter().flat_map(|x| self.lower_item_id(x)).collect_hir_vec(arena), } } @@ -3981,7 +4068,7 @@ impl<'a> LoweringContext<'a> { } } - pub fn lower_item(&mut self, i: &Item) -> Option { + pub fn lower_item(&mut self, i: &Item) -> Option> { let mut ident = i.ident; let mut vis = self.lower_visibility(&i.vis, None); let attrs = self.lower_attrs(&i.attrs); @@ -3996,7 +4083,7 @@ impl<'a> LoweringContext<'a> { attrs, hir_id, span: i.span, - body, + body: P::from_existing(self.arena.alloc(body)), legacy: def.legacy, }); } @@ -4015,7 +4102,7 @@ impl<'a> LoweringContext<'a> { }) } - fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem { + fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem<'a> { let def_id = self.resolver.definitions().local_def_id(i.id); hir::ForeignItem { hir_id: self.lower_node_id(i.id), @@ -4057,7 +4144,7 @@ impl<'a> LoweringContext<'a> { fn_def_id: DefId, impl_trait_return_allow: bool, is_async: Option, - ) -> (hir::Generics, hir::MethodSig) { + ) -> (hir::Generics<'a>, hir::MethodSig<'a>) { let header = self.lower_fn_header(sig.header); let (generics, decl) = self.add_in_band_defs( generics, @@ -4144,7 +4231,8 @@ impl<'a> LoweringContext<'a> { } } - fn lower_pat(&mut self, p: &Pat) -> P { + fn lower_pat(&mut self, p: &Pat) -> P<'a, hir::Pat<'a>> { + let arena = self.arena; let node = match p.node { PatKind::Wild => hir::PatKind::Wild, PatKind::Ident(ref binding_mode, ident, ref sub) => { @@ -4165,15 +4253,15 @@ impl<'a> LoweringContext<'a> { } Some(res) => hir::PatKind::Path(hir::QPath::Resolved( None, - P(hir::Path { + p!(self, hir::Path { span: ident.span, res: self.lower_res(res), - segments: hir_vec![hir::PathSegment::from_ident(ident)], + segments: hir_vec![self; hir::PathSegment::from_ident(ident)], }), )), } } - PatKind::Lit(ref e) => hir::PatKind::Lit(P(self.lower_expr(e))), + PatKind::Lit(ref e) => hir::PatKind::Lit(p!(self, self.lower_expr(e))), PatKind::TupleStruct(ref path, ref pats, ddpos) => { let qpath = self.lower_qpath( p.id, @@ -4184,7 +4272,7 @@ impl<'a> LoweringContext<'a> { ); hir::PatKind::TupleStruct( qpath, - pats.iter().map(|x| self.lower_pat(x)).collect(), + pats.iter().map(|x| self.lower_pat(x)).collect_hir_vec(arena), ddpos, ) } @@ -4220,31 +4308,32 @@ impl<'a> LoweringContext<'a> { }, } }) - .collect(); + .collect_hir_vec(arena); hir::PatKind::Struct(qpath, fs, etc) } PatKind::Tuple(ref elts, ddpos) => { - hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)).collect(), ddpos) + hir::PatKind::Tuple(elts.iter().map(|x| self.lower_pat(x)) + .collect_hir_vec(arena), ddpos) } PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)), PatKind::Ref(ref inner, mutbl) => { hir::PatKind::Ref(self.lower_pat(inner), self.lower_mutability(mutbl)) } PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range( - P(self.lower_expr(e1)), - P(self.lower_expr(e2)), + p!(self, self.lower_expr(e1)), + p!(self, self.lower_expr(e2)), self.lower_range_end(end), ), PatKind::Slice(ref before, ref slice, ref after) => hir::PatKind::Slice( - before.iter().map(|x| self.lower_pat(x)).collect(), + before.iter().map(|x| self.lower_pat(x)).collect_hir_vec(arena), slice.as_ref().map(|x| self.lower_pat(x)), - after.iter().map(|x| self.lower_pat(x)).collect(), + after.iter().map(|x| self.lower_pat(x)).collect_hir_vec(arena), ), PatKind::Paren(ref inner) => return self.lower_pat(inner), PatKind::Mac(_) => panic!("Shouldn't exist here"), }; - P(hir::Pat { + p!(self, hir::Pat { hir_id: self.lower_node_id(p.id), node, span: p.span, @@ -4267,26 +4356,31 @@ impl<'a> LoweringContext<'a> { }) } - fn lower_expr(&mut self, e: &Expr) -> hir::Expr { + fn lower_expr(&mut self, e: &Expr) -> hir::Expr<'a> { + let arena = self.arena; let kind = match e.node { - ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))), + ExprKind::Box(ref inner) => hir::ExprKind::Box(p!(self, self.lower_expr(inner))), ExprKind::Array(ref exprs) => { - hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)).collect()) + hir::ExprKind::Array(exprs.iter().map(|x| self.lower_expr(x)) + .collect_hir_vec(arena)) } ExprKind::Repeat(ref expr, ref count) => { - let expr = P(self.lower_expr(expr)); + let expr = p!(self, self.lower_expr(expr)); let count = self.lower_anon_const(count); hir::ExprKind::Repeat(expr, count) } ExprKind::Tup(ref elts) => { - hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect()) + hir::ExprKind::Tup(elts.iter().map(|x| self.lower_expr(x)).collect_hir_vec(arena)) } ExprKind::Call(ref f, ref args) => { - let f = P(self.lower_expr(f)); - hir::ExprKind::Call(f, args.iter().map(|x| self.lower_expr(x)).collect()) + let f = p!(self, self.lower_expr(f)); + hir::ExprKind::Call( + f, + args.iter().map(|x| self.lower_expr(x)).collect_hir_vec(arena) + ) } ExprKind::MethodCall(ref seg, ref args) => { - let hir_seg = P(self.lower_path_segment( + let hir_seg = p!(self, self.lower_path_segment( e.span, seg, ParamMode::Optional, @@ -4295,32 +4389,36 @@ impl<'a> LoweringContext<'a> { ImplTraitContext::disallowed(), None, )); - let args = args.iter().map(|x| self.lower_expr(x)).collect(); + let args = args.iter().map(|x| self.lower_expr(x)).collect_hir_vec(arena); hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args) } ExprKind::Binary(binop, ref lhs, ref rhs) => { let binop = self.lower_binop(binop); - let lhs = P(self.lower_expr(lhs)); - let rhs = P(self.lower_expr(rhs)); + let lhs = p!(self, self.lower_expr(lhs)); + let rhs = p!(self, self.lower_expr(rhs)); hir::ExprKind::Binary(binop, lhs, rhs) } ExprKind::Unary(op, ref ohs) => { let op = self.lower_unop(op); - let ohs = P(self.lower_expr(ohs)); + let ohs = p!(self, self.lower_expr(ohs)); hir::ExprKind::Unary(op, ohs) } - ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.node.clone())), + ExprKind::Lit(ref l) => { + let lit = respan(l.span, l.node.clone()); + let lit = P::from_existing(self.arena.alloc(lit)); + hir::ExprKind::Lit(lit) + } ExprKind::Cast(ref expr, ref ty) => { - let expr = P(self.lower_expr(expr)); + let expr = p!(self, self.lower_expr(expr)); hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed())) } ExprKind::Type(ref expr, ref ty) => { - let expr = P(self.lower_expr(expr)); + let expr = p!(self, self.lower_expr(expr)); hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed())) } ExprKind::AddrOf(m, ref ohs) => { let m = self.lower_mutability(m); - let ohs = P(self.lower_expr(ohs)); + let ohs = p!(self, self.lower_expr(ohs)); hir::ExprKind::AddrOf(m, ohs) } // More complicated than you might expect because the else branch @@ -4329,8 +4427,8 @@ impl<'a> LoweringContext<'a> { // `true => then`: let then_pat = self.pat_bool(e.span, true); let then_blk = self.lower_block(then, false); - let then_expr = self.expr_block(then_blk, ThinVec::new()); - let then_arm = self.arm(hir_vec![then_pat], P(then_expr)); + let then_expr = self.expr_block(then_blk, thin_hir_vec![]); + let then_arm = self.arm(hir_vec![self; then_pat], p!(self, then_expr)); // `_ => else_block` where `else_block` is `{}` if there's `None`: let else_pat = self.pat_wild(e.span); @@ -4340,24 +4438,24 @@ impl<'a> LoweringContext<'a> { ExprKind::IfLet(..) => { // Wrap the `if let` expr in a block. let els = self.lower_expr(els); - let blk = self.block_all(els.span, hir_vec![], Some(P(els))); - self.expr_block(P(blk), ThinVec::new()) + let blk = self.block_all(els.span, hir_vec![], Some(p!(self, els))); + self.expr_block(p!(self, blk), thin_hir_vec![]) } _ => self.lower_expr(els), } }; - let else_arm = self.arm(hir_vec![else_pat], P(else_expr)); + let else_arm = self.arm(hir_vec![self; else_pat], p!(self, else_expr)); // Lower condition: let span_block = self.mark_span_with_reason(IfTemporary, cond.span, None); let cond = self.lower_expr(cond); // Wrap in a construct equivalent to `{ let _t = $cond; _t }` to preserve drop // semantics since `if cond { ... }` don't let temporaries live outside of `cond`. - let cond = self.expr_drop_temps(span_block, P(cond), ThinVec::new()); + let cond = self.expr_drop_temps(span_block, p!(self, cond), thin_hir_vec![]); hir::ExprKind::Match( - P(cond), - vec![then_arm, else_arm].into(), + p!(self, cond), + hir_vec![self; then_arm, else_arm], hir::MatchSource::IfDesugar { contains_else_clause: else_opt.is_some() }, @@ -4365,7 +4463,7 @@ impl<'a> LoweringContext<'a> { } ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| { hir::ExprKind::While( - this.with_loop_condition_scope(|this| P(this.lower_expr(cond))), + this.with_loop_condition_scope(|this| p!(this, this.lower_expr(cond))), this.lower_block(body, false), this.lower_label(opt_label), ) @@ -4391,27 +4489,27 @@ impl<'a> LoweringContext<'a> { hir::Expr { span, node: hir::ExprKind::Tup(hir_vec![]), - attrs: ThinVec::new(), + attrs: thin_hir_vec![], hir_id: this.next_id(), } }, - |x: P| x.into_inner(), + |x: P<'a, hir::Expr<'a>>| x.into_inner(), ); block.expr = Some(this.wrap_in_try_constructor( sym::from_ok, tail, unstable_span)); - hir::ExprKind::Block(P(block), None) + hir::ExprKind::Block(p!(this, block), None) }) } ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match( - P(self.lower_expr(expr)), - arms.iter().map(|x| self.lower_arm(x)).collect(), + p!(self, self.lower_expr(expr)), + arms.iter().map(|x| self.lower_arm(x)).collect_hir_vec(arena), hir::MatchSource::Normal, ), ExprKind::Async(capture_clause, closure_node_id, ref block) => { self.make_async_expr(capture_clause, closure_node_id, None, block.span, |this| { this.with_new_scopes(|this| { let block = this.lower_block(block, false); - this.expr_block(block, ThinVec::new()) + this.expr_block(block, thin_hir_vec![]) }) }) } @@ -4459,7 +4557,7 @@ impl<'a> LoweringContext<'a> { |this| { this.with_new_scopes(|this| this.lower_expr(body)) }); - this.expr(fn_decl_span, async_body, ThinVec::new()) + this.expr(fn_decl_span, async_body, thin_hir_vec![]) }); hir::ExprKind::Closure( this.lower_capture_clause(capture_clause), @@ -4522,16 +4620,18 @@ impl<'a> LoweringContext<'a> { self.lower_label(opt_label)) } ExprKind::Assign(ref el, ref er) => { - hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er))) + hir::ExprKind::Assign(p!(self, self.lower_expr(el)), p!(self, self.lower_expr(er))) } ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp( self.lower_binop(op), - P(self.lower_expr(el)), - P(self.lower_expr(er)), + p!(self, self.lower_expr(el)), + p!(self, self.lower_expr(er)), ), - ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident), + ExprKind::Field(ref el, ident) => { + hir::ExprKind::Field(p!(self, self.lower_expr(el)), ident) + } ExprKind::Index(ref el, ref er) => { - hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er))) + hir::ExprKind::Index(p!(self, self.lower_expr(el)), p!(self, self.lower_expr(er))) } // Desugar `..=` into `std::ops::RangeInclusive::new(, )`. ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => { @@ -4543,7 +4643,7 @@ impl<'a> LoweringContext<'a> { e.span, &[sym::ops, sym::RangeInclusive], "new", - hir_vec![e1, e2], + hir_vec![self; e1, e2], ) } ExprKind::Range(ref e1, ref e2, lims) => { @@ -4565,27 +4665,22 @@ impl<'a> LoweringContext<'a> { .map(|e| ("start", e)) .chain(e2.iter().map(|e| ("end", e))) .map(|(s, e)| { - let expr = P(self.lower_expr(&e)); + let expr = p!(self, self.lower_expr(&e)); let ident = Ident::new(Symbol::intern(s), e.span); self.field(ident, expr, e.span) }) - .collect::>(); + .collect_hir_vec(arena); let is_unit = fields.is_empty(); let struct_path = [sym::ops, path]; let struct_path = self.std_path(e.span, &struct_path, None, is_unit); - let struct_path = hir::QPath::Resolved(None, P(struct_path)); + let struct_path = hir::QPath::Resolved(None, p!(self, struct_path)); - return hir::Expr { - hir_id: self.lower_node_id(e.id), - node: if is_unit { - hir::ExprKind::Path(struct_path) - } else { - hir::ExprKind::Struct(P(struct_path), fields, None) - }, - span: e.span, - attrs: e.attrs.clone(), - }; + if is_unit { + hir::ExprKind::Path(struct_path) + } else { + hir::ExprKind::Struct(p!(self, struct_path), fields, None) + } } ExprKind::Path(ref qself, ref path) => { let qpath = self.lower_qpath( @@ -4608,7 +4703,7 @@ impl<'a> LoweringContext<'a> { }; hir::ExprKind::Break( destination, - opt_expr.as_ref().map(|x| P(self.lower_expr(x))), + opt_expr.as_ref().map(|x| p!(self, self.lower_expr(x))), ) } ExprKind::Continue(opt_label) => { @@ -4621,7 +4716,9 @@ impl<'a> LoweringContext<'a> { self.lower_loop_destination(opt_label.map(|label| (e.id, label))) }) } - ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))), + ExprKind::Ret(ref e) => { + hir::ExprKind::Ret(e.as_ref().map(|x| p!(self, self.lower_expr(x)))) + } ExprKind::InlineAsm(ref asm) => { let hir_asm = hir::InlineAsm { inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(), @@ -4645,23 +4742,24 @@ impl<'a> LoweringContext<'a> { let outputs = asm.outputs .iter() .map(|out| self.lower_expr(&out.expr)) - .collect(); + .collect_hir_vec(arena); let inputs = asm.inputs .iter() .map(|&(_, ref input)| self.lower_expr(input)) - .collect(); - hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs) + .collect_hir_vec(arena); + let hir_asm = P::from_existing(self.arena.alloc(hir_asm)); + hir::ExprKind::InlineAsm(hir_asm, outputs, inputs) } ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct( - P(self.lower_qpath( + p!(self, self.lower_qpath( e.id, &None, path, ParamMode::Optional, ImplTraitContext::disallowed(), )), - fields.iter().map(|x| self.lower_field(x)).collect(), - maybe_expr.as_ref().map(|x| P(self.lower_expr(x))), + fields.iter().map(|x| self.lower_field(x)).collect_hir_vec(arena), + maybe_expr.as_ref().map(|x| p!(self, self.lower_expr(x))), ), ExprKind::Paren(ref ex) => { let mut ex = self.lower_expr(ex); @@ -4670,9 +4768,11 @@ impl<'a> LoweringContext<'a> { ex.span = e.span; } // Merge attributes into the inner expression. - let mut attrs = e.attrs.clone(); - attrs.extend::>(ex.attrs.into()); - ex.attrs = attrs; + if !e.attrs.is_empty() { + ex.attrs = self.copy_attrs( + e.attrs.iter().cloned().chain(ex.attrs.iter().cloned()) + ); + } return ex; } @@ -4682,7 +4782,7 @@ impl<'a> LoweringContext<'a> { .as_ref() .map(|x| self.lower_expr(x)) .unwrap_or_else(|| self.expr_unit(e.span)); - hir::ExprKind::Yield(P(expr)) + hir::ExprKind::Yield(p!(self, expr)) } ExprKind::Err => hir::ExprKind::Err, @@ -4702,8 +4802,8 @@ impl<'a> LoweringContext<'a> { // ` => ` { let body = self.lower_block(body, false); - let body_expr = P(self.expr_block(body, ThinVec::new())); - let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect(); + let body_expr = p!(self, self.expr_block(body, thin_hir_vec![])); + let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect_hir_vec(arena); arms.push(self.arm(pats, body_expr)); } @@ -4716,16 +4816,16 @@ impl<'a> LoweringContext<'a> { } else { self.expr_block_empty(e.span) }; - arms.push(self.arm(hir_vec![wildcard_pattern], P(body))); + arms.push(self.arm(hir_vec![self; wildcard_pattern], p!(self, body))); } let contains_else_clause = else_opt.is_some(); - let sub_expr = P(self.lower_expr(sub_expr)); + let sub_expr = p!(self, self.lower_expr(sub_expr)); hir::ExprKind::Match( sub_expr, - arms.into(), + P::from_slice(self.arena, &arms), hir::MatchSource::IfLetDesugar { contains_else_clause, }, @@ -4749,34 +4849,34 @@ impl<'a> LoweringContext<'a> { let (body, break_expr, sub_expr) = self.with_loop_scope(e.id, |this| { ( this.lower_block(body, false), - this.expr_break(e.span, ThinVec::new()), - this.with_loop_condition_scope(|this| P(this.lower_expr(sub_expr))), + this.expr_break(e.span, thin_hir_vec![]), + this.with_loop_condition_scope(|this| p!(this, this.lower_expr(sub_expr))), ) }); // ` => ` let pat_arm = { - let body_expr = P(self.expr_block(body, ThinVec::new())); - let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect(); + let body_expr = p!(self, self.expr_block(body, thin_hir_vec![])); + let pats = pats.iter().map(|pat| self.lower_pat(pat)).collect_hir_vec(arena); self.arm(pats, body_expr) }; // `_ => break` let break_arm = { let pat_under = self.pat_wild(e.span); - self.arm(hir_vec![pat_under], break_expr) + self.arm(hir_vec![self; pat_under], break_expr) }; // `match { ... }` - let arms = hir_vec![pat_arm, break_arm]; + let arms = hir_vec![self; pat_arm, break_arm]; let match_expr = self.expr( sub_expr.span, hir::ExprKind::Match(sub_expr, arms, hir::MatchSource::WhileLetDesugar), - ThinVec::new(), + thin_hir_vec![], ); // `[opt_ident]: loop { ... }` - let loop_block = P(self.block_expr(P(match_expr))); + let loop_block = p!(self, self.block_expr(p!(self, match_expr))); let loop_expr = hir::ExprKind::Loop( loop_block, self.lower_label(opt_label), @@ -4831,23 +4931,23 @@ impl<'a> LoweringContext<'a> { let pat_arm = { let val_ident = Ident::with_empty_ctxt(sym::val); let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident); - let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat_hid)); - let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat_hid)); - let assign = P(self.expr( + let val_expr = p!(self, self.expr_ident(pat.span, val_ident, val_pat_hid)); + let next_expr = p!(self, self.expr_ident(pat.span, next_ident, next_pat_hid)); + let assign = p!(self, self.expr( pat.span, hir::ExprKind::Assign(next_expr, val_expr), - ThinVec::new(), + thin_hir_vec![], )); let some_pat = self.pat_some(pat.span, val_pat); - self.arm(hir_vec![some_pat], assign) + self.arm(hir_vec![self; some_pat], assign) }; // `::std::option::Option::None => break` let break_arm = { let break_expr = - self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new())); + self.with_loop_scope(e.id, |this| this.expr_break(e.span, thin_hir_vec![])); let pat = self.pat_none(e.span); - self.arm(hir_vec![pat], break_expr) + self.arm(hir_vec![self; pat], break_expr) }; // `mut iter` @@ -4859,29 +4959,29 @@ impl<'a> LoweringContext<'a> { // `match ::std::iter::Iterator::next(&mut iter) { ... }` let match_expr = { - let iter = P(self.expr_ident(head_sp, iter, iter_pat_nid)); + let iter = p!(self, self.expr_ident(head_sp, iter, iter_pat_nid)); let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter); let next_path = &[sym::iter, sym::Iterator, sym::next]; - let next_expr = P(self.expr_call_std_path( + let next_expr = p!(self, self.expr_call_std_path( head_sp, next_path, - hir_vec![ref_mut_iter], + hir_vec![self; ref_mut_iter], )); - let arms = hir_vec![pat_arm, break_arm]; + let arms = hir_vec![self; pat_arm, break_arm]; - P(self.expr( + p!(self, self.expr( head_sp, hir::ExprKind::Match( next_expr, arms, hir::MatchSource::ForLoopDesugar ), - ThinVec::new(), + thin_hir_vec![], )) }; let match_stmt = self.stmt(head_sp, hir::StmtKind::Expr(match_expr)); - let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat_hid)); + let next_expr = p!(self, self.expr_ident(head_sp, next_ident, next_pat_hid)); // `let mut __next` let next_let = self.stmt_let_pat( @@ -4901,12 +5001,12 @@ impl<'a> LoweringContext<'a> { ); let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false)); - let body_expr = P(self.expr_block(body_block, ThinVec::new())); + let body_expr = p!(self, self.expr_block(body_block, thin_hir_vec![])); let body_stmt = self.stmt(body.span, hir::StmtKind::Expr(body_expr)); - let loop_block = P(self.block_all( + let loop_block = p!(self, self.block_all( e.span, - hir_vec![next_let, match_stmt, pat_let, body_stmt], + hir_vec![self; next_let, match_stmt, pat_let, body_stmt], None, )); @@ -4916,31 +5016,31 @@ impl<'a> LoweringContext<'a> { self.lower_label(opt_label), hir::LoopSource::ForLoop, ); - let loop_expr = P(hir::Expr { + let loop_expr = p!(self, hir::Expr { hir_id: self.lower_node_id(e.id), node: loop_expr, span: e.span, - attrs: ThinVec::new(), + attrs: thin_hir_vec![], }); // `mut iter => { ... }` - let iter_arm = self.arm(hir_vec![iter_pat], loop_expr); + let iter_arm = self.arm(hir_vec![self; iter_pat], loop_expr); // `match ::std::iter::IntoIterator::into_iter() { ... }` let into_iter_expr = { let into_iter_path = &[sym::iter, sym::IntoIterator, sym::into_iter]; - P(self.expr_call_std_path( + p!(self, self.expr_call_std_path( head_sp, into_iter_path, - hir_vec![head], + hir_vec![self; head], )) }; - let match_expr = P(self.expr_match( + let match_expr = p!(self, self.expr_match( head_sp, into_iter_expr, - hir_vec![iter_arm], + hir_vec![self; iter_arm], hir::MatchSource::ForLoopDesugar, )); @@ -4948,7 +5048,8 @@ impl<'a> LoweringContext<'a> { // The construct was introduced in #21984. // FIXME(60253): Is this still necessary? // Also, add the attributes to the outer returned expr node. - return self.expr_drop_temps(head_sp, match_expr, e.attrs.clone()) + let attrs = self.copy_attrs(e.attrs.iter().cloned()); + return self.expr_drop_temps(head_sp, match_expr, attrs) } // Desugar `ExprKind::Try` @@ -4983,10 +5084,10 @@ impl<'a> LoweringContext<'a> { let sub_expr = self.lower_expr(sub_expr); let path = &[sym::ops, sym::Try, sym::into_result]; - P(self.expr_call_std_path( + p!(self, self.expr_call_std_path( unstable_span, path, - hir_vec![sub_expr], + hir_vec![self; sub_expr], )) }; @@ -5002,21 +5103,21 @@ impl<'a> LoweringContext<'a> { }; attr::mk_spanned_attr_outer(e.span, attr::mk_attr_id(), allow) }; - let attrs = vec![attr]; + let attrs = self.copy_attrs(Some(attr)); // `Ok(val) => #[allow(unreachable_code)] val,` let ok_arm = { let val_ident = Ident::with_empty_ctxt(sym::val); let (val_pat, val_pat_nid) = self.pat_ident(e.span, val_ident); - let val_expr = P(self.expr_ident_with_attrs( + let val_expr = p!(self, self.expr_ident_with_attrs( e.span, val_ident, val_pat_nid, - ThinVec::from(attrs.clone()), + attrs, )); let ok_pat = self.pat_ok(e.span, val_pat); - self.arm(hir_vec![ok_pat], val_expr) + self.arm(hir_vec![self; ok_pat], val_expr) }; // `Err(err) => #[allow(unreachable_code)] @@ -5027,15 +5128,14 @@ impl<'a> LoweringContext<'a> { let from_expr = { let from_path = &[sym::convert, sym::From, sym::from]; let err_expr = self.expr_ident(try_span, err_ident, err_local_nid); - self.expr_call_std_path(try_span, from_path, hir_vec![err_expr]) + self.expr_call_std_path(try_span, from_path, hir_vec![self; err_expr]) }; let from_err_expr = self.wrap_in_try_constructor(sym::from_error, from_expr, unstable_span); - let thin_attrs = ThinVec::from(attrs); let catch_scope = self.catch_scopes.last().map(|x| *x); let ret_expr = if let Some(catch_node) = catch_scope { let target_id = Ok(self.lower_node_id(catch_node)); - P(self.expr( + p!(self, self.expr( try_span, hir::ExprKind::Break( hir::Destination { @@ -5044,19 +5144,22 @@ impl<'a> LoweringContext<'a> { }, Some(from_err_expr), ), - thin_attrs, + attrs, )) } else { - P(self.expr(try_span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs)) + p!( + self, + self.expr(try_span, hir::ExprKind::Ret(Some(from_err_expr)), attrs) + ) }; let err_pat = self.pat_err(try_span, err_local); - self.arm(hir_vec![err_pat], ret_expr) + self.arm(hir_vec![self; err_pat], ret_expr) }; hir::ExprKind::Match( discr, - hir_vec![err_arm, ok_arm], + hir_vec![self; err_arm, ok_arm], hir::MatchSource::TryDesugar, ) } @@ -5068,11 +5171,11 @@ impl<'a> LoweringContext<'a> { hir_id: self.lower_node_id(e.id), node: kind, span: e.span, - attrs: e.attrs.clone(), + attrs: self.copy_attrs(e.attrs.iter().cloned()), } } - fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt; 1]> { + fn lower_stmt(&mut self, s: &Stmt) -> SmallVec<[hir::Stmt<'a>; 1]> { smallvec![match s.node { StmtKind::Local(ref l) => { let (l, item_ids) = self.lower_local(l); @@ -5086,7 +5189,7 @@ impl<'a> LoweringContext<'a> { ids.push({ hir::Stmt { hir_id: self.lower_node_id(s.id), - node: hir::StmtKind::Local(P(l)), + node: hir::StmtKind::Local(p!(self, l)), span: s.span, } }); @@ -5113,14 +5216,14 @@ impl<'a> LoweringContext<'a> { StmtKind::Expr(ref e) => { hir::Stmt { hir_id: self.lower_node_id(s.id), - node: hir::StmtKind::Expr(P(self.lower_expr(e))), + node: hir::StmtKind::Expr(p!(self, self.lower_expr(e))), span: s.span, } }, StmtKind::Semi(ref e) => { hir::Stmt { hir_id: self.lower_node_id(s.id), - node: hir::StmtKind::Semi(P(self.lower_expr(e))), + node: hir::StmtKind::Semi(p!(self, self.lower_expr(e))), span: s.span, } }, @@ -5144,7 +5247,7 @@ impl<'a> LoweringContext<'a> { &mut self, v: &Visibility, explicit_owner: Option, - ) -> hir::Visibility { + ) -> hir::Visibility<'a> { let node = match v.node { VisibilityKind::Public => hir::VisibilityKind::Public, VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar), @@ -5158,7 +5261,7 @@ impl<'a> LoweringContext<'a> { let res = self.expect_full_res(id); let res = self.lower_res(res); hir::VisibilityKind::Restricted { - path: P(self.lower_path_extra( + path: p!(self, self.lower_path_extra( res, path, ParamMode::Explicit, @@ -5223,7 +5326,11 @@ impl<'a> LoweringContext<'a> { // Helper methods for building HIR. - fn arm(&mut self, pats: hir::HirVec>, expr: P) -> hir::Arm { + fn arm( + &mut self, + pats: hir::HirVec<'a, P<'a, hir::Pat<'a>>>, + expr: P<'a, hir::Expr<'a>> + ) -> hir::Arm<'a> { hir::Arm { hir_id: self.next_id(), attrs: hir_vec![], @@ -5234,7 +5341,7 @@ impl<'a> LoweringContext<'a> { } } - fn field(&mut self, ident: Ident, expr: P, span: Span) -> hir::Field { + fn field(&mut self, ident: Ident, expr: P<'a, hir::Expr<'a>>, span: Span) -> hir::Field<'a> { hir::Field { hir_id: self.next_id(), ident, @@ -5244,18 +5351,18 @@ impl<'a> LoweringContext<'a> { } } - fn expr_break(&mut self, span: Span, attrs: ThinVec) -> P { + fn expr_break(&mut self, span: Span, attrs: ThinHirVec<'a, Attribute>) -> P<'a, hir::Expr<'a>> { let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None); - P(self.expr(span, expr_break, attrs)) + p!(self, self.expr(span, expr_break, attrs)) } fn expr_call( &mut self, span: Span, - e: P, - args: hir::HirVec, - ) -> hir::Expr { - self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new()) + e: P<'a, hir::Expr<'a>>, + args: hir::HirVec<'a, hir::Expr<'a>>, + ) -> hir::Expr<'a> { + self.expr(span, hir::ExprKind::Call(e, args), thin_hir_vec![]) } // Note: associated functions must use `expr_call_std_path`. @@ -5263,9 +5370,9 @@ impl<'a> LoweringContext<'a> { &mut self, span: Span, path_components: &[Symbol], - args: hir::HirVec, - ) -> hir::Expr { - let path = P(self.expr_std_path(span, path_components, None, ThinVec::new())); + args: hir::HirVec<'a, hir::Expr<'a>>, + ) -> hir::Expr<'a> { + let path = p!(self, self.expr_std_path(span, path_components, None, thin_hir_vec![])); self.expr_call(span, path, args) } @@ -5284,18 +5391,18 @@ impl<'a> LoweringContext<'a> { span: Span, ty_path_components: &[Symbol], assoc_fn_name: &str, - args: hir::HirVec, - ) -> hir::ExprKind { - let ty_path = P(self.std_path(span, ty_path_components, None, false)); - let ty = P(self.ty_path(ty_path_id, span, hir::QPath::Resolved(None, ty_path))); - let fn_seg = P(hir::PathSegment::from_ident(Ident::from_str(assoc_fn_name))); + args: hir::HirVec<'a, hir::Expr<'a>>, + ) -> hir::ExprKind<'a> { + let ty_path = p!(self, self.std_path(span, ty_path_components, None, false)); + let ty = p!(self, self.ty_path(ty_path_id, span, hir::QPath::Resolved(None, ty_path))); + let fn_seg = p!(self, hir::PathSegment::from_ident(Ident::from_str(assoc_fn_name))); let fn_path = hir::QPath::TypeRelative(ty, fn_seg); - let fn_expr = P(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new())); + let fn_expr = p!(self, self.expr(span, hir::ExprKind::Path(fn_path), thin_hir_vec![])); hir::ExprKind::Call(fn_expr, args) } - fn expr_ident(&mut self, span: Span, ident: Ident, binding: hir::HirId) -> hir::Expr { - self.expr_ident_with_attrs(span, ident, binding, ThinVec::new()) + fn expr_ident(&mut self, span: Span, ident: Ident, binding: hir::HirId) -> hir::Expr<'a> { + self.expr_ident_with_attrs(span, ident, binding, thin_hir_vec![]) } fn expr_ident_with_attrs( @@ -5303,35 +5410,35 @@ impl<'a> LoweringContext<'a> { span: Span, ident: Ident, binding: hir::HirId, - attrs: ThinVec, - ) -> hir::Expr { + attrs: ThinHirVec<'a, Attribute>, + ) -> hir::Expr<'a> { let expr_path = hir::ExprKind::Path(hir::QPath::Resolved( None, - P(hir::Path { + p!(self, hir::Path { span, res: Res::Local(binding), - segments: hir_vec![hir::PathSegment::from_ident(ident)], + segments: hir_vec![self; hir::PathSegment::from_ident(ident)], }), )); self.expr(span, expr_path, attrs) } - fn expr_mut_addr_of(&mut self, span: Span, e: P) -> hir::Expr { - self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new()) + fn expr_mut_addr_of(&mut self, span: Span, e: P<'a, hir::Expr<'a>>) -> hir::Expr<'a> { + self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), thin_hir_vec![]) } fn expr_std_path( &mut self, span: Span, components: &[Symbol], - params: Option>, - attrs: ThinVec, - ) -> hir::Expr { + params: Option>>, + attrs: ThinHirVec<'a, Attribute>, + ) -> hir::Expr<'a> { let path = self.std_path(span, components, params, true); self.expr( span, - hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))), + hir::ExprKind::Path(hir::QPath::Resolved(None, p!(self, path))), attrs, ) } @@ -5345,35 +5452,44 @@ impl<'a> LoweringContext<'a> { fn expr_drop_temps( &mut self, span: Span, - expr: P, - attrs: ThinVec - ) -> hir::Expr { + expr: P<'a, hir::Expr<'a>>, + attrs: ThinHirVec<'a, Attribute>, + ) -> hir::Expr<'a> { self.expr(span, hir::ExprKind::DropTemps(expr), attrs) } fn expr_match( &mut self, span: Span, - arg: P, - arms: hir::HirVec, + arg: P<'a, hir::Expr<'a>>, + arms: hir::HirVec<'a, hir::Arm<'a>>, source: hir::MatchSource, - ) -> hir::Expr { - self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new()) + ) -> hir::Expr<'a> { + self.expr(span, hir::ExprKind::Match(arg, arms, source), thin_hir_vec![]) } - fn expr_block(&mut self, b: P, attrs: ThinVec) -> hir::Expr { + fn expr_block( + &mut self, + b: P<'a, hir::Block<'a>>, + attrs: ThinHirVec<'a, Attribute> + ) -> hir::Expr<'a> { self.expr(b.span, hir::ExprKind::Block(b, None), attrs) } - fn expr_unit(&mut self, sp: Span) -> hir::Expr { + fn expr_unit(&mut self, sp: Span) -> hir::Expr<'a> { self.expr_tuple(sp, hir_vec![]) } - fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec) -> hir::Expr { - self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new()) + fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<'a, hir::Expr<'a>>) -> hir::Expr<'a> { + self.expr(sp, hir::ExprKind::Tup(exprs), thin_hir_vec![]) } - fn expr(&mut self, span: Span, node: hir::ExprKind, attrs: ThinVec) -> hir::Expr { + fn expr( + &mut self, + span: Span, + node: hir::ExprKind<'a>, + attrs: ThinHirVec<'a, Attribute> + ) -> hir::Expr<'a> { hir::Expr { hir_id: self.next_id(), node, @@ -5382,17 +5498,17 @@ impl<'a> LoweringContext<'a> { } } - fn stmt(&mut self, span: Span, node: hir::StmtKind) -> hir::Stmt { + fn stmt(&mut self, span: Span, node: hir::StmtKind<'a>) -> hir::Stmt<'a> { hir::Stmt { span, node, hir_id: self.next_id() } } fn stmt_let_pat( &mut self, span: Span, - init: Option>, - pat: P, + init: Option>>, + pat: P<'a, hir::Pat<'a>>, source: hir::LocalSource, - ) -> hir::Stmt { + ) -> hir::Stmt<'a> { let local = hir::Local { pat, ty: None, @@ -5400,26 +5516,26 @@ impl<'a> LoweringContext<'a> { hir_id: self.next_id(), span, source, - attrs: ThinVec::new() + attrs: thin_hir_vec![], }; - self.stmt(span, hir::StmtKind::Local(P(local))) + self.stmt(span, hir::StmtKind::Local(p!(self, local))) } - fn expr_block_empty(&mut self, span: Span) -> hir::Expr { + fn expr_block_empty(&mut self, span: Span) -> hir::Expr<'a> { let blk = self.block_all(span, hir_vec![], None); - self.expr_block(P(blk), ThinVec::new()) + self.expr_block(p!(self, blk), thin_hir_vec![]) } - fn block_expr(&mut self, expr: P) -> hir::Block { + fn block_expr(&mut self, expr: P<'a, hir::Expr<'a>>) -> hir::Block<'a> { self.block_all(expr.span, hir::HirVec::new(), Some(expr)) } fn block_all( &mut self, span: Span, - stmts: hir::HirVec, - expr: Option>, - ) -> hir::Block { + stmts: hir::HirVec<'a, hir::Stmt<'a>>, + expr: Option>>, + ) -> hir::Block<'a> { hir::Block { stmts, expr, @@ -5430,12 +5546,12 @@ impl<'a> LoweringContext<'a> { } } - fn expr_unsafe(&mut self, expr: P) -> hir::Expr { + fn expr_unsafe(&mut self, expr: P<'a, hir::Expr<'a>>) -> hir::Expr<'a> { let hir_id = self.next_id(); let span = expr.span; self.expr( span, - hir::ExprKind::Block(P(hir::Block { + hir::ExprKind::Block(p!(self, hir::Block { stmts: hir_vec![], expr: Some(expr), hir_id, @@ -5443,30 +5559,31 @@ impl<'a> LoweringContext<'a> { span, targeted_by_break: false, }), None), - ThinVec::new(), + thin_hir_vec![], ) } /// Constructs a `true` or `false` literal pattern. - fn pat_bool(&mut self, span: Span, val: bool) -> P { + fn pat_bool(&mut self, span: Span, val: bool) -> P<'a, hir::Pat<'a>> { let lit = Spanned { span, node: LitKind::Bool(val) }; - let expr = self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new()); - self.pat(span, hir::PatKind::Lit(P(expr))) + let lit = P::from_existing(self.arena.alloc(lit)); + let expr = self.expr(span, hir::ExprKind::Lit(lit), thin_hir_vec![]); + self.pat(span, hir::PatKind::Lit(p!(self, expr))) } - fn pat_ok(&mut self, span: Span, pat: P) -> P { - self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![pat]) + fn pat_ok(&mut self, span: Span, pat: P<'a, hir::Pat<'a>>) -> P<'a, hir::Pat<'a>> { + self.pat_std_enum(span, &[sym::result, sym::Result, sym::Ok], hir_vec![self; pat]) } - fn pat_err(&mut self, span: Span, pat: P) -> P { - self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![pat]) + fn pat_err(&mut self, span: Span, pat: P<'a, hir::Pat<'a>>) -> P<'a, hir::Pat<'a>> { + self.pat_std_enum(span, &[sym::result, sym::Result, sym::Err], hir_vec![self; pat]) } - fn pat_some(&mut self, span: Span, pat: P) -> P { - self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![pat]) + fn pat_some(&mut self, span: Span, pat: P<'a, hir::Pat<'a>>) -> P<'a, hir::Pat<'a>> { + self.pat_std_enum(span, &[sym::option, sym::Option, sym::Some], hir_vec![self; pat]) } - fn pat_none(&mut self, span: Span) -> P { + fn pat_none(&mut self, span: Span) -> P<'a, hir::Pat<'a>> { self.pat_std_enum(span, &[sym::option, sym::Option, sym::None], hir_vec![]) } @@ -5474,10 +5591,10 @@ impl<'a> LoweringContext<'a> { &mut self, span: Span, components: &[Symbol], - subpats: hir::HirVec>, - ) -> P { + subpats: hir::HirVec<'a, P<'a, hir::Pat<'a>>>, + ) -> P<'a, hir::Pat<'a>> { let path = self.std_path(span, components, None, true); - let qpath = hir::QPath::Resolved(None, P(path)); + let qpath = hir::QPath::Resolved(None, p!(self, path)); let pt = if subpats.is_empty() { hir::PatKind::Path(qpath) } else { @@ -5486,7 +5603,7 @@ impl<'a> LoweringContext<'a> { self.pat(span, pt) } - fn pat_ident(&mut self, span: Span, ident: Ident) -> (P, hir::HirId) { + fn pat_ident(&mut self, span: Span, ident: Ident) -> (P<'a, hir::Pat<'a>>, hir::HirId) { self.pat_ident_binding_mode(span, ident, hir::BindingAnnotation::Unannotated) } @@ -5495,25 +5612,22 @@ impl<'a> LoweringContext<'a> { span: Span, ident: Ident, bm: hir::BindingAnnotation, - ) -> (P, hir::HirId) { + ) -> (P<'a, hir::Pat<'a>>, hir::HirId) { let hir_id = self.next_id(); - ( - P(hir::Pat { - hir_id, - node: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None), - span, - }), - hir_id - ) + (p!(self, hir::Pat { + hir_id, + node: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None), + span, + }), hir_id) } - fn pat_wild(&mut self, span: Span) -> P { + fn pat_wild(&mut self, span: Span) -> P<'a, hir::Pat<'a>> { self.pat(span, hir::PatKind::Wild) } - fn pat(&mut self, span: Span, pat: hir::PatKind) -> P { - P(hir::Pat { + fn pat(&mut self, span: Span, pat: hir::PatKind<'a>) -> P<'a, hir::Pat<'a>> { + p!(self, hir::Pat { hir_id: self.next_id(), node: pat, span, @@ -5527,22 +5641,28 @@ impl<'a> LoweringContext<'a> { &mut self, span: Span, components: &[Symbol], - params: Option>, + params: Option>>, is_value: bool, - ) -> hir::Path { + ) -> hir::Path<'a> { let mut path = self.resolver - .resolve_str_path(span, self.crate_root, components, is_value); - path.segments.last_mut().unwrap().args = params; - - for seg in path.segments.iter_mut() { + .resolve_str_path(self.arena, span, self.crate_root, components, is_value); + let mut segments = path.segments.into_vec(); + segments.last_mut().unwrap().args = params; + for seg in &mut segments { if seg.hir_id.is_some() { seg.hir_id = Some(self.next_id()); } } + path.segments = P::from_slice(self.arena, &segments); path } - fn ty_path(&mut self, mut hir_id: hir::HirId, span: Span, qpath: hir::QPath) -> hir::Ty { + fn ty_path( + &mut self, + mut hir_id: hir::HirId, + span: Span, + qpath: hir::QPath<'a> + ) -> hir::Ty<'a> { let node = match qpath { hir::QPath::Resolved(None, path) => { // Turn trait object paths into `TyKind::TraitObject` instead. @@ -5551,7 +5671,7 @@ impl<'a> LoweringContext<'a> { let principal = hir::PolyTraitRef { bound_generic_params: hir::HirVec::new(), trait_ref: hir::TraitRef { - path: path.and_then(|path| path), + path: **path, hir_ref_id: hir_id, }, span, @@ -5560,7 +5680,10 @@ impl<'a> LoweringContext<'a> { // The original ID is taken by the `PolyTraitRef`, // so the `Ty` itself needs a different one. hir_id = self.next_id(); - hir::TyKind::TraitObject(hir_vec![principal], self.elided_dyn_bound(span)) + hir::TyKind::TraitObject( + hir_vec![self; principal], + self.elided_dyn_bound(span) + ) } _ => hir::TyKind::Path(hir::QPath::Resolved(None, path)), } @@ -5631,10 +5754,12 @@ impl<'a> LoweringContext<'a> { /// `std::cell::Ref`; note that implicit lifetimes in these /// sorts of cases are deprecated. This may therefore report a warning or an /// error, depending on the mode. - fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> { + fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<'a, [hir::Lifetime]> { + let arena = self.arena; + (0..count) .map(|_| self.elided_path_lifetime(span)) - .collect() + .collect_hir_vec(arena) } fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime { @@ -5726,20 +5851,20 @@ impl<'a> LoweringContext<'a> { fn wrap_in_try_constructor( &mut self, method: Symbol, - e: hir::Expr, + e: hir::Expr<'a>, unstable_span: Span, - ) -> P { + ) -> P<'a, hir::Expr<'a>> { let path = &[sym::ops, sym::Try, method]; - let from_err = P(self.expr_std_path(unstable_span, path, None, - ThinVec::new())); - P(self.expr_call(e.span, from_err, hir_vec![e])) + let from_err = p!(self, self.expr_std_path(unstable_span, path, None, + thin_hir_vec![])); + p!(self, self.expr_call(e.span, from_err, hir_vec![self; e])) } fn lower_await( &mut self, await_span: Span, expr: &ast::Expr, - ) -> hir::ExprKind { + ) -> hir::ExprKind<'a> { // to: // // { @@ -5780,7 +5905,7 @@ impl<'a> LoweringContext<'a> { ); // let mut pinned = ; - let expr = P(self.lower_expr(expr)); + let expr = p!(self, self.lower_expr(expr)); let pinned_ident = Ident::with_empty_ctxt(sym::pinned); let (pinned_pat, pinned_pat_hid) = self.pat_ident_binding_mode( span, @@ -5798,7 +5923,7 @@ impl<'a> LoweringContext<'a> { // ::std::pin::Pin::new_unchecked(&mut pinned) // })` let poll_expr = { - let pinned = P(self.expr_ident(span, pinned_ident, pinned_pat_hid)); + let pinned = p!(self, self.expr_ident(span, pinned_ident, pinned_pat_hid)); let ref_mut_pinned = self.expr_mut_addr_of(span, pinned); let pin_ty_id = self.next_id(); let new_unchecked_expr_kind = self.expr_call_std_assoc_fn( @@ -5806,14 +5931,14 @@ impl<'a> LoweringContext<'a> { span, &[sym::pin, sym::Pin], "new_unchecked", - hir_vec![ref_mut_pinned], + hir_vec![self; ref_mut_pinned], ); - let new_unchecked = P(self.expr(span, new_unchecked_expr_kind, ThinVec::new())); + let new_unchecked = p!(self, self.expr(span, new_unchecked_expr_kind, thin_hir_vec![])); let unsafe_expr = self.expr_unsafe(new_unchecked); - P(self.expr_call_std_path( + p!(self, self.expr_call_std_path( gen_future_span, &[sym::future, sym::poll_with_tls_context], - hir_vec![unsafe_expr], + hir_vec![self; unsafe_expr], )) }; @@ -5823,20 +5948,20 @@ impl<'a> LoweringContext<'a> { let ready_arm = { let x_ident = Ident::with_empty_ctxt(sym::result); let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident); - let x_expr = P(self.expr_ident(span, x_ident, x_pat_hid)); + let x_expr = p!(self, self.expr_ident(span, x_ident, x_pat_hid)); let ready_pat = self.pat_std_enum( span, &[sym::task, sym::Poll, sym::Ready], - hir_vec![x_pat], + hir_vec![self; x_pat], ); let break_x = self.with_loop_scope(loop_node_id, |this| { let expr_break = hir::ExprKind::Break( this.lower_loop_destination(None), Some(x_expr), ); - P(this.expr(await_span, expr_break, ThinVec::new())) + p!(this, this.expr(await_span, expr_break, thin_hir_vec![])) }); - self.arm(hir_vec![ready_pat], break_x) + self.arm(hir_vec![self; ready_pat], break_x) }; // `::std::task::Poll::Pending => {}` @@ -5846,15 +5971,15 @@ impl<'a> LoweringContext<'a> { &[sym::task, sym::Poll, sym::Pending], hir_vec![], ); - let empty_block = P(self.expr_block_empty(span)); - self.arm(hir_vec![pending_pat], empty_block) + let empty_block = p!(self, self.expr_block_empty(span)); + self.arm(hir_vec![self; pending_pat], empty_block) }; let match_stmt = { - let match_expr = P(self.expr_match( + let match_expr = p!(self, self.expr_match( span, poll_expr, - hir_vec![ready_arm, pending_arm], + hir_vec![self; ready_arm, pending_arm], hir::MatchSource::AwaitDesugar, )); self.stmt(span, hir::StmtKind::Expr(match_expr)) @@ -5862,21 +5987,21 @@ impl<'a> LoweringContext<'a> { let yield_stmt = { let unit = self.expr_unit(span); - let yield_expr = P(self.expr( + let yield_expr = p!(self, self.expr( span, - hir::ExprKind::Yield(P(unit)), - ThinVec::new(), + hir::ExprKind::Yield(p!(self, unit)), + thin_hir_vec![], )); self.stmt(span, hir::StmtKind::Expr(yield_expr)) }; - let loop_block = P(self.block_all( + let loop_block = p!(self, self.block_all( span, - hir_vec![match_stmt, yield_stmt], + hir_vec![self; match_stmt, yield_stmt], None, )); - let loop_expr = P(hir::Expr { + let loop_expr = p!(self, hir::Expr { hir_id: loop_hir_id, node: hir::ExprKind::Loop( loop_block, @@ -5884,11 +6009,11 @@ impl<'a> LoweringContext<'a> { hir::LoopSource::Loop, ), span, - attrs: ThinVec::new(), + attrs: thin_hir_vec![], }); hir::ExprKind::Block( - P(self.block_all(span, hir_vec![pinned_let], Some(loop_expr))), + p!(self, self.block_all(span, hir_vec![self; pinned_let], Some(loop_expr))), None, ) } diff --git a/src/librustc/hir/map/blocks.rs b/src/librustc/hir/map/blocks.rs index f50037a746d97..47bd6b8a0f311 100644 --- a/src/librustc/hir/map/blocks.rs +++ b/src/librustc/hir/map/blocks.rs @@ -35,19 +35,19 @@ pub struct FnLikeNode<'a> { node: Node<'a> } /// corresponds to some FnLikeNode. trait MaybeFnLike { fn is_fn_like(&self) -> bool; } -impl MaybeFnLike for ast::Item { +impl MaybeFnLike for ast::Item<'_> { fn is_fn_like(&self) -> bool { match self.node { ast::ItemKind::Fn(..) => true, _ => false, } } } -impl MaybeFnLike for ast::ImplItem { +impl MaybeFnLike for ast::ImplItem<'_> { fn is_fn_like(&self) -> bool { match self.node { ast::ImplItemKind::Method(..) => true, _ => false, } } } -impl MaybeFnLike for ast::TraitItem { +impl MaybeFnLike for ast::TraitItem<'_> { fn is_fn_like(&self) -> bool { match self.node { ast::TraitItemKind::Method(_, ast::TraitMethod::Provided(_)) => true, @@ -56,7 +56,7 @@ impl MaybeFnLike for ast::TraitItem { } } -impl MaybeFnLike for ast::Expr { +impl MaybeFnLike for ast::Expr<'_> { fn is_fn_like(&self) -> bool { match self.node { ast::ExprKind::Closure(..) => true, @@ -71,7 +71,7 @@ impl MaybeFnLike for ast::Expr { #[derive(Copy, Clone)] pub enum Code<'a> { FnLike(FnLikeNode<'a>), - Expr(&'a Expr), + Expr(&'a Expr<'a>), } impl<'a> Code<'a> { @@ -99,10 +99,10 @@ impl<'a> Code<'a> { /// use when implementing FnLikeNode operations. struct ItemFnParts<'a> { ident: Ident, - decl: &'a ast::FnDecl, + decl: &'a ast::FnDecl<'a>, header: ast::FnHeader, - vis: &'a ast::Visibility, - generics: &'a ast::Generics, + vis: &'a ast::Visibility<'a>, + generics: &'a ast::Generics<'a>, body: ast::BodyId, id: ast::HirId, span: Span, @@ -112,7 +112,7 @@ struct ItemFnParts<'a> { /// These are all the components one can extract from a closure expr /// for use when implementing FnLikeNode operations. struct ClosureParts<'a> { - decl: &'a FnDecl, + decl: &'a FnDecl<'a>, body: ast::BodyId, id: ast::HirId, span: Span, @@ -156,7 +156,7 @@ impl<'a> FnLikeNode<'a> { |c: ClosureParts<'a>| c.body) } - pub fn decl(self) -> &'a FnDecl { + pub fn decl(self) -> &'a FnDecl<'a> { self.handle(|i: ItemFnParts<'a>| &*i.decl, |_, _, sig: &'a ast::MethodSig, _, _, _, _| &sig.decl, |c: ClosureParts<'a>| c.decl) @@ -193,7 +193,7 @@ impl<'a> FnLikeNode<'a> { let closure = |c: ClosureParts<'a>| { FnKind::Closure(c.attrs) }; - let method = |_, ident: Ident, sig: &'a ast::MethodSig, vis, _, _, attrs| { + let method = |_, ident: Ident, sig: &'a ast::MethodSig<'a>, vis, _, _, attrs| { FnKind::Method(ident, sig, vis, attrs) }; self.handle(item, method, closure) @@ -203,8 +203,8 @@ impl<'a> FnLikeNode<'a> { I: FnOnce(ItemFnParts<'a>) -> A, M: FnOnce(ast::HirId, Ident, - &'a ast::MethodSig, - Option<&'a ast::Visibility>, + &'a ast::MethodSig<'a>, + Option<&'a ast::Visibility<'a>>, ast::BodyId, Span, &'a [Attribute]) diff --git a/src/librustc/hir/map/collector.rs b/src/librustc/hir/map/collector.rs index 8a59f6b69bcd6..da3dd0624654e 100644 --- a/src/librustc/hir/map/collector.rs +++ b/src/librustc/hir/map/collector.rs @@ -22,7 +22,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHashe /// A visitor that walks over the HIR and collects `Node`s into a HIR map. pub(super) struct NodeCollector<'a, 'hir> { /// The crate - krate: &'hir Crate, + krate: &'hir Crate<'hir>, /// Source map source_map: &'a SourceMap, diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index 978a5556d31bf..e27dd54860cad 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -8,8 +8,6 @@ use crate::dep_graph::{DepGraph, DepNode, DepKind, DepNodeIndex}; use crate::hir::def_id::{CRATE_DEF_INDEX, DefId, LocalDefId}; -use crate::middle::cstore::CrateStoreDyn; - use rustc_target::spec::abi::Abi; use rustc_data_structures::svh::Svh; use rustc_data_structures::indexed_vec::IndexVec; @@ -28,6 +26,7 @@ use crate::util::common::time; use std::io; use std::result::Result::Err; use crate::ty::query::Providers; +use crate::ty::TyCtxt; pub mod blocks; mod collector; @@ -51,7 +50,7 @@ impl<'hir> Entry<'hir> { } } - fn fn_decl(&self) -> Option<&FnDecl> { + fn fn_decl(&self) -> Option<&FnDecl<'hir>> { match self.node { Node::Item(ref item) => { match item.node { @@ -134,20 +133,20 @@ impl<'hir> Entry<'hir> { } /// Stores a crate and any number of inlined items from other crates. -pub struct Forest { - krate: Crate, +pub struct Forest<'hir> { + krate: Crate<'hir>, pub dep_graph: DepGraph, } -impl Forest { - pub fn new(krate: Crate, dep_graph: &DepGraph) -> Forest { +impl<'hir> Forest<'hir> { + pub fn new(krate: Crate<'hir>, dep_graph: &DepGraph) -> Forest<'hir> { Forest { krate, dep_graph: dep_graph.clone(), } } - pub fn krate<'hir>(&'hir self) -> &'hir Crate { + pub fn krate(&'hir self) -> &'hir Crate<'hir> { self.dep_graph.read(DepNode::new_no_params(DepKind::Krate)); &self.krate } @@ -155,7 +154,7 @@ impl Forest { /// This is used internally in the dependency tracking system. /// Use the `krate` method to ensure your dependency on the /// crate is tracked. - pub fn untracked_krate<'hir>(&'hir self) -> &'hir Crate { + pub fn untracked_krate(&'hir self) -> &'hir Crate<'hir> { &self.krate } } @@ -170,7 +169,7 @@ pub(super) type HirEntryMap<'hir> = Vec { /// The backing storage for all the AST nodes. - pub forest: &'hir Forest, + pub forest: &'hir Forest<'hir>, /// Same as the dep_graph in forest, just available with one fewer /// deref. This is a gratuitous micro-optimization. @@ -398,7 +397,7 @@ impl<'hir> Map<'hir> { self.forest.krate() } - pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem { + pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> { self.read(id.hir_id); // N.B., intentionally bypass `self.forest.krate()` so that we @@ -406,7 +405,7 @@ impl<'hir> Map<'hir> { self.forest.krate.trait_item(id) } - pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem { + pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> { self.read(id.hir_id); // N.B., intentionally bypass `self.forest.krate()` so that we @@ -414,7 +413,7 @@ impl<'hir> Map<'hir> { self.forest.krate.impl_item(id) } - pub fn body(&self, id: BodyId) -> &'hir Body { + pub fn body(&self, id: BodyId) -> &'hir Body<'hir> { self.read(id.hir_id); // N.B., intentionally bypass `self.forest.krate()` so that we @@ -422,13 +421,13 @@ impl<'hir> Map<'hir> { self.forest.krate.body(id) } - pub fn fn_decl(&self, node_id: ast::NodeId) -> Option { + pub fn fn_decl(&self, node_id: ast::NodeId) -> Option> { let hir_id = self.node_to_hir_id(node_id); self.fn_decl_by_hir_id(hir_id) } // FIXME(@ljedrz): replace the `NodeId` variant. - pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option { + pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option> { if let Some(entry) = self.find_entry(hir_id) { entry.fn_decl().cloned() } else { @@ -605,7 +604,7 @@ impl<'hir> Map<'hir> { self.as_local_node_id(id).map(|id| self.get(id)) // read recorded by `get` } - pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics> { + pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics<'hir>> { self.get_if_local(id).and_then(|node| { match node { Node::ImplItem(ref impl_item) => Some(&impl_item.generics), @@ -930,34 +929,34 @@ impl<'hir> Map<'hir> { bug!("expected foreign mod or inlined parent, found {}", self.hir_to_string(parent)) } - pub fn expect_item(&self, id: NodeId) -> &'hir Item { + pub fn expect_item(&self, id: NodeId) -> &'hir Item<'hir> { let hir_id = self.node_to_hir_id(id); self.expect_item_by_hir_id(hir_id) } // FIXME(@ljedrz): replace the `NodeId` variant. - pub fn expect_item_by_hir_id(&self, id: HirId) -> &'hir Item { + pub fn expect_item_by_hir_id(&self, id: HirId) -> &'hir Item<'hir> { match self.find_by_hir_id(id) { // read recorded by `find` Some(Node::Item(item)) => item, _ => bug!("expected item, found {}", self.hir_to_string(id)) } } - pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem { + pub fn expect_impl_item(&self, id: HirId) -> &'hir ImplItem<'hir> { match self.find_by_hir_id(id) { Some(Node::ImplItem(item)) => item, _ => bug!("expected impl item, found {}", self.hir_to_string(id)) } } - pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem { + pub fn expect_trait_item(&self, id: HirId) -> &'hir TraitItem<'hir> { match self.find_by_hir_id(id) { Some(Node::TraitItem(item)) => item, _ => bug!("expected trait item, found {}", self.hir_to_string(id)) } } - pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData { + pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData<'hir> { match self.find_by_hir_id(id) { Some(Node::Item(i)) => { match i.node { @@ -972,27 +971,27 @@ impl<'hir> Map<'hir> { } } - pub fn expect_variant(&self, id: HirId) -> &'hir Variant { + pub fn expect_variant(&self, id: HirId) -> &'hir Variant<'hir> { match self.find_by_hir_id(id) { Some(Node::Variant(variant)) => variant, _ => bug!("expected variant, found {}", self.hir_to_string(id)), } } - pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem { + pub fn expect_foreign_item(&self, id: HirId) -> &'hir ForeignItem<'hir> { match self.find_by_hir_id(id) { Some(Node::ForeignItem(item)) => item, _ => bug!("expected foreign item, found {}", self.hir_to_string(id)) } } - pub fn expect_expr(&self, id: NodeId) -> &'hir Expr { + pub fn expect_expr(&self, id: NodeId) -> &'hir Expr<'hir> { let hir_id = self.node_to_hir_id(id); self.expect_expr_by_hir_id(hir_id) } // FIXME(@ljedrz): replace the `NodeId` variant. - pub fn expect_expr_by_hir_id(&self, id: HirId) -> &'hir Expr { + pub fn expect_expr_by_hir_id(&self, id: HirId) -> &'hir Expr<'hir> { match self.find_by_hir_id(id) { // read recorded by find Some(Node::Expr(expr)) => expr, _ => bug!("expected expr, found {}", self.hir_to_string(id)) @@ -1040,9 +1039,9 @@ impl<'hir> Map<'hir> { Some(Node::ImplItem(ref ii)) => Some(&ii.attrs[..]), Some(Node::Variant(ref v)) => Some(&v.node.attrs[..]), Some(Node::Field(ref f)) => Some(&f.attrs[..]), - Some(Node::Expr(ref e)) => Some(&*e.attrs), + Some(Node::Expr(ref e)) => Some(&****e.attrs), Some(Node::Stmt(ref s)) => Some(s.node.attrs()), - Some(Node::Arm(ref a)) => Some(&*a.attrs), + Some(Node::Arm(ref a)) => Some(&**a.attrs), Some(Node::GenericParam(param)) => Some(¶m.attrs[..]), // Unit/tuple structs/variants take the attributes straight from // the struct/variant definition. @@ -1250,52 +1249,54 @@ trait Named { impl Named for Spanned { fn name(&self) -> Name { self.node.name() } } -impl Named for Item { fn name(&self) -> Name { self.ident.name } } -impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } } -impl Named for VariantKind { fn name(&self) -> Name { self.ident.name } } -impl Named for StructField { fn name(&self) -> Name { self.ident.name } } -impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } } -impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } } - -pub fn map_crate<'hir>(sess: &crate::session::Session, - cstore: &CrateStoreDyn, - forest: &'hir Forest, - definitions: &'hir Definitions) - -> Map<'hir> { +impl Named for Item<'_> { fn name(&self) -> Name { self.ident.name } } +impl Named for ForeignItem<'_> { fn name(&self) -> Name { self.ident.name } } +impl Named for VariantKind<'_> { fn name(&self) -> Name { self.ident.name } } +impl Named for StructField<'_> { fn name(&self) -> Name { self.ident.name } } +impl Named for TraitItem<'_> { fn name(&self) -> Name { self.ident.name } } +impl Named for ImplItem<'_> { fn name(&self) -> Name { self.ident.name } } + +pub fn map_crate(tcx: TyCtxt<'_>) -> Map<'_> { + // FIXME: Error handling here? + let hir = tcx.lowered_hir(); + // Build the reverse mapping of `node_to_hir_id`. - let hir_to_node_id = definitions.node_to_hir_id.iter_enumerated() + let hir_to_node_id = hir.defs.node_to_hir_id.iter_enumerated() .map(|(node_id, &hir_id)| (hir_id, node_id)).collect(); let (map, crate_hash) = { - let hcx = crate::ich::StableHashingContext::new(sess, &forest.krate, definitions, cstore); - - let mut collector = NodeCollector::root(sess, - &forest.krate, - &forest.dep_graph, - &definitions, - &hir_to_node_id, - hcx); - intravisit::walk_crate(&mut collector, &forest.krate); - - let crate_disambiguator = sess.local_crate_disambiguator(); - let cmdline_args = sess.opts.dep_tracking_hash(); + let hcx = tcx.create_stable_hashing_context(); + let krate = hir.forest.untracked_krate(); + + let mut collector = NodeCollector::root( + tcx.sess, + krate, + &tcx.dep_graph, + &hir.defs, + &hir_to_node_id, + hcx + ); + intravisit::walk_crate(&mut collector, krate); + + let crate_disambiguator = tcx.sess.local_crate_disambiguator(); + let cmdline_args = tcx.sess.opts.dep_tracking_hash(); collector.finalize_and_compute_crate_hash( crate_disambiguator, - cstore, + tcx.cstore, cmdline_args ) }; let map = Map { - forest, - dep_graph: forest.dep_graph.clone(), + forest: &hir.forest, + dep_graph: tcx.dep_graph.clone(), crate_hash, map, hir_to_node_id, - definitions, + definitions: &hir.defs, }; - time(sess, "validate hir map", || { + time(tcx.sess, "validate hir map", || { hir_id_validator::check_crate(&map); }); diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 1b4c56c3453a1..39748e9d87403 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -10,9 +10,12 @@ pub use self::PrimTy::*; pub use self::UnOp::*; pub use self::UnsafeSource::*; +use crate::arena::Arena; use crate::hir::def::{Res, DefKind}; use crate::hir::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX}; -use crate::util::nodemap::{NodeMap, FxHashSet}; +use crate::hir::map::definitions::DefPathHash; +use crate::hir::def::Export; +use crate::util::nodemap::NodeMap; use crate::mir::mono::Linkage; use errors::FatalError; @@ -23,7 +26,6 @@ use syntax::ast::{self, CrateSugar, Ident, Name, NodeId, AsmDialect}; use syntax::ast::{Attribute, Label, LitKind, StrStyle, FloatTy, IntTy, UintTy}; use syntax::attr::{InlineAttr, OptimizeAttr}; use syntax::ext::hygiene::SyntaxContext; -use syntax::ptr::P; use syntax::symbol::{Symbol, kw}; use syntax::tokenstream::TokenStream; use syntax::util::parser::ExprPrecedence; @@ -31,7 +33,8 @@ use crate::ty::AdtKind; use crate::ty::query::Providers; use rustc_data_structures::sync::{par_for_each_in, Send, Sync}; -use rustc_data_structures::thin_vec::ThinVec; +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_data_structures::stable_hasher::StableVec; use rustc_macros::HashStable; use serialize::{self, Encoder, Encodable, Decoder, Decodable}; @@ -39,21 +42,16 @@ use std::collections::{BTreeSet, BTreeMap}; use std::fmt; use smallvec::SmallVec; +use self::ptr::P; + /// HIR doesn't commit to a concrete storage type and has its own alias for a vector. -/// It can be `Vec`, `P<[T]>` or potentially `Box<[T]>`, or some other container with similar +/// It can be `Vec`, `P<'a, [T]>` or potentially `Box<[T]>`, or some other container with similar /// behavior. Unlike AST, HIR is mostly a static structure, so we can use an owned slice instead /// of `Vec` to avoid keeping extra capacity. -pub type HirVec = P<[T]>; - -macro_rules! hir_vec { - ($elem:expr; $n:expr) => ( - $crate::hir::HirVec::from(vec![$elem; $n]) - ); - ($($x:expr),*) => ( - $crate::hir::HirVec::from(vec![$($x),*]) - ); -} +pub type HirVec<'a, T> = P<'a, [T]>; +pub type ThinHirVec<'a, T> = P<'a, P<'a, [T]>>; +pub mod ptr; pub mod check_attr; pub mod def; pub mod def_id; @@ -65,6 +63,35 @@ pub mod pat_util; pub mod print; pub mod upvars; +pub struct LoweredHir<'tcx> { + pub forest: map::Forest<'tcx>, + pub defs: map::Definitions, + + /// Export map produced by name resolution. + pub export_map: FxHashMap>>, + + pub maybe_unused_trait_imports: FxHashSet, + pub maybe_unused_extern_crates: Vec<(DefId, Span)>, + + /// A map of glob use to a set of names it actually imports. Currently only + /// used in save-analysis. + pub glob_map: FxHashMap>, + /// Extern prelude entries. The value is `true` if the entry was introduced + /// via `extern crate` item and not `--extern` option or compiler built-in. + pub extern_prelude: FxHashMap, + + /// A map from DefPathHash -> DefId. Includes DefIds from the local crate + /// as well as all upstream crates. Only populated in incremental mode. + pub def_path_hash_to_def_id: Option>, + + /// Map indicating what traits are in scope for places where this + /// is relevant; generated by resolve. + pub trait_map: FxHashMap>>, + +} + /// Uniquely identifies a node in the HIR of the current crate. It is /// composed of the `owner`, which is the `DefIndex` of the directly enclosing /// `hir::Item`, `hir::TraitItem`, or `hir::ImplItem` (i.e., the closest "item-like"), @@ -295,28 +322,28 @@ impl Lifetime { /// A `Path` is essentially Rust's notion of a name; for instance, /// `std::cmp::PartialEq`. It's represented as a sequence of identifiers, /// along with a bunch of supporting information. -#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)] -pub struct Path { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)] +pub struct Path<'a> { pub span: Span, /// The resolution for the path. pub res: Res, /// The segments in the path: the things separated by `::`. - pub segments: HirVec, + pub segments: HirVec<'a, PathSegment<'a>>, } -impl Path { +impl Path<'_> { pub fn is_global(&self) -> bool { !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot } } -impl fmt::Debug for Path { +impl fmt::Debug for Path<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "path({})", self) } } -impl fmt::Display for Path { +impl fmt::Display for Path<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", print::to_string(print::NO_ANN, |s| s.print_path(self, false))) } @@ -324,8 +351,8 @@ impl fmt::Display for Path { /// A segment of a path: an identifier, an optional lifetime, and a set of /// types. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct PathSegment { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct PathSegment<'a> { /// The identifier portion of this path segment. #[stable_hasher(project(name))] pub ident: Ident, @@ -342,7 +369,7 @@ pub struct PathSegment { /// this is more than just simple syntactic sugar; the use of /// parens affects the region binding rules, so we preserve the /// distinction. - pub args: Option>, + pub args: Option>>, /// Whether to infer remaining type parameters, if any. /// This only applies to expression and pattern paths, and @@ -351,9 +378,9 @@ pub struct PathSegment { pub infer_args: bool, } -impl PathSegment { +impl<'a> PathSegment<'a> { /// Converts an identifier to the corresponding segment. - pub fn from_ident(ident: Ident) -> PathSegment { + pub fn from_ident(ident: Ident) -> Self { PathSegment { ident, hir_id: None, @@ -364,10 +391,11 @@ impl PathSegment { } pub fn new( + arena: &'a Arena<'a>, ident: Ident, hir_id: Option, res: Option, - args: GenericArgs, + args: GenericArgs<'a>, infer_args: bool, ) -> Self { PathSegment { @@ -378,7 +406,7 @@ impl PathSegment { args: if args.is_empty() { None } else { - Some(P(args)) + Some(P::alloc(arena, args)) } } } @@ -386,7 +414,7 @@ impl PathSegment { // FIXME: hack required because you can't create a static // `GenericArgs`, so you can't just return a `&GenericArgs`. pub fn with_generic_args(&self, f: F) -> R - where F: FnOnce(&GenericArgs) -> R + where F: FnOnce(&GenericArgs<'a>) -> R { let dummy = GenericArgs::none(); f(if let Some(ref args) = self.args { @@ -397,20 +425,20 @@ impl PathSegment { } } -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] pub struct ConstArg { pub value: AnonConst, pub span: Span, } -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub enum GenericArg { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub enum GenericArg<'a> { Lifetime(Lifetime), - Type(Ty), + Type(Ty<'a>), Const(ConstArg), } -impl GenericArg { +impl GenericArg<'_> { pub fn span(&self) -> Span { match self { GenericArg::Lifetime(l) => l.span, @@ -435,20 +463,20 @@ impl GenericArg { } } -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct GenericArgs { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct GenericArgs<'a> { /// The generic arguments for this path segment. - pub args: HirVec, + pub args: HirVec<'a, GenericArg<'a>>, /// Bindings (equality constraints) on associated types, if present. /// E.g., `Foo`. - pub bindings: HirVec, + pub bindings: HirVec<'a, TypeBinding<'a>>, /// Were arguments written in parenthesized form `Fn(T) -> U`? /// This is required mostly for pretty-printing and diagnostics, /// but also for changing lifetime elision rules to be "function-like". pub parenthesized: bool, } -impl GenericArgs { +impl<'a> GenericArgs<'a> { pub fn none() -> Self { Self { args: HirVec::new(), @@ -461,7 +489,7 @@ impl GenericArgs { self.args.is_empty() && self.bindings.is_empty() && !self.parenthesized } - pub fn inputs(&self) -> &[Ty] { + pub fn inputs(&self) -> &[Ty<'a>] { if self.parenthesized { for arg in &self.args { match arg { @@ -509,13 +537,13 @@ pub enum TraitBoundModifier { /// `typeck::collect::compute_bounds` matches these against /// the "special" built-in traits (see `middle::lang_items`) and /// detects `Copy`, `Send` and `Sync`. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub enum GenericBound { - Trait(PolyTraitRef, TraitBoundModifier), +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub enum GenericBound<'a> { + Trait(PolyTraitRef<'a>, TraitBoundModifier), Outlives(Lifetime), } -impl GenericBound { +impl GenericBound<'_> { pub fn span(&self) -> Span { match self { &GenericBound::Trait(ref t, ..) => t.span, @@ -524,7 +552,7 @@ impl GenericBound { } } -pub type GenericBounds = HirVec; +pub type GenericBounds<'a> = HirVec<'a, GenericBound<'a>>; #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug, HashStable)] pub enum LifetimeParamKind { @@ -545,30 +573,30 @@ pub enum LifetimeParamKind { Error, } -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub enum GenericParamKind { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub enum GenericParamKind<'a> { /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`). Lifetime { kind: LifetimeParamKind, }, Type { - default: Option>, + default: Option>>, synthetic: Option, }, Const { - ty: P, + ty: P<'a, Ty<'a>>, } } -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct GenericParam { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct GenericParam<'a> { pub hir_id: HirId, pub name: ParamName, - pub attrs: HirVec, - pub bounds: GenericBounds, + pub attrs: HirVec<'a, Attribute>, + pub bounds: GenericBounds<'a>, pub span: Span, pub pure_wrt_drop: bool, - pub kind: GenericParamKind, + pub kind: GenericParamKind<'a>, } #[derive(Default)] @@ -580,15 +608,15 @@ pub struct GenericParamCount { /// Represents lifetimes and type parameters attached to a declaration /// of a function, enum, trait, etc. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct Generics { - pub params: HirVec, - pub where_clause: WhereClause, +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct Generics<'a> { + pub params: HirVec<'a, GenericParam<'a>>, + pub where_clause: WhereClause<'a>, pub span: Span, } -impl Generics { - pub fn empty() -> Generics { +impl Generics<'_> { + pub fn empty<'a>() -> Generics<'a> { Generics { params: HirVec::new(), where_clause: WhereClause { @@ -642,13 +670,13 @@ pub enum SyntheticTyParamKind { } /// A where-clause in a definition. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct WhereClause { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct WhereClause<'a> { pub hir_id: HirId, - pub predicates: HirVec, + pub predicates: HirVec<'a, WherePredicate<'a>>, } -impl WhereClause { +impl WhereClause<'_> { pub fn span(&self) -> Option { self.predicates.iter().map(|predicate| predicate.span()) .fold(None, |acc, i| match (acc, i) { @@ -661,17 +689,17 @@ impl WhereClause { } /// A single predicate in a where-clause. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub enum WherePredicate { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub enum WherePredicate<'a> { /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`). - BoundPredicate(WhereBoundPredicate), + BoundPredicate(WhereBoundPredicate<'a>), /// A lifetime predicate (e.g., `'a: 'b + 'c`). - RegionPredicate(WhereRegionPredicate), + RegionPredicate(WhereRegionPredicate<'a>), /// An equality predicate (unsupported). - EqPredicate(WhereEqPredicate), + EqPredicate(WhereEqPredicate<'a>), } -impl WherePredicate { +impl WherePredicate<'_> { pub fn span(&self) -> Span { match self { &WherePredicate::BoundPredicate(ref p) => p.span, @@ -682,32 +710,32 @@ impl WherePredicate { } /// A type bound (e.g., `for<'c> Foo: Send + Clone + 'c`). -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct WhereBoundPredicate { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct WhereBoundPredicate<'a> { pub span: Span, /// Any generics from a `for` binding. - pub bound_generic_params: HirVec, + pub bound_generic_params: HirVec<'a, GenericParam<'a>>, /// The type being bounded. - pub bounded_ty: P, + pub bounded_ty: P<'a, Ty<'a>>, /// Trait and lifetime bounds (e.g., `Clone + Send + 'static`). - pub bounds: GenericBounds, + pub bounds: GenericBounds<'a>, } /// A lifetime predicate (e.g., `'a: 'b + 'c`). -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct WhereRegionPredicate { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct WhereRegionPredicate<'a> { pub span: Span, pub lifetime: Lifetime, - pub bounds: GenericBounds, + pub bounds: GenericBounds<'a>, } /// An equality predicate (e.g., `T = int`); currently unsupported. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct WhereEqPredicate { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct WhereEqPredicate<'a> { pub hir_id: HirId, pub span: Span, - pub lhs_ty: P, - pub rhs_ty: P, + pub lhs_ty: P<'a, Ty<'a>>, + pub rhs_ty: P<'a, Ty<'a>>, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] @@ -726,11 +754,11 @@ pub struct ModuleItems { /// /// [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] -pub struct Crate { - pub module: Mod, - pub attrs: HirVec, +pub struct Crate<'a> { + pub module: Mod<'a>, + pub attrs: HirVec<'a, Attribute>, pub span: Span, - pub exported_macros: HirVec, + pub exported_macros: HirVec<'a, MacroDef<'a>>, // N.B., we use a BTreeMap here so that `visit_all_items` iterates // over the ids in increasing order. In principle it should not @@ -738,11 +766,11 @@ pub struct Crate { // does, because it can affect the order in which errors are // detected, which in turn can make compile-fail tests yield // slightly different results. - pub items: BTreeMap, + pub items: BTreeMap>, - pub trait_items: BTreeMap, - pub impl_items: BTreeMap, - pub bodies: BTreeMap, + pub trait_items: BTreeMap>, + pub impl_items: BTreeMap>, + pub bodies: BTreeMap>, pub trait_impls: BTreeMap>, /// A list of the body ids written out in the order in which they @@ -756,7 +784,7 @@ pub struct Crate { pub modules: BTreeMap, } -impl Crate { +impl Crate<'_> { pub fn item(&self, id: HirId) -> &Item { &self.items[&id] } @@ -820,28 +848,30 @@ impl Crate { /// A macro definition, in this crate or imported from another. /// /// Not parsed directly, but created on macro import or `macro_rules!` expansion. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct MacroDef { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct MacroDef<'a> { pub name: Name, - pub vis: Visibility, - pub attrs: HirVec, + pub vis: Visibility<'a>, + pub attrs: HirVec<'a, Attribute>, pub hir_id: HirId, pub span: Span, - pub body: TokenStream, + pub body: P<'a, TokenStream>, pub legacy: bool, } /// A block of statements `{ .. }`, which may have a label (in this case the /// `targeted_by_break` field will be `true`) and may be `unsafe` by means of /// the `rules` being anything but `DefaultBlock`. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct Block { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct Block<'a> { + /// Statements in a block /// Statements in a block. - pub stmts: HirVec, + pub stmts: HirVec<'a, Stmt<'a>>, /// An expression at the end of the block /// without a semicolon, if any. - pub expr: Option>, + pub expr: Option>>, #[stable_hasher(ignore)] + pub hir_id: HirId, /// Distinguishes between `unsafe { ... }` and `{ ... }`. pub rules: BlockCheckMode, @@ -852,22 +882,22 @@ pub struct Block { pub targeted_by_break: bool, } -#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)] -pub struct Pat { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)] +pub struct Pat<'a> { #[stable_hasher(ignore)] pub hir_id: HirId, - pub node: PatKind, + pub node: PatKind<'a>, pub span: Span, } -impl fmt::Debug for Pat { +impl fmt::Debug for Pat<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "pat({}: {})", self.hir_id, print::to_string(print::NO_ANN, |s| s.print_pat(self))) } } -impl Pat { +impl Pat<'_> { // FIXME(#19596) this is a workaround, but there should be a better way fn walk_(&self, it: &mut G) -> bool where G: FnMut(&Pat) -> bool @@ -915,15 +945,16 @@ impl Pat { /// Patterns like the fields of Foo `{ x, ref y, ref mut z }` /// are treated the same as` x: x, y: ref y, z: ref mut z`, /// except `is_shorthand` is true. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct FieldPat { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct FieldPat<'a> { #[stable_hasher(ignore)] pub hir_id: HirId, /// The identifier for the field. #[stable_hasher(project(name))] + #[stable_hasher(project(name))] pub ident: Ident, /// The pattern the field is destructured to. - pub pat: P, + pub pat: P<'a, Pat<'a>>, pub is_shorthand: bool, } @@ -957,8 +988,8 @@ pub enum RangeEnd { Excluded, } -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub enum PatKind { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub enum PatKind<'a> { /// Represents a wildcard pattern (i.e., `_`). Wild, @@ -966,40 +997,40 @@ pub enum PatKind { /// The `HirId` is the canonical ID for the variable being bound, /// (e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID), /// which is the pattern ID of the first `x`. - Binding(BindingAnnotation, HirId, Ident, Option>), + Binding(BindingAnnotation, HirId, Ident, Option>>), /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`). /// The `bool` is `true` in the presence of a `..`. - Struct(QPath, HirVec>, bool), + Struct(QPath<'a>, HirVec<'a, Spanned>>, bool), /// A tuple struct/variant pattern `Variant(x, y, .., z)`. /// If the `..` pattern fragment is present, then `Option` denotes its position. /// `0 <= position <= subpats.len()` - TupleStruct(QPath, HirVec>, Option), + TupleStruct(QPath<'a>, HirVec<'a, P<'a, Pat<'a>>>, Option), /// A path pattern for an unit struct/variant or a (maybe-associated) constant. - Path(QPath), + Path(QPath<'a>), /// A tuple pattern (e.g., `(a, b)`). /// If the `..` pattern fragment is present, then `Option` denotes its position. /// `0 <= position <= subpats.len()` - Tuple(HirVec>, Option), + Tuple(HirVec<'a, P<'a, Pat<'a>>>, Option), /// A `box` pattern. - Box(P), + Box(P<'a, Pat<'a>>), /// A reference pattern (e.g., `&mut (a, b)`). - Ref(P, Mutability), + Ref(P<'a, Pat<'a>>, Mutability), /// A literal. - Lit(P), + Lit(P<'a, Expr<'a>>), /// A range pattern (e.g., `1...2` or `1..2`). - Range(P, P, RangeEnd), + Range(P<'a, Expr<'a>>, P<'a, Expr<'a>>, RangeEnd), /// `[a, b, ..i, y, z]` is represented as: /// `PatKind::Slice(box [a, b], Some(i), box [y, z])`. - Slice(HirVec>, Option>, HirVec>), + Slice(HirVec<'a, P<'a, Pat<'a>>>, Option>>, HirVec<'a, P<'a, Pat<'a>>>), } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, HashStable, @@ -1182,14 +1213,14 @@ impl UnOp { } /// A statement. -#[derive(Clone, RustcEncodable, RustcDecodable)] -pub struct Stmt { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)] +pub struct Stmt<'a> { pub hir_id: HirId, - pub node: StmtKind, + pub node: StmtKind<'a>, pub span: Span, } -impl fmt::Debug for Stmt { +impl fmt::Debug for Stmt<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "stmt({}: {})", self.hir_id, print::to_string(print::NO_ANN, |s| s.print_stmt(self))) @@ -1197,22 +1228,22 @@ impl fmt::Debug for Stmt { } /// The contents of a statement. -#[derive(Clone, RustcEncodable, RustcDecodable, HashStable)] -pub enum StmtKind { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, HashStable)] +pub enum StmtKind<'a> { /// A local (`let`) binding. - Local(P), + Local(P<'a, Local<'a>>), /// An item binding. Item(ItemId), /// An expression without a trailing semi-colon (must have unit type). - Expr(P), + Expr(P<'a, Expr<'a>>), /// An expression with a trailing semi-colon (may have any type). - Semi(P), + Semi(P<'a, Expr<'a>>), } -impl StmtKind { +impl StmtKind<'_> { pub fn attrs(&self) -> &[Attribute] { match *self { StmtKind::Local(ref l) => &l.attrs, @@ -1224,16 +1255,16 @@ impl StmtKind { } /// Represents a `let` statement (i.e., `let : = ;`). -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct Local { - pub pat: P, +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct Local<'a> { + pub pat: P<'a, Pat<'a>>, /// Type annotation, if any (otherwise the type will be inferred). - pub ty: Option>, + pub ty: Option>>, /// Initializer expression to set the value, if any. - pub init: Option>, + pub init: Option>>, pub hir_id: HirId, pub span: Span, - pub attrs: ThinVec, + pub attrs: ThinHirVec<'a, Attribute>, /// Can be `ForLoopDesugar` if the `let` statement is part of a `for` loop /// desugaring. Otherwise will be `Normal`. pub source: LocalSource, @@ -1241,31 +1272,31 @@ pub struct Local { /// Represents a single arm of a `match` expression, e.g. /// ` (if ) => `. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct Arm { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct Arm<'a> { #[stable_hasher(ignore)] pub hir_id: HirId, pub span: Span, - pub attrs: HirVec, + pub attrs: HirVec<'a, Attribute>, /// Multiple patterns can be combined with `|` - pub pats: HirVec>, + pub pats: HirVec<'a, P<'a, Pat<'a>>>, /// Optional guard clause. - pub guard: Option, + pub guard: Option>, /// The expression the arm evaluates to if this arm matches. - pub body: P, + pub body: P<'a, Expr<'a>>, } -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub enum Guard { - If(P), +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub enum Guard<'a> { + If(P<'a, Expr<'a>>), } -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct Field { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct Field<'a> { #[stable_hasher(ignore)] pub hir_id: HirId, pub ident: Ident, - pub expr: P, + pub expr: P<'a, Expr<'a>>, pub span: Span, pub is_shorthand: bool, } @@ -1310,14 +1341,14 @@ pub struct BodyId { /// /// All bodies have an **owner**, which can be accessed via the HIR /// map using `body_owner_def_id()`. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug)] -pub struct Body { - pub arguments: HirVec, - pub value: Expr, +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug)] +pub struct Body<'a> { + pub arguments: HirVec<'a, Arg<'a>>, + pub value: Expr<'a>, pub is_generator: bool, } -impl Body { +impl Body<'_> { pub fn id(&self) -> BodyId { BodyId { hir_id: self.value.hir_id, @@ -1364,19 +1395,19 @@ pub struct AnonConst { } /// An expression -#[derive(Clone, RustcEncodable, RustcDecodable)] -pub struct Expr { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable)] +pub struct Expr<'a> { pub span: Span, - pub node: ExprKind, - pub attrs: ThinVec, + pub node: ExprKind<'a>, + pub attrs: ThinHirVec<'a, Attribute>, pub hir_id: HirId, } // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(target_arch = "x86_64")] -static_assert_size!(Expr, 72); +static_assert_size!(Expr<'static>, 72); -impl Expr { +impl Expr<'_> { pub fn precedence(&self) -> ExprPrecedence { match self.node { ExprKind::Box(_) => ExprPrecedence::Box, @@ -1468,26 +1499,26 @@ impl Expr { } } -impl fmt::Debug for Expr { +impl fmt::Debug for Expr<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "expr({}: {})", self.hir_id, print::to_string(print::NO_ANN, |s| s.print_expr(self))) } } -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub enum ExprKind { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub enum ExprKind<'a> { /// A `box x` expression. - Box(P), + Box(P<'a, Expr<'a>>), /// An array (e.g., `[a, b, c, d]`). - Array(HirVec), + Array(HirVec<'a, Expr<'a>>), /// A function call. /// /// The first field resolves to the function itself (usually an `ExprKind::Path`), /// and the second field is the list of arguments. /// This also represents calling the constructor of /// tuple-like ADTs such as tuple structs and enum variants. - Call(P, HirVec), + Call(P<'a, Expr<'a>>, HirVec<'a, Expr<'a>>), /// A method call (e.g., `x.foo::<'static, Bar, Baz>(a, b, c, d)`). /// /// The `PathSegment`/`Span` represent the method name and its generic arguments @@ -1497,109 +1528,109 @@ pub enum ExprKind { /// and the remaining elements are the rest of the arguments. /// Thus, `x.foo::(a, b, c, d)` is represented as /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`. - MethodCall(P, Span, HirVec), + MethodCall(P<'a, PathSegment<'a>>, Span, HirVec<'a, Expr<'a>>), /// A tuple (e.g., `(a, b, c ,d)`). - Tup(HirVec), + Tup(HirVec<'a, Expr<'a>>), /// A binary operation (e.g., `a + b`, `a * b`). - Binary(BinOp, P, P), + Binary(BinOp, P<'a, Expr<'a>>, P<'a, Expr<'a>>), /// A unary operation (e.g., `!x`, `*x`). - Unary(UnOp, P), + Unary(UnOp, P<'a, Expr<'a>>), /// A literal (e.g., `1`, `"foo"`). - Lit(Lit), + Lit(P<'a, Lit>), /// A cast (e.g., `foo as f64`). - Cast(P, P), + Cast(P<'a, Expr<'a>>, P<'a, Ty<'a>>), /// A type reference (e.g., `Foo`). - Type(P, P), + Type(P<'a, Expr<'a>>, P<'a, Ty<'a>>), /// Wraps the expression in a terminating scope. /// This makes it semantically equivalent to `{ let _t = expr; _t }`. /// /// This construct only exists to tweak the drop order in HIR lowering. /// An example of that is the desugaring of `for` loops. - DropTemps(P), + DropTemps(P<'a, Expr<'a>>), /// A while loop, with an optional label /// /// I.e., `'label: while expr { }`. - While(P, P, Option, D}` - Enum(EnumDef, Generics), + Enum(EnumDef<'a>, Generics<'a>), /// A struct definition, e.g., `struct Foo {x: A}` - Struct(VariantData, Generics), + Struct(VariantData<'a>, Generics<'a>), /// A union definition, e.g., `union Foo {x: A, y: B}` - Union(VariantData, Generics), + Union(VariantData<'a>, Generics<'a>), /// Represents a Trait Declaration - Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec), + Trait(IsAuto, Unsafety, Generics<'a>, GenericBounds<'a>, HirVec<'a, TraitItemRef>), /// Represents a Trait Alias Declaration - TraitAlias(Generics, GenericBounds), + TraitAlias(Generics<'a>, GenericBounds<'a>), /// An implementation, eg `impl Trait for Foo { .. }` Impl(Unsafety, ImplPolarity, Defaultness, - Generics, - Option, // (optional) trait this impl implements - P, // self - HirVec), + Generics<'a>, + Option>, // (optional) trait this impl implements + P<'a, Ty<'a>>, // self + HirVec<'a, ImplItemRef<'a>>), } -impl ItemKind { +impl ItemKind<'_> { pub fn descriptive_variant(&self) -> &str { match *self { ItemKind::ExternCrate(..) => "extern crate", @@ -2445,7 +2476,7 @@ impl ItemKind { /// type or method, and whether it is public). This allows other /// passes to find the impl they want without loading the ID (which /// means fewer edges in the incremental compilation graph). -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] pub struct TraitItemRef { pub id: TraitItemId, #[stable_hasher(project(name))] @@ -2461,14 +2492,14 @@ pub struct TraitItemRef { /// type or method, and whether it is public). This allows other /// passes to find the impl they want without loading the ID (which /// means fewer edges in the incremental compilation graph). -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct ImplItemRef { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct ImplItemRef<'a> { pub id: ImplItemId, #[stable_hasher(project(name))] pub ident: Ident, pub kind: AssocItemKind, pub span: Span, - pub vis: Visibility, + pub vis: Visibility<'a>, pub defaultness: Defaultness, } @@ -2480,29 +2511,29 @@ pub enum AssocItemKind { Existential, } -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub struct ForeignItem { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub struct ForeignItem<'a> { #[stable_hasher(project(name))] pub ident: Ident, - pub attrs: HirVec, - pub node: ForeignItemKind, + pub attrs: HirVec<'a, Attribute>, + pub node: ForeignItemKind<'a>, pub hir_id: HirId, pub span: Span, - pub vis: Visibility, + pub vis: Visibility<'a>, } /// An item within an `extern` block. -#[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub enum ForeignItemKind { +#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Debug, HashStable)] +pub enum ForeignItemKind<'a> { /// A foreign function. - Fn(P, HirVec, Generics), + Fn(P<'a, FnDecl<'a>>, HirVec<'a, Ident>, Generics<'a>), /// A foreign static item (`static ext: u8`). - Static(P, Mutability), + Static(P<'a, Ty<'a>>, Mutability), /// A foreign type. Type, } -impl ForeignItemKind { +impl ForeignItemKind<'_> { pub fn descriptive_variant(&self) -> &str { match *self { ForeignItemKind::Fn(..) => "foreign function", @@ -2651,33 +2682,33 @@ impl CodegenFnAttrs { } #[derive(Copy, Clone, Debug)] -pub enum Node<'hir> { - Item(&'hir Item), - ForeignItem(&'hir ForeignItem), - TraitItem(&'hir TraitItem), - ImplItem(&'hir ImplItem), - Variant(&'hir Variant), - Field(&'hir StructField), - AnonConst(&'hir AnonConst), - Expr(&'hir Expr), - Stmt(&'hir Stmt), - PathSegment(&'hir PathSegment), - Ty(&'hir Ty), - TraitRef(&'hir TraitRef), - Binding(&'hir Pat), - Pat(&'hir Pat), - Arm(&'hir Arm), - Block(&'hir Block), - Local(&'hir Local), - MacroDef(&'hir MacroDef), +pub enum Node<'a> { + Item(&'a Item<'a>), + ForeignItem(&'a ForeignItem<'a>), + TraitItem(&'a TraitItem<'a>), + ImplItem(&'a ImplItem<'a>), + Variant(&'a Variant<'a>), + Field(&'a StructField<'a>), + AnonConst(&'a AnonConst), + Expr(&'a Expr<'a>), + Stmt(&'a Stmt<'a>), + PathSegment(&'a PathSegment<'a>), + Ty(&'a Ty<'a>), + TraitRef(&'a TraitRef<'a>), + Binding(&'a Pat<'a>), + Pat(&'a Pat<'a>), + Arm(&'a Arm<'a>), + Block(&'a Block<'a>), + Local(&'a Local<'a>), + MacroDef(&'a MacroDef<'a>), /// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants /// with synthesized constructors. - Ctor(&'hir VariantData), + Ctor(&'a VariantData<'a>), - Lifetime(&'hir Lifetime), - GenericParam(&'hir GenericParam), - Visibility(&'hir Visibility), + Lifetime(&'a Lifetime), + GenericParam(&'a GenericParam<'a>), + Visibility(&'a Visibility<'a>), Crate, } diff --git a/src/librustc/hir/pat_util.rs b/src/librustc/hir/pat_util.rs index 0d2c7d393bb89..f2c853d5b8bf6 100644 --- a/src/librustc/hir/pat_util.rs +++ b/src/librustc/hir/pat_util.rs @@ -43,7 +43,7 @@ impl EnumerateAndAdjustIterator for T { } } -impl hir::Pat { +impl hir::Pat<'_> { pub fn is_refutable(&self) -> bool { match self.node { PatKind::Lit(_) | @@ -162,7 +162,7 @@ impl hir::Pat { } } -impl hir::Arm { +impl hir::Arm<'_> { /// Checks if the patterns for this arm contain any `ref` or `ref mut` /// bindings, and if yes whether its containing mutable ones or just immutables ones. pub fn contains_explicit_ref_binding(&self) -> Option { diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index 7b0a499fa5c66..11d0dd0717990 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -6,7 +6,6 @@ use syntax::parse::lexer::comments; use syntax::print::pp::{self, Breaks}; use syntax::print::pp::Breaks::{Consistent, Inconsistent}; use syntax::print::pprust::{self, PrintState}; -use syntax::ptr::P; use syntax::symbol::kw; use syntax::util::parser::{self, AssocOp, Fixity}; use syntax_pos::{self, BytePos, FileName}; @@ -14,6 +13,7 @@ use syntax_pos::{self, BytePos, FileName}; use crate::hir; use crate::hir::{PatKind, GenericBound, TraitBoundModifier, RangeEnd}; use crate::hir::{GenericParam, GenericParamKind, GenericArg}; +use hir::ptr::P; use std::borrow::Cow; use std::cell::Cell; @@ -22,11 +22,11 @@ use std::vec; pub enum AnnNode<'a> { Name(&'a ast::Name), - Block(&'a hir::Block), - Item(&'a hir::Item), + Block(&'a hir::Block<'a>), + Item(&'a hir::Item<'a>), SubItem(hir::HirId), - Expr(&'a hir::Expr), - Pat(&'a hir::Pat), + Expr(&'a hir::Expr<'a>), + Pat(&'a hir::Pat<'a>), } pub enum Nested { @@ -56,7 +56,7 @@ pub struct NoAnn; impl PpAnn for NoAnn {} pub const NO_ANN: &dyn PpAnn = &NoAnn; -impl PpAnn for hir::Crate { +impl PpAnn for hir::Crate<'_> { fn try_fetch_item(&self, item: hir::HirId) -> Option<&hir::Item> { Some(self.item(item)) } @@ -930,7 +930,7 @@ impl<'a> State<'a> { hir::TraitItemKind::Type(ref bounds, ref default) => { self.print_associated_type(ti.ident, Some(bounds), - default.as_ref().map(|ty| &**ty))?; + default.as_ref().map(|ty| &***ty))?; } } self.ann.post(self, AnnNode::SubItem(ti.hir_id)) @@ -991,7 +991,7 @@ impl<'a> State<'a> { self.maybe_print_comment(st.span.lo())?; match st.node { hir::StmtKind::Local(ref loc) => { - self.print_local(loc.init.deref(), |this| this.print_local_decl(&loc))?; + self.print_local(loc.init.map(|e| &**e), |this| this.print_local_decl(&loc))?; } hir::StmtKind::Item(item) => { self.ann.nested(self, Nested::Item(item))? diff --git a/src/librustc/hir/ptr.rs b/src/librustc/hir/ptr.rs new file mode 100644 index 0000000000000..9a62959785ca4 --- /dev/null +++ b/src/librustc/hir/ptr.rs @@ -0,0 +1,188 @@ +use std::fmt::{self, Display, Debug}; +use std::ops::Deref; +use std::{slice, vec}; +use crate::arena::Arena; + +use serialize::{Encodable, Decodable, Encoder, Decoder}; + +use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult, + HashStable}; + +pub trait IteratorExt: Iterator { + fn collect_hir_vec<'a>(self, arena: &'a Arena<'a>) -> P<'a, [Self::Item]>; +} + +impl IteratorExt for T where T::Item: Copy { + fn collect_hir_vec<'a>(self, arena: &'a Arena<'a>) -> P<'a, [Self::Item]> { + P::from_iter(arena, self) + } +} + +#[derive(Hash, PartialEq, Eq)] +#[repr(transparent)] +pub struct P<'a, T: ?Sized>(&'a T); + +impl<'a, T: 'a+?Sized> Clone for P<'a, T> { + #[inline] + fn clone(&self) -> Self { + P(self.0) + } +} +impl<'a, T: 'a+?Sized> Copy for P<'a, T> {} + +impl<'a, T: ?Sized> Deref for P<'a, T> { + type Target = &'a T; + + #[inline] + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl<'a, T: Copy> P<'a, [T]> { + #[inline] + pub fn from_slice(arena: &'a Arena<'a>, slice: &[T]) -> Self { + if slice.is_empty() { + P::new() + } else { + P(arena.alloc_slice(slice)) + } + } + + #[inline] + pub fn from_iter>(arena: &'a Arena<'a>, iter: I) -> Self { + P(arena.alloc_from_iter(iter)) + } +} + +impl<'a, T: Copy> P<'a, T> { + /// Equivalent to and_then(|x| x) + #[inline] + pub fn into_inner(&self) -> T { + *self.0 + } + + /// Move out of the pointer. + /// Intended for chaining transformations not covered by `map`. + #[inline] + pub fn and_then(&self, f: F) -> U where + F: FnOnce(T) -> U, + { + f(*self.0) + } + + #[inline] + pub fn alloc(arena: &'a Arena<'a>, inner: T) -> Self { + P(arena.alloc(inner)) + } +} + +impl<'a, T> P<'a, T> { + #[inline] + pub fn empty_thin() -> P<'a, P<'a, [T]>> { + P(&P(&[])) + } +} + +impl<'a, T: ?Sized> P<'a, T> { + // FIXME: Doesn't work with deserialization + #[inline] + pub fn from_existing(val: &'a T) -> Self { + P(val) + } +} + +impl Debug for P<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(self.0, f) + } +} + +impl Display for P<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} + +impl fmt::Pointer for P<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Pointer::fmt(&(self.0 as *const T), f) + } +} + +impl Decodable for P<'_, T> { + fn decode(_d: &mut D) -> Result { + panic!() + } +} + +impl Encodable for P<'_, T> { + fn encode(&self, s: &mut S) -> Result<(), S::Error> { + (**self).encode(s) + } +} + +impl<'a, T> P<'a, [T]> { + #[inline] + pub fn new() -> Self { + P(&[]) + } + + #[inline(never)] + pub fn into_vec(self) -> Vec where T: Clone { + (*self.0).iter().cloned().collect() + } +} + +impl Default for P<'_, [T]> { + /// Creates an empty `P<[T]>`. + #[inline] + fn default() -> Self { + P::new() + } +} + +impl Into> for P<'_, [T]> { + fn into(self) -> Vec { + self.into_vec() + } +} + +impl IntoIterator for P<'_, [T]> { + type Item = T; + type IntoIter = vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.into_vec().into_iter() + } +} + +impl<'a, T> IntoIterator for &'a P<'_, [T]> { + type Item = &'a T; + type IntoIter = slice::Iter<'a, T>; + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl Encodable for P<'_, [T]> { + fn encode(&self, s: &mut S) -> Result<(), S::Error> { + Encodable::encode(&**self, s) + } +} + +impl Decodable for P<'_, [T]> { + fn decode(_d: &mut D) -> Result { + panic!() + } +} + +impl HashStable for P<'_, T> + where T: ?Sized + HashStable +{ + fn hash_stable(&self, + hcx: &mut CTX, + hasher: &mut StableHasher) { + (**self).hash_stable(hcx, hasher); + } +} diff --git a/src/librustc/ich/hcx.rs b/src/librustc/ich/hcx.rs index 4ef4d70ee1dcd..1146f1348ee55 100644 --- a/src/librustc/ich/hcx.rs +++ b/src/librustc/ich/hcx.rs @@ -61,12 +61,12 @@ pub enum NodeIdHashingMode { /// We could also just store a plain reference to the hir::Crate but we want /// to avoid that the crate is used to get untracked access to all of the HIR. #[derive(Clone, Copy)] -struct BodyResolver<'tcx>(&'tcx hir::Crate); +struct BodyResolver<'tcx>(&'tcx hir::Crate<'tcx>); impl<'tcx> BodyResolver<'tcx> { // Return a reference to the hir::Body with the given BodyId. // DOES NOT DO ANY TRACKING, use carefully. - fn body(self, id: hir::BodyId) -> &'tcx hir::Body { + fn body(self, id: hir::BodyId) -> &'tcx hir::Body<'tcx> { self.0.body(id) } } diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs index f2f909b6af156..8a7b0ae28fe60 100644 --- a/src/librustc/ich/impls_hir.rs +++ b/src/librustc/ich/impls_hir.rs @@ -136,7 +136,7 @@ impl_stable_hash_for!(struct ast::Label { ident }); -impl<'a> HashStable> for hir::Ty { +impl<'a> HashStable> for hir::Ty<'_> { fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { @@ -153,20 +153,15 @@ impl<'a> HashStable> for hir::Ty { } } -impl_stable_hash_for_spanned!(hir::FieldPat); +impl_stable_hash_for_spanned!(for<'hir> hir::FieldPat<'hir>); impl_stable_hash_for_spanned!(hir::BinOpKind); -impl_stable_hash_for!(struct hir::Stmt { - hir_id, - node, - span, -}); - +impl_stable_hash_for_spanned!(for<'hir> hir::StmtKind<'hir>); impl_stable_hash_for_spanned!(ast::Name); -impl<'a> HashStable> for hir::Expr { +impl<'a> HashStable> for hir::Expr<'_> { fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { @@ -194,7 +189,7 @@ impl_stable_hash_for!(struct ast::Ident { span, }); -impl<'a> HashStable> for hir::TraitItem { +impl<'a> HashStable> for hir::TraitItem<'_> { fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { @@ -218,7 +213,7 @@ impl<'a> HashStable> for hir::TraitItem { } -impl<'a> HashStable> for hir::ImplItem { +impl<'a> HashStable> for hir::ImplItem<'_> { fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { @@ -250,7 +245,7 @@ impl_stable_hash_for!(enum ::syntax::ast::CrateSugar { PubCrate, }); -impl<'a> HashStable> for hir::VisibilityKind { +impl<'a> HashStable> for hir::VisibilityKind<'_> { fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { @@ -273,9 +268,9 @@ impl<'a> HashStable> for hir::VisibilityKind { } } -impl_stable_hash_for_spanned!(hir::VisibilityKind); +impl_stable_hash_for_spanned!(for<'hir> hir::VisibilityKind<'hir>); -impl<'a> HashStable> for hir::Mod { +impl<'a> HashStable> for hir::Mod<'_> { fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { @@ -304,10 +299,9 @@ impl<'a> HashStable> for hir::Mod { } } -impl_stable_hash_for_spanned!(hir::VariantKind); - +impl_stable_hash_for_spanned!(for<'hir> hir::VariantKind<'hir>); -impl<'a> HashStable> for hir::Item { +impl<'a> HashStable> for hir::Item<'_> { fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { @@ -330,7 +324,7 @@ impl<'a> HashStable> for hir::Item { } } -impl<'a> HashStable> for hir::Body { +impl<'a> HashStable> for hir::Body<'_> { fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { diff --git a/src/librustc/infer/error_reporting/need_type_info.rs b/src/librustc/infer/error_reporting/need_type_info.rs index 362a680f53c9a..c28be4c8fa6eb 100644 --- a/src/librustc/infer/error_reporting/need_type_info.rs +++ b/src/librustc/infer/error_reporting/need_type_info.rs @@ -13,8 +13,8 @@ struct FindLocalByTypeVisitor<'a, 'tcx> { infcx: &'a InferCtxt<'a, 'tcx>, target_ty: Ty<'tcx>, hir_map: &'a hir::map::Map<'tcx>, - found_local_pattern: Option<&'tcx Pat>, - found_arg_pattern: Option<&'tcx Pat>, + found_local_pattern: Option<&'tcx Pat<'tcx>>, + found_arg_pattern: Option<&'tcx Pat<'tcx>>, found_ty: Option>, } diff --git a/src/librustc/infer/error_reporting/nice_region_error/find_anon_type.rs b/src/librustc/infer/error_reporting/nice_region_error/find_anon_type.rs index fa95ea1013253..5a65bf598e671 100644 --- a/src/librustc/infer/error_reporting/nice_region_error/find_anon_type.rs +++ b/src/librustc/infer/error_reporting/nice_region_error/find_anon_type.rs @@ -25,7 +25,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { &self, region: Region<'tcx>, br: &ty::BoundRegion, - ) -> Option<(&hir::Ty, &hir::FnDecl)> { + ) -> Option<(&'tcx hir::Ty<'tcx>, &'tcx hir::FnDecl<'tcx>)> { if let Some(anon_reg) = self.tcx().is_suitable_region(region) { let def_id = anon_reg.def_id; if let Some(node_id) = self.tcx().hir().as_local_node_id(def_id) { @@ -50,7 +50,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { .iter() .filter_map(|arg| self.find_component_for_bound_region(arg, br)) .next() - .map(|ty| (ty, &**fndecl)); + .map(|ty| (ty, &***fndecl)); } } None @@ -62,7 +62,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { &self, arg: &'tcx hir::Ty, br: &ty::BoundRegion, - ) -> Option<(&'tcx hir::Ty)> { + ) -> Option<(&'tcx hir::Ty<'tcx>)> { let mut nested_visitor = FindNestedTypeVisitor { tcx: self.tcx(), bound_region: *br, @@ -88,7 +88,7 @@ struct FindNestedTypeVisitor<'tcx> { bound_region: ty::BoundRegion, // The type where the anonymous lifetime appears // for e.g., Vec<`&u8`> and <`&u8`> - found_type: Option<&'tcx hir::Ty>, + found_type: Option<&'tcx hir::Ty<'tcx>>, current_index: ty::DebruijnIndex, } diff --git a/src/librustc/infer/error_reporting/nice_region_error/util.rs b/src/librustc/infer/error_reporting/nice_region_error/util.rs index 017f36b020988..60b9fd9e1a2cc 100644 --- a/src/librustc/infer/error_reporting/nice_region_error/util.rs +++ b/src/librustc/infer/error_reporting/nice_region_error/util.rs @@ -12,7 +12,7 @@ use syntax_pos::Span; #[derive(Debug)] pub(super) struct AnonymousArgInfo<'tcx> { // the argument corresponding to the anonymous region - pub arg: &'tcx hir::Arg, + pub arg: &'tcx hir::Arg<'tcx>, // the type corresponding to the anonymopus region argument pub arg_ty: Ty<'tcx>, // the ty::BoundRegion corresponding to the anonymous region diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index e2f2799d9634d..acc3d46e12692 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -28,9 +28,9 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")] -#![deny(rust_2018_idioms)] #![deny(internal)] -#![deny(unused_lifetimes)] +// FIXME: Enable +//#![deny(unused_lifetimes)] #![allow(explicit_outlives_requirements)] #![feature(arbitrary_self_types)] diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index 468d909e5497b..12479187c21dd 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -527,7 +527,7 @@ pub struct LateContext<'a, 'tcx: 'a> { last_node_with_lint_attrs: hir::HirId, /// Generic type parameters in scope for the item we are in. - pub generics: Option<&'tcx hir::Generics>, + pub generics: Option<&'tcx hir::Generics<'tcx>>, /// We are only looking at one module only_module: bool, @@ -966,13 +966,13 @@ for LateContextAndPass<'a, 'tcx, T> { self.context.tables = old_tables; } - fn visit_body(&mut self, body: &'tcx hir::Body) { + fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) { lint_callback!(self, check_body, body); hir_visit::walk_body(self, body); lint_callback!(self, check_body_post, body); } - fn visit_item(&mut self, it: &'tcx hir::Item) { + fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) { let generics = self.context.generics.take(); self.context.generics = it.node.generics(); self.with_lint_attrs(it.hir_id, &it.attrs, |cx| { @@ -985,7 +985,7 @@ for LateContextAndPass<'a, 'tcx, T> { self.context.generics = generics; } - fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem) { + fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) { self.with_lint_attrs(it.hir_id, &it.attrs, |cx| { cx.with_param_env(it.hir_id, |cx| { lint_callback!(cx, check_foreign_item, it); @@ -995,12 +995,12 @@ for LateContextAndPass<'a, 'tcx, T> { }) } - fn visit_pat(&mut self, p: &'tcx hir::Pat) { + fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { lint_callback!(self, check_pat, p); hir_visit::walk_pat(self, p); } - fn visit_expr(&mut self, e: &'tcx hir::Expr) { + fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { self.with_lint_attrs(e.hir_id, &e.attrs, |cx| { lint_callback!(cx, check_expr, e); hir_visit::walk_expr(cx, e); @@ -1008,7 +1008,7 @@ for LateContextAndPass<'a, 'tcx, T> { }) } - fn visit_stmt(&mut self, s: &'tcx hir::Stmt) { + fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) { // statement attributes are actually just attributes on one of // - item // - local @@ -1018,7 +1018,7 @@ for LateContextAndPass<'a, 'tcx, T> { hir_visit::walk_stmt(self, s); } - fn visit_fn(&mut self, fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl, + fn visit_fn(&mut self, fk: hir_visit::FnKind<'tcx>, decl: &'tcx hir::FnDecl<'tcx>, body_id: hir::BodyId, span: Span, id: hir::HirId) { // Wrap in tables here, not just in visit_nested_body, // in order for `check_fn` to be able to use them. @@ -1032,9 +1032,9 @@ for LateContextAndPass<'a, 'tcx, T> { } fn visit_variant_data(&mut self, - s: &'tcx hir::VariantData, + s: &'tcx hir::VariantData<'tcx>, name: ast::Name, - g: &'tcx hir::Generics, + g: &'tcx hir::Generics<'tcx>, item_id: hir::HirId, _: Span) { lint_callback!(self, check_struct_def, s, name, g, item_id); @@ -1042,7 +1042,7 @@ for LateContextAndPass<'a, 'tcx, T> { lint_callback!(self, check_struct_def_post, s, name, g, item_id); } - fn visit_struct_field(&mut self, s: &'tcx hir::StructField) { + fn visit_struct_field(&mut self, s: &'tcx hir::StructField<'tcx>) { self.with_lint_attrs(s.hir_id, &s.attrs, |cx| { lint_callback!(cx, check_struct_field, s); hir_visit::walk_struct_field(cx, s); @@ -1050,8 +1050,8 @@ for LateContextAndPass<'a, 'tcx, T> { } fn visit_variant(&mut self, - v: &'tcx hir::Variant, - g: &'tcx hir::Generics, + v: &'tcx hir::Variant<'tcx>, + g: &'tcx hir::Generics<'tcx>, item_id: hir::HirId) { self.with_lint_attrs(v.node.id, &v.node.attrs, |cx| { lint_callback!(cx, check_variant, v, g); @@ -1060,7 +1060,7 @@ for LateContextAndPass<'a, 'tcx, T> { }) } - fn visit_ty(&mut self, t: &'tcx hir::Ty) { + fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) { lint_callback!(self, check_ty, t); hir_visit::walk_ty(self, t); } @@ -1069,7 +1069,7 @@ for LateContextAndPass<'a, 'tcx, T> { lint_callback!(self, check_name, sp, name); } - fn visit_mod(&mut self, m: &'tcx hir::Mod, s: Span, n: hir::HirId) { + fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, s: Span, n: hir::HirId) { if !self.context.only_module { self.process_mod(m, s, n); } @@ -1082,39 +1082,39 @@ for LateContextAndPass<'a, 'tcx, T> { }) } - fn visit_block(&mut self, b: &'tcx hir::Block) { + fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) { lint_callback!(self, check_block, b); hir_visit::walk_block(self, b); lint_callback!(self, check_block_post, b); } - fn visit_arm(&mut self, a: &'tcx hir::Arm) { + fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) { lint_callback!(self, check_arm, a); hir_visit::walk_arm(self, a); } - fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam) { + fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) { lint_callback!(self, check_generic_param, p); hir_visit::walk_generic_param(self, p); } - fn visit_generics(&mut self, g: &'tcx hir::Generics) { + fn visit_generics(&mut self, g: &'tcx hir::Generics<'tcx>) { lint_callback!(self, check_generics, g); hir_visit::walk_generics(self, g); } - fn visit_where_predicate(&mut self, p: &'tcx hir::WherePredicate) { + fn visit_where_predicate(&mut self, p: &'tcx hir::WherePredicate<'tcx>) { lint_callback!(self, check_where_predicate, p); hir_visit::walk_where_predicate(self, p); } - fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef, + fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef<'tcx>, m: hir::TraitBoundModifier) { lint_callback!(self, check_poly_trait_ref, t, m); hir_visit::walk_poly_trait_ref(self, t, m); } - fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) { + fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { let generics = self.context.generics.take(); self.context.generics = Some(&trait_item.generics); self.with_lint_attrs(trait_item.hir_id, &trait_item.attrs, |cx| { @@ -1127,7 +1127,7 @@ for LateContextAndPass<'a, 'tcx, T> { self.context.generics = generics; } - fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) { + fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { let generics = self.context.generics.take(); self.context.generics = Some(&impl_item.generics); self.with_lint_attrs(impl_item.hir_id, &impl_item.attrs, |cx| { diff --git a/src/librustc/macros.rs b/src/librustc/macros.rs index 09fa924efc7ab..72bca58c1197c 100644 --- a/src/librustc/macros.rs +++ b/src/librustc/macros.rs @@ -168,6 +168,19 @@ macro_rules! impl_stable_hash_for { #[macro_export] macro_rules! impl_stable_hash_for_spanned { + (for<$($lt:lifetime),*> $T:path) => ( + impl<'a, 'tcx $(, $lt)*> HashStable> + for ::syntax::source_map::Spanned<$T> + { + #[inline] + fn hash_stable(&self, + hcx: &mut StableHashingContext<'a>, + hasher: &mut StableHasher) { + self.node.hash_stable(hcx, hasher); + self.span.hash_stable(hcx, hasher); + } + } + ); ($T:path) => ( impl HashStable> for ::syntax::source_map::Spanned<$T> diff --git a/src/librustc/middle/dead.rs b/src/librustc/middle/dead.rs index 0356e7e10724d..7f74039f69ff4 100644 --- a/src/librustc/middle/dead.rs +++ b/src/librustc/middle/dead.rs @@ -351,15 +351,15 @@ fn has_allow_dead_code_or_lang_attr( // or // 2) We are not sure to be live or not // * Implementation of a trait method -struct LifeSeeder<'k, 'tcx: 'k> { +struct LifeSeeder<'tcx> { worklist: Vec, - krate: &'k hir::Crate, + krate: &'tcx hir::Crate<'tcx>, tcx: TyCtxt<'tcx>, // see `MarkSymbolVisitor::struct_constructors` struct_constructors: FxHashMap, } -impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> { +impl<'v, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'tcx> { fn visit_item(&mut self, item: &hir::Item) { let allow_dead_code = has_allow_dead_code_or_lang_attr(self.tcx, item.hir_id, @@ -427,7 +427,7 @@ impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> { fn create_and_seed_worklist<'tcx>( tcx: TyCtxt<'tcx>, access_levels: &privacy::AccessLevels, - krate: &hir::Crate, + krate: &'tcx hir::Crate<'tcx>, ) -> (Vec, FxHashMap) { let worklist = access_levels.map.iter().filter_map(|(&id, level)| { if level >= &privacy::AccessLevel::Reachable { @@ -455,7 +455,7 @@ fn create_and_seed_worklist<'tcx>( fn find_live<'tcx>( tcx: TyCtxt<'tcx>, access_levels: &privacy::AccessLevels, - krate: &hir::Crate, + krate: &'tcx hir::Crate<'tcx>, ) -> FxHashSet { let (worklist, struct_constructors) = create_and_seed_worklist(tcx, access_levels, krate); let mut symbol_visitor = MarkSymbolVisitor { diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index 61770e6f48705..00af658453770 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -17,8 +17,8 @@ use crate::middle::region; use crate::ty::{self, DefIdTree, TyCtxt, adjustment}; use crate::hir::{self, PatKind}; +use hir::ptr::P; use std::rc::Rc; -use syntax::ptr::P; use syntax_pos::Span; use crate::util::nodemap::ItemLocalSet; @@ -308,7 +308,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { } } - pub fn consume_body(&mut self, body: &hir::Body) { + pub fn consume_body(&mut self, body: &hir::Body<'tcx>) { debug!("consume_body(body={:?})", body); for arg in &body.arguments { @@ -348,13 +348,13 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { self.delegate.consume(consume_id, consume_span, cmt, mode); } - fn consume_exprs(&mut self, exprs: &[hir::Expr]) { + fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) { for expr in exprs { self.consume_expr(&expr); } } - pub fn consume_expr(&mut self, expr: &hir::Expr) { + pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) { debug!("consume_expr(expr={:?})", expr); let cmt = return_if_err!(self.mc.cat_expr(expr)); @@ -364,8 +364,8 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { fn mutate_expr(&mut self, span: Span, - assignment_expr: &hir::Expr, - expr: &hir::Expr, + assignment_expr: &hir::Expr<'_>, + expr: &hir::Expr<'_>, mode: MutateMode) { let cmt = return_if_err!(self.mc.cat_expr(expr)); self.delegate.mutate(assignment_expr.hir_id, span, &cmt, mode); @@ -373,7 +373,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { } fn borrow_expr(&mut self, - expr: &hir::Expr, + expr: &hir::Expr<'_>, r: ty::Region<'tcx>, bk: ty::BorrowKind, cause: LoanCause) { @@ -386,11 +386,11 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { self.walk_expr(expr) } - fn select_from_expr(&mut self, expr: &hir::Expr) { + fn select_from_expr(&mut self, expr: &hir::Expr<'_>) { self.walk_expr(expr) } - pub fn walk_expr(&mut self, expr: &hir::Expr) { + pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) { debug!("walk_expr(expr={:?})", expr); self.walk_adjustment(expr); @@ -552,7 +552,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { } } - fn walk_callee(&mut self, call: &hir::Expr, callee: &hir::Expr) { + fn walk_callee(&mut self, call: &hir::Expr<'_>, callee: &hir::Expr<'_>) { let callee_ty = return_if_err!(self.mc.expr_ty_adjusted(callee)); debug!("walk_callee: callee={:?} callee_ty={:?}", callee, callee_ty); @@ -592,7 +592,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { } } - fn walk_stmt(&mut self, stmt: &hir::Stmt) { + fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) { match stmt.node { hir::StmtKind::Local(ref local) => { self.walk_local(&local); @@ -610,7 +610,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { } } - fn walk_local(&mut self, local: &hir::Local) { + fn walk_local(&mut self, local: &hir::Local<'_>) { match local.init { None => { local.pat.each_binding(|_, hir_id, span, _| { @@ -632,7 +632,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { /// Indicates that the value of `blk` will be consumed, meaning either copied or moved /// depending on its type. - fn walk_block(&mut self, blk: &hir::Block) { + fn walk_block(&mut self, blk: &hir::Block<'_>) { debug!("walk_block(blk.hir_id={})", blk.hir_id); for stmt in &blk.stmts { @@ -645,15 +645,15 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { } fn walk_struct_expr(&mut self, - fields: &[hir::Field], - opt_with: &Option>) { + fields: &[hir::Field<'_>], + opt_with: &Option>>) { // Consume the expressions supplying values for each field. for field in fields { self.consume_expr(&field.expr); } let with_expr = match *opt_with { - Some(ref w) => &**w, + Some(ref w) => &***w, None => { return; } }; @@ -701,7 +701,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { // Invoke the appropriate delegate calls for anything that gets // consumed or borrowed as part of the automatic adjustment // process. - fn walk_adjustment(&mut self, expr: &hir::Expr) { + fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) { let adjustments = self.mc.tables.expr_adjustments(expr); let mut cmt = return_if_err!(self.mc.cat_expr_unadjusted(expr)); for adjustment in adjustments { @@ -738,7 +738,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { /// `expr`. `cmt_base` is the mem-categorized form of `expr` /// after all relevant autoderefs have occurred. fn walk_autoref(&mut self, - expr: &hir::Expr, + expr: &hir::Expr<'_>, cmt_base: &mc::cmt_<'tcx>, autoref: &adjustment::AutoBorrow<'tcx>) { debug!("walk_autoref(expr.hir_id={} cmt_base={:?} autoref={:?})", @@ -780,7 +780,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { } } - fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm) -> TrackMatchMode { + fn arm_move_mode(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm<'_>) -> TrackMatchMode { let mut mode = Unknown; for pat in &arm.pats { self.determine_pat_move_mode(discr_cmt.clone(), &pat, &mut mode); @@ -788,7 +788,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { mode } - fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm, mode: MatchMode) { + fn walk_arm(&mut self, discr_cmt: mc::cmt<'tcx>, arm: &hir::Arm<'_>, mode: MatchMode) { for pat in &arm.pats { self.walk_pat(discr_cmt.clone(), &pat, mode); } @@ -802,7 +802,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or /// let binding, and *not* a match arm or nested pat.) - fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) { + fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat<'_>) { let mut mode = Unknown; self.determine_pat_move_mode(cmt_discr.clone(), pat, &mut mode); let mode = mode.match_mode(); @@ -814,7 +814,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { /// copy, or borrow. fn determine_pat_move_mode(&mut self, cmt_discr: mc::cmt<'tcx>, - pat: &hir::Pat, + pat: &hir::Pat<'_>, mode: &mut TrackMatchMode) { debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr, pat); @@ -840,7 +840,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { /// The core driver for walking a pattern; `match_mode` must be /// established up front, e.g., via `determine_pat_move_mode` (see /// also `walk_irrefutable_pat` for patterns that stand alone). - fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) { + fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat<'_>, match_mode: MatchMode) { debug!("walk_pat(cmt_discr={:?}, pat={:?})", cmt_discr, pat); let tcx = self.tcx(); @@ -927,7 +927,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { })); } - fn walk_captures(&mut self, closure_expr: &hir::Expr, fn_decl_span: Span) { + fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>, fn_decl_span: Span) { debug!("walk_captures({:?})", closure_expr); let closure_def_id = self.tcx().hir().local_def_id_from_hir_id(closure_expr.hir_id); diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 260935a38d6d4..540ea17c67c31 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -111,13 +111,13 @@ use std::io::prelude::*; use std::io; use std::rc::Rc; use syntax::ast::{self, NodeId}; -use syntax::ptr::P; use syntax::symbol::{kw, sym}; use syntax_pos::Span; use crate::hir; use crate::hir::{Expr, HirId}; use crate::hir::def_id::DefId; +use crate::hir::ptr::P; use crate::hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap}; /// For use with `propagate_through_loop`. @@ -125,7 +125,7 @@ enum LoopKind<'a> { /// An endless `loop` loop. LoopLoop, /// A `while` loop, with the given expression as condition. - WhileLoop(&'a Expr), + WhileLoop(&'a Expr<'a>), } #[derive(Copy, Clone, PartialEq)] @@ -976,7 +976,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { if blk.targeted_by_break { self.break_ln.insert(blk.hir_id, succ); } - let succ = self.propagate_through_opt_expr(blk.expr.as_ref().map(|e| &**e), succ); + let succ = self.propagate_through_opt_expr(blk.expr.as_ref().map(|e| &***e), succ); blk.stmts.iter().rev().fold(succ, |succ, stmt| { self.propagate_through_stmt(stmt, succ) }) @@ -1000,7 +1000,10 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { // initialization, which is mildly more complex than checking // once at the func header but otherwise equivalent. - let succ = self.propagate_through_opt_expr(local.init.as_ref().map(|e| &**e), succ); + let succ = self.propagate_through_opt_expr( + local.init.as_ref().map(|e| &***e), + succ, + ); self.define_bindings_in_pat(&local.pat, succ) } hir::StmtKind::Item(..) => succ, @@ -1087,14 +1090,14 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { let body_succ = self.propagate_through_expr(&arm.body, succ); let guard_succ = self.propagate_through_opt_expr( - arm.guard.as_ref().map(|hir::Guard::If(e)| &**e), + arm.guard.as_ref().map(|hir::Guard::If(e)| &***e), body_succ ); // only consider the first pattern; any later patterns must have // the same bindings, and we also consider the first pattern to be // the "authoritative" set of ids let arm_succ = - self.define_bindings_in_arm_pats(arm.pats.first().map(|p| &**p), + self.define_bindings_in_arm_pats(arm.pats.first().map(|p| &***p), guard_succ); self.merge_from_succ(ln, arm_succ, first_merge); first_merge = false; @@ -1105,7 +1108,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { hir::ExprKind::Ret(ref o_e) => { // ignore succ and subst exit_ln: let exit_ln = self.s.exit_ln; - self.propagate_through_opt_expr(o_e.as_ref().map(|e| &**e), exit_ln) + self.propagate_through_opt_expr(o_e.as_ref().map(|e| &***e), exit_ln) } hir::ExprKind::Break(label, ref opt_expr) => { @@ -1119,7 +1122,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { // look it up in the break loop nodes table match target { - Some(b) => self.propagate_through_opt_expr(opt_expr.as_ref().map(|e| &**e), b), + Some(b) => self.propagate_through_opt_expr(opt_expr.as_ref().map(|e| &***e), b), None => span_bug!(expr.span, "break to unknown label") } } @@ -1164,7 +1167,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { } hir::ExprKind::Struct(_, ref fields, ref with_expr) => { - let succ = self.propagate_through_opt_expr(with_expr.as_ref().map(|e| &**e), succ); + let succ = self.propagate_through_opt_expr(with_expr.as_ref().map(|e| &***e), succ); fields.iter().rev().fold(succ, |succ, field| { self.propagate_through_expr(&field.expr, succ) }) diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 3b21b81df7b43..7c0fe9ed88a8a 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -276,12 +276,12 @@ pub trait HirNode { fn span(&self) -> Span; } -impl HirNode for hir::Expr { +impl HirNode for hir::Expr<'_> { fn hir_id(&self) -> hir::HirId { self.hir_id } fn span(&self) -> Span { self.span } } -impl HirNode for hir::Pat { +impl HirNode for hir::Pat<'_> { fn hir_id(&self) -> hir::HirId { self.hir_id } fn span(&self) -> Span { self.span } } diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index 8b1eeeb7f51b7..f657db8cb65a0 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -1326,7 +1326,7 @@ impl<'tcx> Visitor<'tcx> for RegionResolutionVisitor<'tcx> { resolve_expr(self, ex); } fn visit_local(&mut self, l: &'tcx Local) { - resolve_local(self, Some(&l.pat), l.init.as_ref().map(|e| &**e)); + resolve_local(self, Some(&l.pat), l.init.as_ref().map(|e| &***e)); } } diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 8bc3158bd3c7d..71dc66935912e 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -8,6 +8,7 @@ use crate::hir::def::{Res, DefKind}; use crate::hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; use crate::hir::map::Map; +use crate::hir::ptr::P; use crate::hir::{GenericArg, GenericParam, ItemLocalId, LifetimeName, Node, ParamName}; use crate::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt}; @@ -21,7 +22,6 @@ use std::cell::Cell; use std::mem::replace; use syntax::ast; use syntax::attr; -use syntax::ptr::P; use syntax::symbol::{kw, sym}; use syntax_pos::Span; @@ -456,7 +456,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { replace(&mut self.labels_in_fn, saved); } - fn visit_item(&mut self, item: &'tcx hir::Item) { + fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { match item.node { hir::ItemKind::Fn(ref decl, _, ref generics, _) => { self.visit_early_late(None, decl, generics, |this| { @@ -538,7 +538,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } } - fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) { + fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) { match item.node { hir::ForeignItemKind::Fn(ref decl, _, ref generics) => { self.visit_early_late(None, decl, generics, |this| { @@ -554,7 +554,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } } - fn visit_ty(&mut self, ty: &'tcx hir::Ty) { + fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) { debug!("visit_ty: id={:?} ty={:?}", ty.hir_id, ty); match ty.node { hir::TyKind::BareFn(ref c) => { @@ -764,7 +764,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } } - fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) { + fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { use self::hir::TraitItemKind::*; match trait_item.node { Method(ref sig, _) => { @@ -816,7 +816,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } } - fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) { + fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { use self::hir::ImplItemKind::*; match impl_item.node { Method(ref sig, _) => { @@ -908,7 +908,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { self.resolve_lifetime_ref(lifetime_ref); } - fn visit_path(&mut self, path: &'tcx hir::Path, _: hir::HirId) { + fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _: hir::HirId) { for (i, segment) in path.segments.iter().enumerate() { let depth = path.segments.len() - i - 1; if let Some(ref args) = segment.args { @@ -917,15 +917,15 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } } - fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl) { + fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) { let output = match fd.output { hir::DefaultReturn(_) => None, - hir::Return(ref ty) => Some(&**ty), + hir::Return(ref ty) => Some(&***ty), }; self.visit_fn_like_elision(&fd.inputs, output); } - fn visit_generics(&mut self, generics: &'tcx hir::Generics) { + fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { check_mixed_explicit_and_in_band_defs(self.tcx, &generics.params); for param in &generics.params { match param.kind { diff --git a/src/librustc/query/mod.rs b/src/librustc/query/mod.rs index 10efef54526a6..3acaea20d6dea 100644 --- a/src/librustc/query/mod.rs +++ b/src/librustc/query/mod.rs @@ -31,6 +31,24 @@ use syntax_pos::symbol::InternedString; // as they will raise an fatal error on query cycles instead. rustc_queries! { Other { + query prepare_outputs(_: ()) -> Result, ErrorReported> { + no_hash + eval_always + desc { "preparing outputs" } + } + + query lower_ast_to_hir(_: ()) -> Result<&'tcx hir::LoweredHir<'tcx>, ErrorReported> { + no_hash + eval_always + desc { "lowering AST to HIR" } + } + + query hir_map(_: CrateNum) -> &'tcx hir::map::Map<'tcx> { + no_hash + eval_always + desc { "indexing HIR" } + } + /// Records the type of every item. query type_of(key: DefId) -> Ty<'tcx> { cache { key.is_local() } diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index f4d523b92338c..bedb2c2a9a966 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -496,6 +496,15 @@ impl BorrowckMode { } } +#[derive(Clone)] +pub struct InputsAndOutputs { + pub input: Input, + pub input_path: Option, + pub output_dir: Option, + pub output_file: Option, +} + +#[derive(Clone)] pub enum Input { /// Loads source from file File(PathBuf), diff --git a/src/librustc/traits/error_reporting.rs b/src/librustc/traits/error_reporting.rs index 42bde3563492f..560a597e6b548 100644 --- a/src/librustc/traits/error_reporting.rs +++ b/src/librustc/traits/error_reporting.rs @@ -1052,12 +1052,12 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { (self.tcx.sess.source_map().def_span(span), self.tcx.hir().body(id).arguments.iter() .map(|arg| { if let hir::Pat { - node: hir::PatKind::Tuple(args, _), + node: hir::PatKind::Tuple(ref args, _), span, .. - } = arg.pat.clone().into_inner() { + } = *arg.pat { ArgKind::Tuple( - Some(span), + Some(*span), args.iter().map(|pat| { let snippet = self.tcx.sess.source_map() .span_to_snippet(pat.span).unwrap(); diff --git a/src/librustc/ty/context.rs b/src/librustc/ty/context.rs index e5d06532b3a16..2cf6b227b2436 100644 --- a/src/librustc/ty/context.rs +++ b/src/librustc/ty/context.rs @@ -6,12 +6,12 @@ use crate::arena::Arena; use crate::dep_graph::DepGraph; use crate::dep_graph::{self, DepNode, DepConstructor}; use crate::session::Session; -use crate::session::config::{BorrowckMode, OutputFilenames}; +use crate::session::config::{BorrowckMode, InputsAndOutputs}; use crate::session::config::CrateType; use crate::middle; use crate::hir::{TraitCandidate, HirId, ItemKind, ItemLocalId, Node}; -use crate::hir::def::{Res, DefKind, Export}; -use crate::hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE}; +use crate::hir::def::{Res, DefKind}; +use crate::hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use crate::hir::map as hir_map; use crate::hir::map::DefPathHash; use crate::lint::{self, Lint}; @@ -46,7 +46,7 @@ use crate::ty::{BoundVar, BindingMode}; use crate::ty::CanonicalPolyFnSig; use crate::util::common::ErrorReported; use crate::util::nodemap::{DefIdMap, DefIdSet, ItemLocalMap, ItemLocalSet}; -use crate::util::nodemap::{FxHashMap, FxHashSet}; +use crate::util::nodemap::FxHashMap; use errors::DiagnosticBuilder; use rustc_data_structures::interner::HashInterner; use smallvec::SmallVec; @@ -55,7 +55,7 @@ use rustc_data_structures::stable_hasher::{HashStable, hash_stable_hashmap, StableVec}; use arena::SyncDroplessArena; use rustc_data_structures::indexed_vec::{Idx, IndexVec}; -use rustc_data_structures::sync::{Lrc, Lock, WorkerLocal}; +use rustc_data_structures::sync::{Lrc, Lock, WorkerLocal, AtomicOnce, OneThread}; use std::any::Any; use std::borrow::Borrow; use std::cmp::Ordering; @@ -66,7 +66,6 @@ use std::mem; use std::ops::{Deref, Bound}; use std::iter; use std::sync::mpsc; -use std::sync::Arc; use std::marker::PhantomData; use rustc_target::spec::abi; use rustc_macros::HashStable; @@ -192,6 +191,7 @@ impl<'tcx> CtxtInterners<'tcx> { pub struct Common<'tcx> { pub empty_predicates: ty::GenericPredicates<'tcx>, + pub empty_generic_args: hir::GenericArgs<'tcx>, } pub struct CommonTypes<'tcx> { @@ -1035,7 +1035,7 @@ pub struct GlobalCtxt<'tcx> { global_interners: CtxtInterners<'tcx>, local_interners: CtxtInterners<'tcx>, - cstore: &'tcx CrateStoreDyn, + pub cstore: &'tcx CrateStoreDyn, pub sess: &'tcx Session, @@ -1053,32 +1053,19 @@ pub struct GlobalCtxt<'tcx> { /// Common consts, pre-interned for your convenience. pub consts: CommonConsts<'tcx>, - /// Map indicating what traits are in scope for places where this - /// is relevant; generated by resolve. - trait_map: FxHashMap>>, + pub io: InputsAndOutputs, - /// Export map produced by name resolution. - export_map: FxHashMap>>, + pub ast_crate: Steal, - hir_map: hir_map::Map<'tcx>, + /// This stores a `Lrc>>)>`, but that type depends on + /// librustc_resolve, so it cannot be used here. + pub boxed_resolver: Steal>>, - /// A map from DefPathHash -> DefId. Includes DefIds from the local crate - /// as well as all upstream crates. Only populated in incremental mode. - pub def_path_hash_to_def_id: Option>, + lowered_hir: AtomicOnce<&'tcx hir::LoweredHir<'tcx>>, + hir_map: AtomicOnce<&'tcx hir_map::Map<'tcx>>, pub queries: query::Queries<'tcx>, - maybe_unused_trait_imports: FxHashSet, - maybe_unused_extern_crates: Vec<(DefId, Span)>, - /// A map of glob use to a set of names it actually imports. Currently only - /// used in save-analysis. - glob_map: FxHashMap>, - /// Extern prelude entries. The value is `true` if the entry was introduced - /// via `extern crate` item and not `--extern` option or compiler built-in. - pub extern_prelude: FxHashMap, - // Internal cache for metadata decoding. No need to track deps on this. pub rcache: Lock>>, @@ -1114,8 +1101,6 @@ pub struct GlobalCtxt<'tcx> { /// when satisfying the query for a particular codegen unit. Internally in /// the query it'll send data along this channel to get processed later. pub tx_to_llvm_workers: Lock>>, - - output_filenames: Arc, } impl<'tcx> TyCtxt<'tcx> { @@ -1129,9 +1114,30 @@ impl<'tcx> TyCtxt<'tcx> { } } + #[inline] + pub fn global_arena(self) -> &'tcx SyncDroplessArena { + &self.gcx.global_interners.arena + } + + pub fn def_path_hash_to_def_id(self) -> Option<&'tcx FxHashMap> { + self.lowered_hir().def_path_hash_to_def_id.as_ref() + } + + #[inline(always)] + pub fn lowered_hir(self) -> &'tcx hir::LoweredHir<'tcx> { + self.lowered_hir.get_or_init(|| { + // FIXME: The ignore here is only sound because all queries + // used to compute LoweredHir are eval_always + self.dep_graph.with_ignore(|| self.lower_ast_to_hir(()).unwrap()) + }) + } + #[inline(always)] pub fn hir(self) -> &'tcx hir_map::Map<'tcx> { - &self.hir_map + self.hir_map.get_or_init(|| { + // We can use `with_ignore` here because the hir map does its own tracking + self.dep_graph.with_ignore(|| self.hir_map(LOCAL_CRATE)) + }) } pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal> { @@ -1220,12 +1226,13 @@ impl<'tcx> TyCtxt<'tcx> { local_providers: ty::query::Providers<'tcx>, extern_providers: ty::query::Providers<'tcx>, arenas: &'tcx AllArenas, - resolutions: ty::Resolutions, - hir: hir_map::Map<'tcx>, + dep_graph: DepGraph, + ast_crate: ast::Crate, + boxed_resolver: Box, on_disk_query_result_cache: query::OnDiskCache<'tcx>, crate_name: &str, tx: mpsc::Sender>, - output_filenames: &OutputFilenames, + io: InputsAndOutputs, ) -> GlobalCtxt<'tcx> { let data_layout = TargetDataLayout::parse(&s.target.target).unwrap_or_else(|err| { s.fatal(&err); @@ -1237,54 +1244,19 @@ impl<'tcx> TyCtxt<'tcx> { parent: None, predicates: vec![], }, + empty_generic_args: hir::GenericArgs { + args: hir::ptr::P::default(), + bindings: hir::ptr::P::default(), + parenthesized: false, + }, }; let common_types = CommonTypes::new(&interners); let common_lifetimes = CommonLifetimes::new(&interners); let common_consts = CommonConsts::new(&interners, &common_types); - let dep_graph = hir.dep_graph.clone(); let max_cnum = cstore.crates_untracked().iter().map(|c| c.as_usize()).max().unwrap_or(0); let mut providers = IndexVec::from_elem_n(extern_providers, max_cnum + 1); providers[LOCAL_CRATE] = local_providers; - let def_path_hash_to_def_id = if s.opts.build_dep_graph() { - let upstream_def_path_tables: Vec<(CrateNum, Lrc<_>)> = cstore - .crates_untracked() - .iter() - .map(|&cnum| (cnum, cstore.def_path_table(cnum))) - .collect(); - - let def_path_tables = || { - upstream_def_path_tables - .iter() - .map(|&(cnum, ref rc)| (cnum, &**rc)) - .chain(iter::once((LOCAL_CRATE, hir.definitions().def_path_table()))) - }; - - // Precompute the capacity of the hashmap so we don't have to - // re-allocate when populating it. - let capacity = def_path_tables().map(|(_, t)| t.size()).sum::(); - - let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher( - capacity, - ::std::default::Default::default() - ); - - for (cnum, def_path_table) in def_path_tables() { - def_path_table.add_def_path_hashes_to(cnum, &mut map); - } - - Some(map) - } else { - None - }; - - let mut trait_map: FxHashMap<_, FxHashMap<_, _>> = FxHashMap::default(); - for (k, v) in resolutions.trait_map { - let hir_id = hir.node_to_hir_id(k); - let map = trait_map.entry(hir_id.owner).or_default(); - map.insert(hir_id.local_id, StableVec::new(v)); - } - GlobalCtxt { sess: s, cstore, @@ -1296,29 +1268,10 @@ impl<'tcx> TyCtxt<'tcx> { types: common_types, lifetimes: common_lifetimes, consts: common_consts, - trait_map, - export_map: resolutions.export_map.into_iter().map(|(k, v)| { - let exports: Vec<_> = v.into_iter().map(|e| { - e.map_id(|id| hir.node_to_hir_id(id)) - }).collect(); - (k, exports) - }).collect(), - maybe_unused_trait_imports: - resolutions.maybe_unused_trait_imports - .into_iter() - .map(|id| hir.local_def_id(id)) - .collect(), - maybe_unused_extern_crates: - resolutions.maybe_unused_extern_crates - .into_iter() - .map(|(id, sp)| (hir.local_def_id(id), sp)) - .collect(), - glob_map: resolutions.glob_map.into_iter().map(|(id, names)| { - (hir.local_def_id(id), names) - }).collect(), - extern_prelude: resolutions.extern_prelude, - hir_map: hir, - def_path_hash_to_def_id, + ast_crate: Steal::new(ast_crate), + boxed_resolver: Steal::new(OneThread::new(boxed_resolver)), + lowered_hir: AtomicOnce::new(), + hir_map: AtomicOnce::new(), queries: query::Queries::new( providers, extern_providers, @@ -1334,7 +1287,7 @@ impl<'tcx> TyCtxt<'tcx> { allocation_interner: Default::default(), alloc_map: Lock::new(interpret::AllocMap::new()), tx_to_llvm_workers: Lock::new(tx), - output_filenames: Arc::new(output_filenames.clone()), + io, } } @@ -1412,7 +1365,8 @@ impl<'tcx> TyCtxt<'tcx> { /// be a non-local `DefPath`. pub fn def_path(self, id: DefId) -> hir_map::DefPath { if id.is_local() { - self.hir().def_path(id) + // FIXME: This is used in some panic path? Don't use hir() + self.lowered_hir().defs.def_path(id.index) } else { self.cstore.def_path(id) } @@ -1431,7 +1385,9 @@ impl<'tcx> TyCtxt<'tcx> { #[inline] pub fn def_path_hash(self, def_id: DefId) -> hir_map::DefPathHash { if def_id.is_local() { - self.hir().definitions().def_path_hash(def_id.index) + // This is used when creating dep nodes, which happens when executing queries, + // so we can't use hir() here + self.lowered_hir().defs.def_path_hash(def_id.index) } else { self.cstore.def_path_hash(def_id) } @@ -1470,12 +1426,18 @@ impl<'tcx> TyCtxt<'tcx> { #[inline(always)] pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> { - let krate = self.gcx.hir_map.forest.untracked_krate(); + let hir = self.lowered_hir(); + + // FIXME: This is used when executing the hir query, can't use hir() here. + // Also used when dealing with query cycles + let krate = hir.forest.untracked_krate(); - StableHashingContext::new(self.sess, - krate, - self.hir().definitions(), - self.cstore) + StableHashingContext::new( + self.sess, + krate, + &hir.defs, + self.cstore, + ) } // This method makes sure that we have a DepNode and a Fingerprint for @@ -1493,7 +1455,7 @@ impl<'tcx> TyCtxt<'tcx> { self, crate_hash, |_, x| x, // No transformation needed - dep_graph::hash_result, + Some(dep_graph::hash_result), ); } } @@ -2999,8 +2961,12 @@ fn ptr_eq(t: *const T, u: *const U) -> bool { } pub fn provide(providers: &mut ty::query::Providers<'_>) { - providers.in_scope_traits_map = |tcx, id| tcx.gcx.trait_map.get(&id); - providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).map(|v| &v[..]); + providers.in_scope_traits_map = |tcx, id| { + tcx.lowered_hir().trait_map.get(&id) + }; + providers.module_exports = |tcx, id| { + tcx.lowered_hir().export_map.get(&id).map(|v| &v[..]) + }; providers.crate_name = |tcx, id| { assert_eq!(id, LOCAL_CRATE); tcx.crate_name @@ -3014,15 +2980,15 @@ pub fn provide(providers: &mut ty::query::Providers<'_>) { tcx.arena.alloc(middle::lang_items::collect(tcx)) }; providers.maybe_unused_trait_import = |tcx, id| { - tcx.maybe_unused_trait_imports.contains(&id) + tcx.lowered_hir().maybe_unused_trait_imports.contains(&id) }; providers.maybe_unused_extern_crates = |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); - &tcx.maybe_unused_extern_crates[..] + &tcx.lowered_hir().maybe_unused_extern_crates[..] }; providers.names_imported_by_glob_use = |tcx, id| { assert_eq!(id.krate, LOCAL_CRATE); - Lrc::new(tcx.glob_map.get(&id).cloned().unwrap_or_default()) + Lrc::new(tcx.lowered_hir().glob_map.get(&id).cloned().unwrap_or_default()) }; providers.stability_index = |tcx, cnum| { @@ -3053,7 +3019,7 @@ pub fn provide(providers: &mut ty::query::Providers<'_>) { }; providers.output_filenames = |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); - tcx.output_filenames.clone() + tcx.prepare_outputs(()).unwrap() }; providers.features_query = |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); diff --git a/src/librustc/ty/query/config.rs b/src/librustc/ty/query/config.rs index 13d93f173e845..d244975aa67ff 100644 --- a/src/librustc/ty/query/config.rs +++ b/src/librustc/ty/query/config.rs @@ -38,10 +38,7 @@ pub(crate) trait QueryAccessors<'tcx>: QueryConfig<'tcx> { // Don't use this method to compute query results, instead use the methods on TyCtxt fn compute(tcx: TyCtxt<'tcx>, key: Self::Key) -> Self::Value; - fn hash_result( - hcx: &mut StableHashingContext<'_>, - result: &Self::Value - ) -> Option; + fn hash_result() -> Option, &Self::Value) -> Fingerprint>; fn handle_cycle_error(tcx: TyCtxt<'tcx>, error: CycleError<'tcx>) -> Self::Value; } diff --git a/src/librustc/ty/query/keys.rs b/src/librustc/ty/query/keys.rs index 30a3e53dddfbb..24e8ea94c2f06 100644 --- a/src/librustc/ty/query/keys.rs +++ b/src/librustc/ty/query/keys.rs @@ -64,6 +64,15 @@ impl Key for CrateNum { } } +impl Key for () { + fn query_crate(&self) -> CrateNum { + LOCAL_CRATE + } + fn default_span(&self, _: TyCtxt<'_>) -> Span { + DUMMY_SP + } +} + impl Key for DefIndex { fn query_crate(&self) -> CrateNum { LOCAL_CRATE diff --git a/src/librustc/ty/query/on_disk_cache.rs b/src/librustc/ty/query/on_disk_cache.rs index 6f83991a2daa2..31c5c5ad7be32 100644 --- a/src/librustc/ty/query/on_disk_cache.rs +++ b/src/librustc/ty/query/on_disk_cache.rs @@ -672,7 +672,7 @@ impl<'a, 'tcx> SpecializedDecoder for CacheDecoder<'a, 'tcx> { let def_path_hash = DefPathHash::decode(self)?; // Using the DefPathHash, we can lookup the new DefId - Ok(self.tcx().def_path_hash_to_def_id.as_ref().unwrap()[&def_path_hash]) + Ok(self.tcx().def_path_hash_to_def_id().unwrap()[&def_path_hash]) } } @@ -690,8 +690,7 @@ impl<'a, 'tcx> SpecializedDecoder for CacheDecoder<'a, 'tcx> { // Use the DefPathHash to map to the current DefId. let def_id = self.tcx() - .def_path_hash_to_def_id - .as_ref() + .def_path_hash_to_def_id() .unwrap()[&def_path_hash]; debug_assert!(def_id.is_local()); diff --git a/src/librustc/ty/query/plumbing.rs b/src/librustc/ty/query/plumbing.rs index 48e68167f824c..560a621dfb649 100644 --- a/src/librustc/ty/query/plumbing.rs +++ b/src/librustc/ty/query/plumbing.rs @@ -2,12 +2,13 @@ //! generate the actual methods on tcx which find and execute the provider, //! manage the caches, and so forth. -use crate::dep_graph::{DepNodeIndex, DepNode, DepKind, SerializedDepNodeIndex}; +use crate::dep_graph::{DepNodeIndex, DepNode, DepConstructor, DepKind, SerializedDepNodeIndex}; use crate::ty::tls; use crate::ty::{self, TyCtxt}; use crate::ty::query::Query; use crate::ty::query::config::{QueryConfig, QueryDescription}; use crate::ty::query::job::{QueryJob, QueryResult, QueryInfo}; +use crate::hir::def_id::LOCAL_CRATE; use crate::util::common::{profq_msg, ProfileQueriesMsg, QueryMsg}; @@ -514,7 +515,7 @@ impl<'tcx> TyCtxt<'tcx> { debug!("BEGIN verify_ich({:?})", dep_node); let mut hcx = self.create_stable_hashing_context(); - let new_hash = Q::hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO); + let new_hash = Q::hash_result().map(|h| h(&mut hcx, result)).unwrap_or(Fingerprint::ZERO); debug!("END verify_ich({:?})", dep_node); let old_hash = self.dep_graph.fingerprint_of(dep_node_index); @@ -530,6 +531,10 @@ impl<'tcx> TyCtxt<'tcx> { job: JobOwner<'_, 'tcx, Q>, dep_node: DepNode, ) -> (Q::Value, DepNodeIndex) { + if self.dep_graph.is_fully_enabled() { + debug_assert_eq!(dep_node, Q::to_dep_node(self, &key)); + } + // If the following assertion triggers, it can have two reasons: // 1. Something is wrong with DepNode creation, either here or // in DepGraph::try_mark_green() @@ -551,13 +556,13 @@ impl<'tcx> TyCtxt<'tcx> { tcx, key, Q::compute, - Q::hash_result) + Q::hash_result()) } else { tcx.dep_graph.with_task(dep_node, tcx, key, Q::compute, - Q::hash_result) + Q::hash_result()) } }) }); @@ -654,14 +659,14 @@ macro_rules! handle_cycle_error { } macro_rules! hash_result { - ([][$hcx:expr, $result:expr]) => {{ - dep_graph::hash_result($hcx, &$result) + ([]) => {{ + Some(dep_graph::hash_result) }}; - ([no_hash$(, $modifiers:ident)*][$hcx:expr, $result:expr]) => {{ + ([no_hash$(, $modifiers:ident)*]) => {{ None }}; - ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => { - hash_result!([$($modifiers),*][$($args)*]) + ([$other:ident$(, $modifiers:ident)*]) => { + hash_result!([$($modifiers),*]) }; } @@ -965,11 +970,10 @@ macro_rules! define_queries_inner { }) } - fn hash_result( - _hcx: &mut StableHashingContext<'_>, - _result: &Self::Value - ) -> Option { - hash_result!([$($modifiers)*][_hcx, _result]) + fn hash_result() -> Option, &Self::Value + ) -> Fingerprint> { + hash_result!([$($modifiers)*]) } fn handle_cycle_error( @@ -1187,14 +1191,28 @@ pub fn force_from_dep_node<'tcx>(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> bool ($query:ident, $key:expr) => { force_ex!(tcx, $query, $key) } }; + let force_hir_map = || { + tcx.force_query::>( + LOCAL_CRATE, + DUMMY_SP, + DepNode::new(tcx, DepConstructor::hir_map(LOCAL_CRATE)), + ); + }; + rustc_dep_node_force!([dep_node, tcx] + // Created by the Hir map query + DepKind::AllLocalTraitImpls | + DepKind::Krate => force_hir_map(), + DepKind::HirBody | + DepKind::Hir => { + // Ensure the def_id exists + def_id!(); + force_hir_map(); + } + // These are inputs that are expected to be pre-allocated and that // should therefore always be red or green already - DepKind::AllLocalTraitImpls | - DepKind::Krate | DepKind::CrateMetadata | - DepKind::HirBody | - DepKind::Hir | // This are anonymous nodes DepKind::TraitSelect | diff --git a/src/librustc_borrowck/borrowck/check_loans.rs b/src/librustc_borrowck/borrowck/check_loans.rs index 4a36d441d3d9f..64098c1fd0f00 100644 --- a/src/librustc_borrowck/borrowck/check_loans.rs +++ b/src/librustc_borrowck/borrowck/check_loans.rs @@ -184,7 +184,7 @@ pub fn check_loans<'a, 'tcx>( dfcx_loans: &LoanDataFlow<'tcx>, move_data: &move_data::FlowedMoveData<'tcx>, all_loans: &[Loan<'tcx>], - body: &hir::Body, + body: &hir::Body<'tcx>, ) { debug!("check_loans(body id={})", body.value.hir_id); diff --git a/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs b/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs index 4d03b58179db0..3e08f9d42851e 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs @@ -26,8 +26,8 @@ struct GatherMoveInfo<'c, 'tcx: 'c> { /// Represents the kind of pattern #[derive(Debug, Clone, Copy)] pub enum PatternSource<'tcx> { - MatchExpr(&'tcx Expr), - LetDecl(&'tcx Local), + MatchExpr(&'tcx Expr<'tcx>), + LetDecl(&'tcx Local<'tcx>), Other, } diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs index 9b0dce50dd0cb..5b423b1686b21 100644 --- a/src/librustc_borrowck/borrowck/mod.rs +++ b/src/librustc_borrowck/borrowck/mod.rs @@ -230,7 +230,7 @@ pub struct BorrowckCtxt<'a, 'tcx> { owner_def_id: DefId, - body: &'tcx hir::Body, + body: &'tcx hir::Body<'tcx>, used_mut_nodes: RefCell>, diff --git a/src/librustc_borrowck/lib.rs b/src/librustc_borrowck/lib.rs index 98e629ce046bb..0571328b3306f 100644 --- a/src/librustc_borrowck/lib.rs +++ b/src/librustc_borrowck/lib.rs @@ -1,7 +1,6 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")] #![allow(non_camel_case_types)] -#![deny(rust_2018_idioms)] #![deny(internal)] #![deny(unused_lifetimes)] diff --git a/src/librustc_codegen_llvm/base.rs b/src/librustc_codegen_llvm/base.rs index 04645dacfec58..06355f422928a 100644 --- a/src/librustc_codegen_llvm/base.rs +++ b/src/librustc_codegen_llvm/base.rs @@ -112,7 +112,7 @@ pub fn compile_codegen_unit(tcx: TyCtxt<'tcx>, cgu_name: InternedString) { tcx, cgu_name, module_codegen, - dep_graph::hash_result, + Some(dep_graph::hash_result), ); let time_to_codegen = start_time.elapsed(); diff --git a/src/librustc_codegen_utils/lib.rs b/src/librustc_codegen_utils/lib.rs index 942c2d13fac87..e8bca8f4dea15 100644 --- a/src/librustc_codegen_utils/lib.rs +++ b/src/librustc_codegen_utils/lib.rs @@ -16,7 +16,7 @@ #![recursion_limit="256"] -#![deny(rust_2018_idioms)] +//#![deny(rust_2018_idioms)] #![deny(internal)] #![deny(unused_lifetimes)] diff --git a/src/librustc_data_structures/Cargo.toml b/src/librustc_data_structures/Cargo.toml index cd792d31187bd..fc58da4335025 100644 --- a/src/librustc_data_structures/Cargo.toml +++ b/src/librustc_data_structures/Cargo.toml @@ -19,6 +19,7 @@ rustc_cratesio_shim = { path = "../librustc_cratesio_shim" } serialize = { path = "../libserialize" } graphviz = { path = "../libgraphviz" } cfg-if = "0.1.2" +crossbeam-utils = { version = "0.6.5", features = ["nightly"] } stable_deref_trait = "1.0.0" rayon = { version = "0.2.0", package = "rustc-rayon" } rayon-core = { version = "0.2.0", package = "rustc-rayon-core" } diff --git a/src/librustc_data_structures/sync.rs b/src/librustc_data_structures/sync.rs index 73247c1469efd..469f778551239 100644 --- a/src/librustc_data_structures/sync.rs +++ b/src/librustc_data_structures/sync.rs @@ -21,6 +21,7 @@ use std::collections::HashMap; use std::hash::{Hash, BuildHasher}; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; +use crate::cold_path; use crate::owning_ref::{Erased, OwningRef}; pub fn serial_join(oper_a: A, oper_b: B) -> (RA, RB) @@ -67,6 +68,59 @@ cfg_if! { use std::ops::Add; use std::panic::{resume_unwind, catch_unwind, AssertUnwindSafe}; + #[derive(Debug)] + pub struct AtomicCell(Cell); + + impl AtomicCell { + #[inline] + pub fn new(v: T) -> Self { + AtomicCell(Cell::new(v)) + } + } + + impl AtomicCell { + pub fn into_inner(self) -> T { + self.0.into_inner() + } + + #[inline] + pub fn load(&self) -> T { + self.0.get() + } + + #[inline] + pub fn store(&self, val: T) { + self.0.set(val) + } + + pub fn swap(&self, val: T) -> T { + self.0.replace(val) + } + } + + impl AtomicCell { + pub fn compare_exchange(&self, + current: T, + new: T) + -> Result { + let read = self.0.get(); + if read == current { + self.0.set(new); + Ok(read) + } else { + Err(read) + } + } + } + + impl + Copy> AtomicCell { + pub fn fetch_add(&self, val: T) -> T { + let old = self.0.get(); + self.0.set(old + val); + old + } + } + #[derive(Debug)] pub struct Atomic(Cell); @@ -77,7 +131,7 @@ cfg_if! { } } - impl Atomic { + impl Atomic { pub fn into_inner(self) -> T { self.0.into_inner() } @@ -95,7 +149,9 @@ cfg_if! { pub fn swap(&self, val: T, _: Ordering) -> T { self.0.replace(val) } + } + impl Atomic { pub fn compare_exchange(&self, current: T, new: T, @@ -271,6 +327,8 @@ cfg_if! { pub use std::sync::atomic::{AtomicBool, AtomicUsize, AtomicU32, AtomicU64}; + pub use crossbeam_utils::atomic::AtomicCell; + pub use std::sync::Arc as Lrc; pub use std::sync::Weak as Weak; @@ -516,6 +574,34 @@ impl Once { } } +/// A type whose inner value can be written once and then will stay read-only +pub struct AtomicOnce(AtomicCell>); + +impl AtomicOnce { + /// Creates an AtomicOnce value which is uninitialized + #[inline] + pub fn new() -> Self { + AtomicOnce(AtomicCell::new(None)) + } + + /// Gets the inner value. If the value is not already initalized. + /// It will be initalized by the closure. The closure may be called + /// concurrently by many threads. + #[inline(always)] + pub fn get_or_init(&self, f: impl FnOnce() -> T) -> T { + let value = self.0.load(); + if unlikely!(value.is_none()) { + cold_path(|| { + let value = f(); + self.0.store(Some(value)); + value + }) + } else { + value.unwrap() + } + } +} + #[derive(Debug)] pub struct Lock(InnerLock); diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 5fb6ed31b0693..ceccba2218119 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -255,11 +255,10 @@ pub fn run_compiler( if ppm.needs_ast_map(&opt_uii) { pretty::visit_crate(sess, &mut compiler.parse()?.peek_mut(), ppm); compiler.global_ctxt()?.peek_mut().enter(|tcx| { - let expanded_crate = compiler.expansion()?.take().0; pretty::print_after_hir_lowering( tcx, compiler.input(), - &expanded_crate, + &tcx.ast_crate.borrow(), ppm, opt_uii.clone(), compiler.output_file().as_ref().map(|p| &**p), @@ -299,7 +298,10 @@ pub fn run_compiler( return sess.compile_status(); } - compiler.prepare_outputs()?; + compiler.global_ctxt()?.peek_mut().enter(|tcx| { + tcx.prepare_outputs(())?; + Ok(()) + })?; if sess.opts.output_types.contains_key(&OutputType::DepInfo) && sess.opts.output_types.len() == 1 @@ -307,7 +309,10 @@ pub fn run_compiler( return sess.compile_status(); } - compiler.global_ctxt()?; + compiler.global_ctxt()?.peek_mut().enter(|tcx| { + tcx.lower_ast_to_hir(())?; + Ok(()) + })?; if sess.opts.debugging_opts.no_analysis || sess.opts.debugging_opts.ast_json { @@ -315,19 +320,18 @@ pub fn run_compiler( } if sess.opts.debugging_opts.save_analysis { - let expanded_crate = &compiler.expansion()?.peek().0; - let crate_name = compiler.crate_name()?.peek().clone(); compiler.global_ctxt()?.peek_mut().enter(|tcx| { let result = tcx.analysis(LOCAL_CRATE); + let crate_name = &tcx.crate_name.as_str(); time(sess, "save analysis", || { save::process_crate( tcx, - &expanded_crate, - &crate_name, + &tcx.ast_crate.borrow(), + crate_name, &compiler.input(), None, - DumpHandler::new(compiler.output_dir().as_ref().map(|p| &**p), &crate_name) + DumpHandler::new(compiler.output_dir().as_ref().map(|p| &**p), crate_name) ) }); @@ -336,8 +340,10 @@ pub fn run_compiler( // (needed by the RLS) })?; } else { - // Drop AST after creating GlobalCtxt to free memory - mem::drop(compiler.expansion()?.take()); + compiler.global_ctxt()?.peek_mut().enter(|tcx| { + // Drop AST after lowering HIR to free memory + mem::drop(tcx.ast_crate.steal()); + }); } compiler.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?; @@ -347,7 +353,10 @@ pub fn run_compiler( } if sess.opts.debugging_opts.save_analysis { - mem::drop(compiler.expansion()?.take()); + compiler.global_ctxt()?.peek_mut().enter(|tcx| { + // Drop AST after lowering HIR to free memory + mem::drop(tcx.ast_crate.steal()); + }); } compiler.ongoing_codegen()?; diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index e70c510b779c1..1e1fa8222f34d 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -190,7 +190,7 @@ impl PpSourceMode { } fn call_with_pp_support_hir<'tcx, A, F>(&self, tcx: TyCtxt<'tcx>, f: F) -> A where - F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate) -> A, + F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate<'_>) -> A, { match *self { PpmNormal => { diff --git a/src/librustc_incremental/lib.rs b/src/librustc_incremental/lib.rs index ffea495d3ebdb..dadf291ea9502 100644 --- a/src/librustc_incremental/lib.rs +++ b/src/librustc_incremental/lib.rs @@ -8,7 +8,7 @@ #![recursion_limit="256"] -#![deny(rust_2018_idioms)] +//#![deny(rust_2018_idioms)] #![deny(internal)] #![deny(unused_lifetimes)] diff --git a/src/librustc_interface/interface.rs b/src/librustc_interface/interface.rs index 674b2b60e44a2..8fef6338ec0d0 100644 --- a/src/librustc_interface/interface.rs +++ b/src/librustc_interface/interface.rs @@ -4,7 +4,7 @@ use crate::profile; pub use crate::passes::BoxedResolver; use rustc::lint; -use rustc::session::config::{self, Input}; +use rustc::session::config::{self, Input, InputsAndOutputs}; use rustc::session::{DiagnosticOutput, Session}; use rustc::util::common::ErrorReported; use rustc_codegen_utils::codegen_backend::CodegenBackend; @@ -29,10 +29,7 @@ pub struct Compiler { pub(crate) sess: Lrc, codegen_backend: Lrc>, source_map: Lrc, - pub(crate) input: Input, - pub(crate) input_path: Option, - pub(crate) output_dir: Option, - pub(crate) output_file: Option, + pub(crate) io: InputsAndOutputs, pub(crate) queries: Queries, pub(crate) cstore: Lrc, pub(crate) crate_name: Option, @@ -52,13 +49,13 @@ impl Compiler { &self.source_map } pub fn input(&self) -> &Input { - &self.input + &self.io.input } pub fn output_dir(&self) -> &Option { - &self.output_dir + &self.io.output_dir } pub fn output_file(&self) -> &Option { - &self.output_file + &self.io.output_file } } @@ -104,10 +101,12 @@ where codegen_backend, source_map, cstore, - input: config.input, - input_path: config.input_path, - output_dir: config.output_dir, - output_file: config.output_file, + io: InputsAndOutputs { + input: config.input, + input_path: config.input_path, + output_dir: config.output_dir, + output_file: config.output_file, + }, queries: Default::default(), crate_name: config.crate_name, }; diff --git a/src/librustc_interface/passes.rs b/src/librustc_interface/passes.rs index 69cb696f4c580..8af010e111895 100644 --- a/src/librustc_interface/passes.rs +++ b/src/librustc_interface/passes.rs @@ -16,7 +16,7 @@ use rustc::traits; use rustc::util::common::{time, ErrorReported}; use rustc::util::profiling::ProfileCategory; use rustc::session::{CompileResult, CrateDisambiguator, Session}; -use rustc::session::config::{self, CrateType, Input, OutputFilenames, OutputType}; +use rustc::session::config::{self, CrateType, Input, OutputFilenames, OutputType, InputsAndOutputs}; use rustc::session::search_paths::PathKind; use rustc_allocator as allocator; use rustc_borrowck as borrowck; @@ -25,8 +25,9 @@ use rustc_codegen_utils::codegen_backend::CodegenBackend; use rustc_codegen_utils::link::filename_for_metadata; use rustc_data_structures::{box_region_allow_access, declare_box_region_type, parallel}; use rustc_data_structures::fingerprint::Fingerprint; -use rustc_data_structures::stable_hasher::StableHasher; -use rustc_data_structures::sync::{Lrc, ParallelIterator, par_iter}; +use rustc_data_structures::stable_hasher::{StableHasher, StableVec}; +use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::sync::{self, Lrc, Lock, OneThread, ParallelIterator, par_iter}; use rustc_incremental; use rustc_incremental::DepGraphFuture; use rustc_metadata::creader::CrateLoader; @@ -63,7 +64,7 @@ use std::iter; use std::path::{Path, PathBuf}; use std::sync::mpsc; use std::cell::RefCell; -use std::rc::Rc; +use std::sync::Arc; use std::mem; use std::ops::Generator; @@ -167,8 +168,8 @@ pub fn configure_and_expand( } pub struct ExpansionResult { - pub defs: Steal, - pub resolutions: Steal, + pub defs: hir::map::Definitions, + pub resolutions: Resolutions, } impl ExpansionResult { @@ -176,8 +177,8 @@ impl ExpansionResult { resolver: Resolver<'_>, ) -> Self { ExpansionResult { - defs: Steal::new(resolver.definitions), - resolutions: Steal::new(Resolutions { + defs: resolver.definitions, + resolutions: Resolutions { export_map: resolver.export_map, trait_map: resolver.trait_map, glob_map: resolver.glob_map, @@ -186,7 +187,7 @@ impl ExpansionResult { extern_prelude: resolver.extern_prelude.iter().map(|(ident, entry)| { (ident.name, entry.introduced_by_item) }).collect(), - }), + }, } } @@ -194,8 +195,8 @@ impl ExpansionResult { resolver: &Resolver<'_>, ) -> Self { ExpansionResult { - defs: Steal::new(resolver.definitions.clone()), - resolutions: Steal::new(Resolutions { + defs: resolver.definitions.clone(), + resolutions: Resolutions { export_map: resolver.export_map.clone(), trait_map: resolver.trait_map.clone(), glob_map: resolver.glob_map.clone(), @@ -204,20 +205,19 @@ impl ExpansionResult { extern_prelude: resolver.extern_prelude.iter().map(|(ident, entry)| { (ident.name, entry.introduced_by_item) }).collect(), - }), + }, } } } impl BoxedResolver { pub fn to_expansion_result( - mut resolver: Rc>>, + resolver: &mut Lrc>>, ) -> ExpansionResult { - if let Some(resolver) = Rc::get_mut(&mut resolver) { + if let Some(resolver) = Lrc::get_mut(resolver) { mem::replace(resolver, None).unwrap().into_inner().complete() } else { - let resolver = &*resolver; - resolver.as_ref().unwrap().borrow_mut().access(|resolver| { + (**resolver).as_ref().unwrap().lock().access(|resolver| { ExpansionResult::from_resolver_ref(resolver) }) } @@ -548,26 +548,44 @@ fn configure_and_expand_inner<'a>( Ok((krate, resolver)) } -pub fn lower_to_hir( - sess: &Session, - cstore: &CStore, - resolver: &mut Resolver<'_>, - dep_graph: &DepGraph, - krate: &ast::Crate, -) -> Result { +fn lower_ast_to_hir<'tcx>( + tcx: TyCtxt<'tcx>, + _: (), +) -> Result<&'tcx hir::LoweredHir<'tcx>> { + tcx.prepare_outputs(())?; + + let sess = tcx.sess; + + let boxed_resolver: Box = OneThread::into_inner(tcx.boxed_resolver.steal()); + let mut boxed_resolver: Box>>> = + boxed_resolver.downcast().unwrap(); + // Lower ast -> hir - let hir_forest = time(sess, "lowering ast -> hir", || { - let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, resolver); + let forest = time(sess, "lowering ast -> hir", || { + (**boxed_resolver).as_ref().unwrap().lock().access(|resolver| { + let hir_crate = lower_crate( + sess, + tcx.cstore, + &tcx.arena, + &tcx.dep_graph, + &tcx.ast_crate.borrow(), + resolver, + ); - if sess.opts.debugging_opts.hir_stats { - hir_stats::print_hir_stats(&hir_crate); - } + if sess.opts.debugging_opts.hir_stats { + hir_stats::print_hir_stats(&hir_crate); + } - hir::map::Forest::new(hir_crate, &dep_graph) + hir::map::Forest::new(hir_crate, &tcx.dep_graph) + }) }); time(sess, "early lint checks", || { - lint::check_ast_crate(sess, &krate, false, rustc_lint::BuiltinCombinedEarlyLintPass::new()) + lint::check_ast_crate( + sess, + &tcx.ast_crate.borrow(), + false,rustc_lint::BuiltinCombinedEarlyLintPass::new() + ) }); // Discard hygiene data, which isn't required after lowering to HIR. @@ -575,7 +593,76 @@ pub fn lower_to_hir( syntax::ext::hygiene::clear_markings(); } - Ok(hir_forest) + let ExpansionResult { + defs, + resolutions, + } = BoxedResolver::to_expansion_result(&mut *boxed_resolver); + + let def_path_hash_to_def_id = if tcx.sess.opts.build_dep_graph() { + let upstream_def_path_tables: Vec<(CrateNum, Lrc<_>)> = tcx.cstore + .crates_untracked() + .iter() + .map(|&cnum| (cnum, tcx.cstore.def_path_table(cnum))) + .collect(); + + let def_path_tables = || { + upstream_def_path_tables + .iter() + .map(|&(cnum, ref rc)| (cnum, &**rc)) + .chain(iter::once((LOCAL_CRATE, defs.def_path_table()))) + }; + + // Precompute the capacity of the hashmap so we don't have to + // re-allocate when populating it. + let capacity = def_path_tables().map(|(_, t)| t.size()).sum::(); + + let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher( + capacity, + ::std::default::Default::default() + ); + + for (cnum, def_path_table) in def_path_tables() { + def_path_table.add_def_path_hashes_to(cnum, &mut map); + } + + Some(map) + } else { + None + }; + + let mut trait_map: FxHashMap<_, FxHashMap<_, _>> = FxHashMap::default(); + for (k, v) in resolutions.trait_map { + let hir_id = defs.node_to_hir_id(k); + let map = trait_map.entry(hir_id.owner).or_default(); + map.insert(hir_id.local_id, StableVec::new(v)); + } + + Ok(tcx.arena.alloc(hir::LoweredHir { + forest, + export_map: resolutions.export_map.into_iter().map(|(k, v)| { + let exports: Vec<_> = v.into_iter().map(|e| { + e.map_id(|id| defs.node_to_hir_id(id)) + }).collect(); + (k, exports) + }).collect(), + maybe_unused_trait_imports: + resolutions.maybe_unused_trait_imports + .into_iter() + .map(|id| defs.local_def_id(id)) + .collect(), + maybe_unused_extern_crates: + resolutions.maybe_unused_extern_crates + .into_iter() + .map(|(id, sp)| (defs.local_def_id(id), sp)) + .collect(), + glob_map: resolutions.glob_map.into_iter().map(|(id, names)| { + (defs.local_def_id(id), names) + }).collect(), + defs, + extern_prelude: resolutions.extern_prelude, + def_path_hash_to_def_id, + trait_map, + })) } // Returns all the paths that correspond to generated files. @@ -697,33 +784,31 @@ fn write_out_deps(sess: &Session, outputs: &OutputFilenames, out_filenames: &[Pa } } -pub fn prepare_outputs( - sess: &Session, - compiler: &Compiler, - krate: &ast::Crate, - crate_name: &str -) -> Result { - // FIXME: rustdoc passes &[] instead of &krate.attrs here +fn prepare_outputs( + tcx: TyCtxt<'_>, + _: (), +) -> Result> { + // FIXME: rustdoc passes &[] instead of &tcx.ast_krate.borrow().attrs here let outputs = util::build_output_filenames( - &compiler.input, - &compiler.output_dir, - &compiler.output_file, - &krate.attrs, - sess + &tcx.io.input, + &tcx.io.output_dir, + &tcx.io.output_file, + &tcx.ast_crate.borrow().attrs, + tcx.sess ); let output_paths = generated_output_paths( - sess, + tcx.sess, &outputs, - compiler.output_file.is_some(), - &crate_name, + tcx.io.output_file.is_some(), + &tcx.crate_name.as_str(), ); // Ensure the source file isn't accidentally overwritten during compilation. - if let Some(ref input_path) = compiler.input_path { - if sess.opts.will_create_output_file() { + if let Some(ref input_path) = tcx.io.input_path { + if tcx.sess.opts.will_create_output_file() { if output_contains_path(&output_paths, input_path) { - sess.err(&format!( + tcx.sess.err(&format!( "the input file \"{}\" would be overwritten by the generated \ executable", input_path.display() @@ -731,7 +816,7 @@ pub fn prepare_outputs( return Err(ErrorReported); } if let Some(dir_path) = output_conflicts_with_dir(&output_paths) { - sess.err(&format!( + tcx.sess.err(&format!( "the generated executable for the input file \"{}\" conflicts with the \ existing directory \"{}\"", input_path.display(), @@ -742,25 +827,28 @@ pub fn prepare_outputs( } } - write_out_deps(sess, &outputs, &output_paths); + write_out_deps(tcx.sess, &outputs, &output_paths); - let only_dep_info = sess.opts.output_types.contains_key(&OutputType::DepInfo) - && sess.opts.output_types.len() == 1; + let only_dep_info = tcx.sess.opts.output_types.contains_key(&OutputType::DepInfo) + && tcx.sess.opts.output_types.len() == 1; if !only_dep_info { - if let Some(ref dir) = compiler.output_dir { + if let Some(ref dir) = tcx.io.output_dir { if fs::create_dir_all(dir).is_err() { - sess.err("failed to find or create the directory specified by --out-dir"); + tcx.sess.err("failed to find or create the directory specified by --out-dir"); return Err(ErrorReported); } } } - Ok(outputs) + Ok(Arc::new(outputs)) } pub fn default_provide(providers: &mut ty::query::Providers<'_>) { providers.analysis = analysis; + providers.hir_map = hir_map; + providers.lower_ast_to_hir = lower_ast_to_hir; + providers.prepare_outputs = prepare_outputs; proc_macro_decls::provide(providers); plugin::build::provide(providers); hir::provide(providers); @@ -806,10 +894,10 @@ impl BoxedGlobalCtxt { pub fn create_global_ctxt( compiler: &Compiler, - mut hir_forest: hir::map::Forest, - defs: hir::map::Definitions, - resolutions: Resolutions, - outputs: OutputFilenames, + dep_graph: DepGraph, + ast_krate: ast::Crate, + boxed_resolver: Box>>>, + io: InputsAndOutputs, tx: mpsc::Sender>, crate_name: &str, ) -> BoxedGlobalCtxt { @@ -825,11 +913,6 @@ pub fn create_global_ctxt( let global_ctxt: Option>; let arenas = AllArenas::new(); - // Construct the HIR map - let hir_map = time(sess, "indexing hir", || { - hir::map::map_crate(sess, cstore, &mut hir_forest, &defs) - }); - let query_result_on_disk_cache = time(sess, "load query result cache", || { rustc_incremental::load_query_result_cache(sess) }); @@ -848,12 +931,13 @@ pub fn create_global_ctxt( local_providers, extern_providers, &arenas, - resolutions, - hir_map, + dep_graph, + ast_krate, + boxed_resolver, query_result_on_disk_cache, &crate_name, tx, - &outputs + io, ); global_ctxt = Some(gcx); @@ -871,11 +955,27 @@ pub fn create_global_ctxt( if sess.opts.debugging_opts.query_stats { gcx.queries.print_stats(); } + + // FIXME: ^ ensure this is called. Won't happen if the generator is dropped }); result } +fn hir_map<'tcx>( + tcx: TyCtxt<'tcx>, + cnum: CrateNum, +) -> &'tcx hir::map::Map<'tcx> { + assert_eq!(cnum, LOCAL_CRATE); + + // Construct the HIR map + let hir_map = time(tcx.sess, "indexing hir", || { + hir::map::map_crate(tcx) + }); + + tcx.arena.alloc(hir_map) +} + /// Runs the resolution, type-checking, region checking and other /// miscellaneous analysis passes on the crate. fn analysis<'tcx>(tcx: TyCtxt<'tcx>, cnum: CrateNum) -> Result<()> { diff --git a/src/librustc_interface/proc_macro_decls.rs b/src/librustc_interface/proc_macro_decls.rs index 9e1ef6b022d9b..61999125622e2 100644 --- a/src/librustc_interface/proc_macro_decls.rs +++ b/src/librustc_interface/proc_macro_decls.rs @@ -24,16 +24,16 @@ struct Finder { } impl<'v> ItemLikeVisitor<'v> for Finder { - fn visit_item(&mut self, item: &hir::Item) { + fn visit_item(&mut self, item: &hir::Item<'_>) { if attr::contains_name(&item.attrs, sym::rustc_proc_macro_decls) { self.decls = Some(item.hir_id); } } - fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) { + fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) { } - fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) { + fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) { } } diff --git a/src/librustc_interface/queries.rs b/src/librustc_interface/queries.rs index 570509ffb2b8c..113e28035d758 100644 --- a/src/librustc_interface/queries.rs +++ b/src/librustc_interface/queries.rs @@ -2,14 +2,14 @@ use crate::interface::{Compiler, Result}; use crate::passes::{self, BoxedResolver, ExpansionResult, BoxedGlobalCtxt, PluginInfo}; use rustc_incremental::DepGraphFuture; -use rustc_data_structures::sync::Lrc; +use rustc_data_structures::sync::{Lrc, Lock}; use rustc::session::config::{Input, OutputFilenames, OutputType}; use rustc::session::Session; use rustc::util::common::{time, ErrorReported}; use rustc::util::profiling::ProfileCategory; use rustc::lint; use rustc::hir; -use rustc::hir::def_id::LOCAL_CRATE; + use rustc::hir::def_id::LOCAL_CRATE; use rustc::ty; use rustc::ty::steal::Steal; use rustc::dep_graph::DepGraph; @@ -18,7 +18,7 @@ use rustc_plugin::registry::Registry; use serialize::json; use std::cell::{Ref, RefMut, RefCell}; use std::ops::Deref; -use std::rc::Rc; +use std::sync::Arc; use std::sync::mpsc; use std::any::Any; use std::mem; @@ -88,14 +88,12 @@ pub(crate) struct Queries { parse: Query, crate_name: Query, register_plugins: Query<(ast::Crate, PluginInfo)>, - expansion: Query<(ast::Crate, Rc>>)>, + expansion: Query<(ast::Crate, Lrc>>)>, dep_graph: Query, - lower_to_hir: Query<(Steal, ExpansionResult)>, - prepare_outputs: Query, codegen_channel: Query<(Steal>>, Steal>>)>, global_ctxt: Query, - ongoing_codegen: Query>, + ongoing_codegen: Query<(Box, Arc)>, link: Query<()>, } @@ -112,7 +110,7 @@ impl Compiler { pub fn parse(&self) -> Result<&Query> { self.queries.parse.compute(|| { - passes::parse(self.session(), &self.input).map_err( + passes::parse(self.session(), self.input()).map_err( |mut parse_error| { parse_error.emit(); ErrorReported @@ -145,7 +143,7 @@ impl Compiler { None => rustc_codegen_utils::link::find_crate_name( Some(self.session()), &krate.attrs, - &self.input + self.input(), ), }; Ok(result) @@ -154,7 +152,7 @@ impl Compiler { pub fn expansion( &self - ) -> Result<&Query<(ast::Crate, Rc>>)>> { + ) -> Result<&Query<(ast::Crate, Lrc>>)>> { self.queries.expansion.compute(|| { let crate_name = self.crate_name()?.peek().clone(); let (krate, plugin_info) = self.register_plugins()?.take(); @@ -164,7 +162,7 @@ impl Compiler { krate, &crate_name, plugin_info, - ).map(|(krate, resolver)| (krate, Rc::new(Some(RefCell::new(resolver))))) + ).map(|(krate, resolver)| (krate, Lrc::new(Some(Lock::new(resolver))))) }) } @@ -185,36 +183,6 @@ impl Compiler { }) } - pub fn lower_to_hir(&self) -> Result<&Query<(Steal, ExpansionResult)>> { - self.queries.lower_to_hir.compute(|| { - let expansion_result = self.expansion()?; - let (krate, resolver) = expansion_result.take(); - let resolver_ref = &*resolver; - let hir = Steal::new(resolver_ref.as_ref().unwrap().borrow_mut().access(|resolver| { - passes::lower_to_hir( - self.session(), - self.cstore(), - resolver, - &*self.dep_graph()?.peek(), - &krate - ) - })?); - expansion_result.give((krate, Rc::new(None))); - Ok((hir, BoxedResolver::to_expansion_result(resolver))) - }) - } - - pub fn prepare_outputs(&self) -> Result<&Query> { - self.queries.prepare_outputs.compute(|| { - self.lower_to_hir()?; - let krate = self.expansion()?; - let krate = krate.peek(); - let crate_name = self.crate_name()?; - let crate_name = crate_name.peek(); - passes::prepare_outputs(self.session(), self, &krate.0, &*crate_name) - }) - } - pub fn codegen_channel(&self) -> Result<&Query<(Steal>>, Steal>>)>> { self.queries.codegen_channel.compute(|| { @@ -226,38 +194,37 @@ impl Compiler { pub fn global_ctxt(&self) -> Result<&Query> { self.queries.global_ctxt.compute(|| { let crate_name = self.crate_name()?.peek().clone(); - let outputs = self.prepare_outputs()?.peek().clone(); - let hir = self.lower_to_hir()?; - let hir = hir.peek(); - let (ref hir_forest, ref expansion) = *hir; + let expansion_result = self.expansion()?; + let (krate, resolver) = expansion_result.take(); let tx = self.codegen_channel()?.peek().0.steal(); Ok(passes::create_global_ctxt( self, - hir_forest.steal(), - expansion.defs.steal(), - expansion.resolutions.steal(), - outputs, + self.dep_graph()?.peek().clone(), + krate, + Box::new(resolver), + self.io.clone(), tx, &crate_name)) }) } - pub fn ongoing_codegen(&self) -> Result<&Query>> { + pub fn ongoing_codegen(&self) -> Result<&Query<(Box, Arc)>> { self.queries.ongoing_codegen.compute(|| { let rx = self.codegen_channel()?.peek().1.steal(); - let outputs = self.prepare_outputs()?; self.global_ctxt()?.peek_mut().enter(|tcx| { tcx.analysis(LOCAL_CRATE).ok(); // Don't do code generation if there were any errors self.session().compile_status()?; - Ok(passes::start_codegen( + let outputs = tcx.prepare_outputs(())?; + + Ok((passes::start_codegen( &***self.codegen_backend(), tcx, rx, - &*outputs.peek() - )) + &outputs, + ), outputs)) }) }) } @@ -266,13 +233,13 @@ impl Compiler { self.queries.link.compute(|| { let sess = self.session(); - let ongoing_codegen = self.ongoing_codegen()?.take(); + let (ongoing_codegen, outputs) = self.ongoing_codegen()?.take(); self.codegen_backend().join_codegen_and_link( ongoing_codegen, sess, &*self.dep_graph()?.peek(), - &*self.prepare_outputs()?.peek(), + &outputs, ).map_err(|_| ErrorReported)?; Ok(()) @@ -280,7 +247,10 @@ impl Compiler { } pub fn compile(&self) -> Result<()> { - self.prepare_outputs()?; + self.global_ctxt()?.peek_mut().enter(|tcx| { + tcx.prepare_outputs(())?; + Ok(()) + })?; if self.session().opts.output_types.contains_key(&OutputType::DepInfo) && self.session().opts.output_types.len() == 1 @@ -288,10 +258,13 @@ impl Compiler { return Ok(()) } - self.global_ctxt()?; - // Drop AST after creating GlobalCtxt to free memory - mem::drop(self.expansion()?.take()); + self.global_ctxt()?.peek_mut().enter(|tcx| { + tcx.lower_ast_to_hir(())?; + // Drop AST after lowering HIR to free memory + mem::drop(tcx.ast_crate.steal()); + Ok(()) + })?; self.ongoing_codegen()?; diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index f3b9408569397..14df52734afa7 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -65,7 +65,7 @@ declare_lint! { declare_lint_pass!(WhileTrue => [WHILE_TRUE]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue { - fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) { + fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) { if let hir::ExprKind::While(ref cond, ..) = e.node { if let hir::ExprKind::Lit(ref lit) = cond.node { if let ast::LitKind::Bool(true) = lit.node { @@ -107,7 +107,7 @@ impl BoxPointers { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers { - fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) { match it.node { hir::ItemKind::Fn(..) | hir::ItemKind::Ty(..) | @@ -134,7 +134,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers { } } - fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) { + fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) { let ty = cx.tables.node_type(e.hir_id); self.check_heap_type(cx, e.span, ty); } @@ -149,7 +149,7 @@ declare_lint! { declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns { - fn check_pat(&mut self, cx: &LateContext<'_, '_>, pat: &hir::Pat) { + fn check_pat(&mut self, cx: &LateContext<'_, '_>, pat: &hir::Pat<'_>) { if let PatKind::Struct(ref qpath, ref field_pats, _) = pat.node { let variant = cx.tables.pat_ty(pat).ty_adt_def() .expect("struct pattern type is not an ADT") @@ -368,7 +368,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { self.doc_hidden_stack.pop().expect("empty doc_hidden_stack"); } - fn check_crate(&mut self, cx: &LateContext<'_, '_>, krate: &hir::Crate) { + fn check_crate(&mut self, cx: &LateContext<'_, '_>, krate: &hir::Crate<'_>) { self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate"); for macro_def in &krate.exported_macros { @@ -381,7 +381,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { } } - fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) { let desc = match it.node { hir::ItemKind::Fn(..) => "a function", hir::ItemKind::Mod(..) => "a module", @@ -426,7 +426,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { self.check_missing_docs_attrs(cx, Some(it.hir_id), &it.attrs, it.span, desc); } - fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, trait_item: &hir::TraitItem) { + fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, trait_item: &hir::TraitItem<'_>) { if self.private_traits.contains(&trait_item.hir_id) { return; } @@ -444,7 +444,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { desc); } - fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) { + fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem<'_>) { // If the method is an impl for a trait, don't doc. if method_context(cx, impl_item.hir_id) == MethodLateContext::TraitImpl { return; @@ -463,7 +463,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { desc); } - fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, sf: &hir::StructField) { + fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, sf: &hir::StructField<'_>) { if !sf.is_positional() { self.check_missing_docs_attrs(cx, Some(sf.hir_id), @@ -473,7 +473,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { } } - fn check_variant(&mut self, cx: &LateContext<'_, '_>, v: &hir::Variant, _: &hir::Generics) { + fn check_variant( + &mut self, + cx: &LateContext<'_, '_>, + v: &hir::Variant, + _: &hir::Generics<'_> + ) { self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs, @@ -491,7 +496,7 @@ declare_lint! { declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations { - fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) { if !cx.access_levels.is_reachable(item.hir_id) { return; } @@ -549,7 +554,7 @@ pub struct MissingDebugImplementations { impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations { - fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) { if !cx.access_levels.is_reachable(item.hir_id) { return; } @@ -781,7 +786,7 @@ declare_lint! { declare_lint_pass!(PluginAsLibrary => [PLUGIN_AS_LIBRARY]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary { - fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) { if cx.tcx.plugin_registrar_fn(LOCAL_CRATE).is_some() { // We're compiling a plugin; it's fine to link other plugins. return; @@ -826,7 +831,7 @@ declare_lint! { declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems { - fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) { match it.node { hir::ItemKind::Fn(.., ref generics, _) => { if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, sym::no_mangle) { @@ -891,7 +896,7 @@ declare_lint! { declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes { - fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &hir::Expr) { + fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) { use rustc_target::spec::abi::Abi::RustIntrinsic; let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \ @@ -908,7 +913,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes { fn get_transmute_from_to<'a, 'tcx> (cx: &LateContext<'a, 'tcx>, - expr: &hir::Expr) + expr: &hir::Expr<'_>) -> Option<(Ty<'tcx>, Ty<'tcx>)> { let def = if let hir::ExprKind::Path(ref qpath) = expr.node { cx.tables.qpath_res(qpath, expr.hir_id) @@ -969,7 +974,7 @@ declare_lint_pass!( ); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields { - fn check_item(&mut self, ctx: &LateContext<'_, '_>, item: &hir::Item) { + fn check_item(&mut self, ctx: &LateContext<'_, '_>, item: &hir::Item<'_>) { if let hir::ItemKind::Union(ref vdata, _) = item.node { for field in vdata.fields() { let field_ty = ctx.tcx.type_of( @@ -999,7 +1004,7 @@ declare_lint_pass!( impl UnreachablePub { fn perform_lint(&self, cx: &LateContext<'_, '_>, what: &str, id: hir::HirId, - vis: &hir::Visibility, span: Span, exportable: bool) { + vis: &hir::Visibility<'_>, span: Span, exportable: bool) { let mut applicability = Applicability::MachineApplicable; match vis.node { hir::VisibilityKind::Public if !cx.access_levels.is_reachable(id) => { @@ -1032,20 +1037,24 @@ impl UnreachablePub { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub { - fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) { self.perform_lint(cx, "item", item.hir_id, &item.vis, item.span, true); } - fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, foreign_item: &hir::ForeignItem) { + fn check_foreign_item( + &mut self, + cx: &LateContext<'_, '_>, + foreign_item: &hir::ForeignItem<'_> + ) { self.perform_lint(cx, "item", foreign_item.hir_id, &foreign_item.vis, foreign_item.span, true); } - fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField) { + fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField<'_>) { self.perform_lint(cx, "field", field.hir_id, &field.vis, field.span, false); } - fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) { + fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem<'_>) { self.perform_lint(cx, "item", impl_item.hir_id, &impl_item.vis, impl_item.span, false); } } @@ -1064,7 +1073,7 @@ declare_lint_pass!( ); impl TypeAliasBounds { - fn is_type_variable_assoc(qpath: &hir::QPath) -> bool { + fn is_type_variable_assoc(qpath: &hir::QPath<'_>) -> bool { match *qpath { hir::QPath::TypeRelative(ref ty, _) => { // If this is a type variable, we found a `T::Assoc`. @@ -1082,7 +1091,7 @@ impl TypeAliasBounds { } } - fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder<'_>) { + fn suggest_changing_assoc_types(ty: &hir::Ty<'_>, err: &mut DiagnosticBuilder<'_>) { // Access to associates types should use `::Assoc`, which does not need a // bound. Let's see if this type does that. @@ -1097,7 +1106,7 @@ impl TypeAliasBounds { intravisit::NestedVisitorMap::None } - fn visit_qpath(&mut self, qpath: &'v hir::QPath, id: hir::HirId, span: Span) { + fn visit_qpath(&mut self, qpath: &'v hir::QPath<'_>, id: hir::HirId, span: Span) { if TypeAliasBounds::is_type_variable_assoc(qpath) { self.err.span_help(span, "use fully disambiguated paths (i.e., `::Assoc`) to refer to \ @@ -1114,7 +1123,7 @@ impl TypeAliasBounds { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds { - fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item<'_>) { let (ty, type_alias_generics) = match item.node { hir::ItemKind::Ty(ref ty, ref generics) => (&*ty, generics), _ => return, @@ -1181,7 +1190,7 @@ fn check_const(cx: &LateContext<'_, '_>, body_id: hir::BodyId) { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst { - fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) { match it.node { hir::ItemKind::Const(_, body_id) => { check_const(cx, body_id); @@ -1210,7 +1219,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TrivialConstraints { fn check_item( &mut self, cx: &LateContext<'a, 'tcx>, - item: &'tcx hir::Item, + item: &'tcx hir::Item<'_>, ) { use rustc::ty::fold::TypeFoldable; use rustc::ty::Predicate::*; @@ -1371,7 +1380,7 @@ impl UnnameableTestItems { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnameableTestItems { - fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) { if self.items_nameable { if let hir::ItemKind::Mod(..) = it.node {} else { @@ -1390,7 +1399,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnameableTestItems { } } - fn check_item_post(&mut self, _cx: &LateContext<'_, '_>, it: &hir::Item) { + fn check_item_post(&mut self, _cx: &LateContext<'_, '_>, it: &hir::Item<'_>) { if !self.items_nameable && self.boundary == it.hir_id { self.items_nameable = true; } @@ -1499,7 +1508,7 @@ impl ExplicitOutlivesRequirements { cx: &LateContext<'_, '_>, item_def_id: DefId, param_name: &str, - bounds: &hir::GenericBounds, + bounds: &hir::GenericBounds<'_>, infer_static: bool ) -> Vec<(usize, Span)> { // For lack of a more elegant strategy for comparing the `ty::Predicate`s @@ -1551,7 +1560,7 @@ impl ExplicitOutlivesRequirements { fn consolidate_outlives_bound_spans( &self, lo: Span, - bounds: &hir::GenericBounds, + bounds: &hir::GenericBounds<'_>, bound_spans: Vec<(usize, Span)> ) -> Vec { if bounds.is_empty() { @@ -1606,7 +1615,7 @@ impl ExplicitOutlivesRequirements { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExplicitOutlivesRequirements { - fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) { + fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) { let infer_static = cx.tcx.features().infer_static_outlives_requirements; let def_id = cx.tcx.hir().local_def_id_from_hir_id(item.hir_id); if let hir::ItemKind::Struct(_, ref generics) = item.node { diff --git a/src/librustc_lint/lib.rs b/src/librustc_lint/lib.rs index ec8a9c6fbb2a8..b771c444b094d 100644 --- a/src/librustc_lint/lib.rs +++ b/src/librustc_lint/lib.rs @@ -19,7 +19,7 @@ #![recursion_limit="256"] -#![deny(rust_2018_idioms)] +//#![deny(rust_2018_idioms)] #![deny(internal)] #![deny(unused_lifetimes)] diff --git a/src/librustc_lint/nonstandard_style.rs b/src/librustc_lint/nonstandard_style.rs index 551eded9858a3..81fc1b37aae34 100644 --- a/src/librustc_lint/nonstandard_style.rs +++ b/src/librustc_lint/nonstandard_style.rs @@ -287,7 +287,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase { } } - fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam) { + fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam<'_>) { if let GenericParamKind::Lifetime { .. } = param.kind { self.check_snake_case(cx, "lifetime", ¶m.name.ident()); } @@ -297,8 +297,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase { &mut self, cx: &LateContext<'_, '_>, fk: FnKind<'_>, - _: &hir::FnDecl, - _: &hir::Body, + _: &hir::FnDecl<'_>, + _: &hir::Body<'_>, _: Span, id: hir::HirId, ) { @@ -325,13 +325,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase { } } - fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) { if let hir::ItemKind::Mod(_) = it.node { self.check_snake_case(cx, "module", &it.ident); } } - fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem) { + fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem<'_>) { if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(pnames)) = &item.node { self.check_snake_case(cx, "trait method", &item.ident); for param_name in pnames { @@ -340,7 +340,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase { } } - fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) { + fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat<'_>) { if let &PatKind::Binding(_, _, ident, _) = &p.node { self.check_snake_case(cx, "variable", &ident); } @@ -349,9 +349,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase { fn check_struct_def( &mut self, cx: &LateContext<'_, '_>, - s: &hir::VariantData, + s: &hir::VariantData<'_>, _: ast::Name, - _: &hir::Generics, + _: &hir::Generics<'_>, _: hir::HirId, ) { for sf in s.fields() { @@ -389,7 +389,7 @@ impl NonUpperCaseGlobals { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals { - fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) { match it.node { hir::ItemKind::Static(..) if !attr::contains_name(&it.attrs, sym::no_mangle) => { NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident); @@ -401,19 +401,19 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals { } } - fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, ti: &hir::TraitItem) { + fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, ti: &hir::TraitItem<'_>) { if let hir::TraitItemKind::Const(..) = ti.node { NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident); } } - fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, ii: &hir::ImplItem) { + fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, ii: &hir::ImplItem<'_>) { if let hir::ImplItemKind::Const(..) = ii.node { NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident); } } - fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) { + fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat<'_>) { // Lint for constants that look like binding identifiers (#7526) if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node { if let Res::Def(DefKind::Const, _) = path.res { diff --git a/src/librustc_lint/types.rs b/src/librustc_lint/types.rs index a843ee6d45d8f..c561cbbb61384 100644 --- a/src/librustc_lint/types.rs +++ b/src/librustc_lint/types.rs @@ -397,7 +397,7 @@ fn lint_literal<'a, 'tcx>( } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeLimits { - fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx hir::Expr) { + fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx hir::Expr<'_>) { match e.node { hir::ExprKind::Unary(hir::UnNeg, ref expr) => { // propagate negation, if the negation itself isn't negated @@ -440,8 +440,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeLimits { fn check_limits(cx: &LateContext<'_, '_>, binop: hir::BinOp, - l: &hir::Expr, - r: &hir::Expr) + l: &hir::Expr<'_>, + r: &hir::Expr<'_>) -> bool { let (lit, expr, swap) = match (&l.node, &r.node) { (&hir::ExprKind::Lit(_), _) => (l, r, true), @@ -887,7 +887,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { } } - fn check_foreign_fn(&mut self, id: hir::HirId, decl: &hir::FnDecl) { + fn check_foreign_fn(&mut self, id: hir::HirId, decl: &hir::FnDecl<'_>) { let def_id = self.cx.tcx.hir().local_def_id_from_hir_id(id); let sig = self.cx.tcx.fn_sig(def_id); let sig = self.cx.tcx.erase_late_bound_regions(&sig); @@ -919,7 +919,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImproperCTypes { - fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::ForeignItem) { + fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::ForeignItem<'_>) { let mut vis = ImproperCTypesVisitor { cx }; let abi = cx.tcx.hir().get_foreign_abi_by_hir_id(it.hir_id); if abi != Abi::RustIntrinsic && abi != Abi::PlatformIntrinsic { @@ -939,7 +939,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImproperCTypes { declare_lint_pass!(VariantSizeDifferences => [VARIANT_SIZE_DIFFERENCES]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences { - fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) { + fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item<'_>) { if let hir::ItemKind::Enum(ref enum_definition, _) = it.node { let item_def_id = cx.tcx.hir().local_def_id_from_hir_id(it.hir_id); let t = cx.tcx.type_of(item_def_id); diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index d540b3f7e40a3..a75082406fdb4 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -37,7 +37,7 @@ declare_lint! { declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults { - fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) { + fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt<'_>) { let expr = match s.node { hir::StmtKind::Semi(ref expr) => &**expr, _ => return, @@ -226,7 +226,7 @@ declare_lint! { declare_lint_pass!(PathStatements => [PATH_STATEMENTS]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements { - fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) { + fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt<'_>) { if let hir::StmtKind::Semi(ref expr) = s.node { if let hir::ExprKind::Path(_) = expr.node { cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect"); @@ -520,7 +520,7 @@ declare_lint! { declare_lint_pass!(UnusedAllocation => [UNUSED_ALLOCATION]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation { - fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) { + fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) { match e.node { hir::ExprKind::Box(_) => {} _ => return, diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index dbf140afda24d..45a6a8fdf3dcd 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -664,7 +664,7 @@ impl EncodeContext<'tcx> { fn encode_info_for_mod( &mut self, - (id, md, attrs, vis): (hir::HirId, &hir::Mod, &[ast::Attribute], &hir::Visibility), + (id, md, attrs, vis): (hir::HirId, &hir::Mod<'_>, &[ast::Attribute], &hir::Visibility<'_>), ) -> Entry<'tcx> { let tcx = self.tcx; let def_id = tcx.hir().local_def_id_from_hir_id(id); @@ -1066,7 +1066,10 @@ impl EncodeContext<'tcx> { self.lazy(rendered_const) } - fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> { + fn encode_info_for_item( + &mut self, + (def_id, item): (DefId, &'tcx hir::Item<'_>) + ) -> Entry<'tcx> { let tcx = self.tcx; debug!("EncodeContext::encode_info_for_item({:?})", def_id); @@ -1311,7 +1314,7 @@ impl EncodeContext<'tcx> { } /// Serialize the text of exported macros - fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> { + fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) -> Entry<'tcx> { use syntax::print::pprust; let def_id = self.tcx.hir().local_def_id_from_hir_id(macro_def.hir_id); Entry { @@ -1602,7 +1605,7 @@ impl EncodeContext<'tcx> { } fn encode_info_for_foreign_item(&mut self, - (def_id, nitem): (DefId, &hir::ForeignItem)) + (def_id, nitem): (DefId, &hir::ForeignItem<'_>)) -> Entry<'tcx> { let tcx = self.tcx; @@ -1650,11 +1653,11 @@ impl Visitor<'tcx> for EncodeContext<'tcx> { fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> { NestedVisitorMap::OnlyBodies(&self.tcx.hir()) } - fn visit_expr(&mut self, ex: &'tcx hir::Expr) { + fn visit_expr(&mut self, ex: &'tcx hir::Expr<'_>) { intravisit::walk_expr(self, ex); self.encode_info_for_expr(ex); } - fn visit_item(&mut self, item: &'tcx hir::Item) { + fn visit_item(&mut self, item: &'tcx hir::Item<'_>) { intravisit::walk_item(self, item); let def_id = self.tcx.hir().local_def_id_from_hir_id(item.hir_id); match item.node { @@ -1664,7 +1667,7 @@ impl Visitor<'tcx> for EncodeContext<'tcx> { } self.encode_addl_info_for_item(item); } - fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) { + fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'_>) { intravisit::walk_foreign_item(self, ni); let def_id = self.tcx.hir().local_def_id_from_hir_id(ni.hir_id); self.record(def_id, @@ -1672,8 +1675,8 @@ impl Visitor<'tcx> for EncodeContext<'tcx> { (def_id, ni)); } fn visit_variant(&mut self, - v: &'tcx hir::Variant, - g: &'tcx hir::Generics, + v: &'tcx hir::Variant<'_>, + g: &'tcx hir::Generics<'_>, id: hir::HirId) { intravisit::walk_variant(self, v, g, id); @@ -1682,15 +1685,15 @@ impl Visitor<'tcx> for EncodeContext<'tcx> { self.record(def_id, EncodeContext::encode_info_for_anon_const, def_id); } } - fn visit_generics(&mut self, generics: &'tcx hir::Generics) { + fn visit_generics(&mut self, generics: &'tcx hir::Generics<'_>) { intravisit::walk_generics(self, generics); self.encode_info_for_generics(generics); } - fn visit_ty(&mut self, ty: &'tcx hir::Ty) { + fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) { intravisit::walk_ty(self, ty); self.encode_info_for_ty(ty); } - fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) { + fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'_>) { let def_id = self.tcx.hir().local_def_id_from_hir_id(macro_def.hir_id); self.record(def_id, EncodeContext::encode_info_for_macro_def, macro_def); } @@ -1708,7 +1711,7 @@ impl EncodeContext<'tcx> { } } - fn encode_info_for_generics(&mut self, generics: &hir::Generics) { + fn encode_info_for_generics(&mut self, generics: &hir::Generics<'_>) { for param in &generics.params { let def_id = self.tcx.hir().local_def_id_from_hir_id(param.hir_id); match param.kind { @@ -1727,7 +1730,7 @@ impl EncodeContext<'tcx> { } } - fn encode_info_for_ty(&mut self, ty: &hir::Ty) { + fn encode_info_for_ty(&mut self, ty: &hir::Ty<'_>) { match ty.node { hir::TyKind::Array(_, ref length) => { let def_id = self.tcx.hir().local_def_id_from_hir_id(length.hir_id); @@ -1737,7 +1740,7 @@ impl EncodeContext<'tcx> { } } - fn encode_info_for_expr(&mut self, expr: &hir::Expr) { + fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) { match expr.node { hir::ExprKind::Closure(..) => { let def_id = self.tcx.hir().local_def_id_from_hir_id(expr.hir_id); @@ -1751,7 +1754,7 @@ impl EncodeContext<'tcx> { /// encode some sub-items. Usually we want some info from the item /// so it's easier to do that here then to wait until we would encounter /// normally in the visitor walk. - fn encode_addl_info_for_item(&mut self, item: &hir::Item) { + fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) { let def_id = self.tcx.hir().local_def_id_from_hir_id(item.hir_id); match item.node { hir::ItemKind::Static(..) | @@ -1821,7 +1824,7 @@ struct ImplVisitor<'tcx> { } impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> { - fn visit_item(&mut self, item: &hir::Item) { + fn visit_item(&mut self, item: &hir::Item<'_>) { if let hir::ItemKind::Impl(..) = item.node { let impl_id = self.tcx.hir().local_def_id_from_hir_id(item.hir_id); if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) { @@ -1833,9 +1836,9 @@ impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> { } } - fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {} + fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'_>) {} - fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) { + fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'_>) { // handled in `visit_item` above } } diff --git a/src/librustc_metadata/foreign_modules.rs b/src/librustc_metadata/foreign_modules.rs index 0ce103cfa40dc..3cf126de5c81b 100644 --- a/src/librustc_metadata/foreign_modules.rs +++ b/src/librustc_metadata/foreign_modules.rs @@ -18,7 +18,7 @@ struct Collector<'tcx> { } impl ItemLikeVisitor<'tcx> for Collector<'tcx> { - fn visit_item(&mut self, it: &'tcx hir::Item) { + fn visit_item(&mut self, it: &'tcx hir::Item<'_>) { let fm = match it.node { hir::ItemKind::ForeignMod(ref fm) => fm, _ => return, @@ -33,6 +33,6 @@ impl ItemLikeVisitor<'tcx> for Collector<'tcx> { }); } - fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem) {} - fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem) {} + fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem<'_>) {} + fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem<'_>) {} } diff --git a/src/librustc_metadata/link_args.rs b/src/librustc_metadata/link_args.rs index cd6270046faab..0b1fee07d252f 100644 --- a/src/librustc_metadata/link_args.rs +++ b/src/librustc_metadata/link_args.rs @@ -26,7 +26,7 @@ struct Collector { } impl<'tcx> ItemLikeVisitor<'tcx> for Collector { - fn visit_item(&mut self, it: &'tcx hir::Item) { + fn visit_item(&mut self, it: &'tcx hir::Item<'_>) { let fm = match it.node { hir::ItemKind::ForeignMod(ref fm) => fm, _ => return, @@ -45,8 +45,8 @@ impl<'tcx> ItemLikeVisitor<'tcx> for Collector { } } - fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem) {} - fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem) {} + fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem<'_>) {} + fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem<'_>) {} } impl Collector { diff --git a/src/librustc_metadata/native_libs.rs b/src/librustc_metadata/native_libs.rs index 7b335b3b4832d..bcdc65ddd980d 100644 --- a/src/librustc_metadata/native_libs.rs +++ b/src/librustc_metadata/native_libs.rs @@ -34,7 +34,7 @@ struct Collector<'tcx> { } impl ItemLikeVisitor<'tcx> for Collector<'tcx> { - fn visit_item(&mut self, it: &'tcx hir::Item) { + fn visit_item(&mut self, it: &'tcx hir::Item<'_>) { let fm = match it.node { hir::ItemKind::ForeignMod(ref fm) => fm, _ => return, @@ -126,8 +126,8 @@ impl ItemLikeVisitor<'tcx> for Collector<'tcx> { } } - fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem) {} - fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem) {} + fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem<'_>) {} + fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem<'_>) {} } impl Collector<'tcx> { diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs index 1ec30897e92da..69703b398f566 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs @@ -369,7 +369,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { ) -> Option { let mir_node_id = infcx.tcx.hir().as_local_node_id(mir_def_id)?; let fn_decl = infcx.tcx.hir().fn_decl(mir_node_id)?; - let argument_hir_ty: &hir::Ty = &fn_decl.inputs[argument_index]; + let argument_hir_ty: &hir::Ty<'_> = &fn_decl.inputs[argument_index]; match argument_hir_ty.node { // This indicates a variable with no type annotation, like // `|x|`... in that case, we can't highlight the type but @@ -464,10 +464,10 @@ impl<'tcx> RegionInferenceContext<'tcx> { tcx: TyCtxt<'tcx>, needle_fr: RegionVid, argument_ty: Ty<'tcx>, - argument_hir_ty: &hir::Ty, + argument_hir_ty: &hir::Ty<'_>, counter: &mut usize, ) -> Option { - let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty)> = + let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty<'_>)> = &mut vec![(argument_ty, argument_hir_ty)]; while let Some((ty, hir_ty)) = search_stack.pop() { @@ -558,9 +558,9 @@ impl<'tcx> RegionInferenceContext<'tcx> { &self, substs: SubstsRef<'tcx>, needle_fr: RegionVid, - last_segment: &'hir hir::PathSegment, + last_segment: &'hir hir::PathSegment<'hir>, counter: &mut usize, - search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>, + search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>, ) -> Option { // Did the user give explicit arguments? (e.g., `Foo<..>`) let args = last_segment.args.as_ref()?; @@ -604,8 +604,8 @@ impl<'tcx> RegionInferenceContext<'tcx> { &self, substs: SubstsRef<'tcx>, needle_fr: RegionVid, - args: &'hir hir::GenericArgs, - search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>, + args: &'hir hir::GenericArgs<'hir>, + search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>, ) -> Option<&'hir hir::Lifetime> { for (kind, hir_arg) in substs.iter().zip(&args.args) { match (kind.unpack(), hir_arg) { diff --git a/src/librustc_mir/build/block.rs b/src/librustc_mir/build/block.rs index 749cd6fc8bf1e..c5aca3e3237b0 100644 --- a/src/librustc_mir/build/block.rs +++ b/src/librustc_mir/build/block.rs @@ -10,7 +10,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { pub fn ast_block(&mut self, destination: &Place<'tcx>, block: BasicBlock, - ast_block: &'tcx hir::Block, + ast_block: &'tcx hir::Block<'_>, source_info: SourceInfo) -> BlockAnd<()> { let Block { diff --git a/src/librustc_mir/build/mod.rs b/src/librustc_mir/build/mod.rs index 69de862362811..7f6f6ac8c285f 100644 --- a/src/librustc_mir/build/mod.rs +++ b/src/librustc_mir/build/mod.rs @@ -515,7 +515,12 @@ fn should_abort_on_panic<'tcx>(tcx: TyCtxt<'tcx>, fn_def_id: DefId, abi: Abi) -> /////////////////////////////////////////////////////////////////////////// /// the main entry point for building MIR for a function -struct ArgInfo<'tcx>(Ty<'tcx>, Option, Option<&'tcx hir::Pat>, Option); +struct ArgInfo<'tcx>( + Ty<'tcx>, + Option, + Option<&'tcx hir::Pat<'tcx>>, + Option +); fn construct_fn<'a, 'tcx, A>( hir: Cx<'a, 'tcx>, @@ -526,7 +531,7 @@ fn construct_fn<'a, 'tcx, A>( return_ty: Ty<'tcx>, yield_ty: Option>, return_ty_span: Span, - body: &'tcx hir::Body, + body: &'tcx hir::Body<'tcx>, ) -> Body<'tcx> where A: Iterator> @@ -775,7 +780,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { mut block: BasicBlock, arguments: &[ArgInfo<'tcx>], argument_scope: region::Scope, - ast_body: &'tcx hir::Expr) + ast_body: &'tcx hir::Expr<'_>) -> BlockAnd<()> { // Allocate locals for the function arguments diff --git a/src/librustc_mir/hair/cx/block.rs b/src/librustc_mir/hair/cx/block.rs index 63239a36a1753..4b6635c5d8ceb 100644 --- a/src/librustc_mir/hair/cx/block.rs +++ b/src/librustc_mir/hair/cx/block.rs @@ -7,7 +7,7 @@ use rustc::ty; use rustc_data_structures::indexed_vec::Idx; -impl<'tcx> Mirror<'tcx> for &'tcx hir::Block { +impl<'tcx> Mirror<'tcx> for &'tcx hir::Block<'tcx> { type Output = Block<'tcx>; fn make_mirror(self, cx: &mut Cx<'_, 'tcx>) -> Block<'tcx> { @@ -43,7 +43,7 @@ impl<'tcx> Mirror<'tcx> for &'tcx hir::Block { fn mirror_stmts<'a, 'tcx>( cx: &mut Cx<'a, 'tcx>, block_id: hir::ItemLocalId, - stmts: &'tcx [hir::Stmt], + stmts: &'tcx [hir::Stmt<'tcx>], ) -> Vec> { let mut result = vec![]; for (index, stmt) in stmts.iter().enumerate() { @@ -117,7 +117,7 @@ fn mirror_stmts<'a, 'tcx>( pub fn to_expr_ref<'a, 'tcx>( cx: &mut Cx<'a, 'tcx>, - block: &'tcx hir::Block, + block: &'tcx hir::Block<'tcx>, ) -> ExprRef<'tcx> { let block_ty = cx.tables().node_type(block.hir_id); let temp_lifetime = cx.region_scope_tree.temporary_scope(block.hir_id.local_id); diff --git a/src/librustc_mir/hair/cx/expr.rs b/src/librustc_mir/hair/cx/expr.rs index 89452b23880c0..7b488db01dba6 100644 --- a/src/librustc_mir/hair/cx/expr.rs +++ b/src/librustc_mir/hair/cx/expr.rs @@ -14,7 +14,7 @@ use rustc::hir::def_id::LocalDefId; use rustc::mir::BorrowKind; use syntax_pos::Span; -impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr { +impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr<'tcx> { type Output = Expr<'tcx>; fn make_mirror(self, cx: &mut Cx<'_, 'tcx>) -> Expr<'tcx> { @@ -70,7 +70,7 @@ impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr { fn apply_adjustment<'a, 'tcx>( cx: &mut Cx<'a, 'tcx>, - hir_expr: &'tcx hir::Expr, + hir_expr: &'tcx hir::Expr<'tcx>, mut expr: Expr<'tcx>, adjustment: &Adjustment<'tcx> ) -> Expr<'tcx> { @@ -199,7 +199,7 @@ fn apply_adjustment<'a, 'tcx>( fn make_mirror_unadjusted<'a, 'tcx>( cx: &mut Cx<'a, 'tcx>, - expr: &'tcx hir::Expr, + expr: &'tcx hir::Expr<'tcx>, ) -> Expr<'tcx> { let expr_ty = cx.tables().expr_ty(expr); let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id); @@ -812,7 +812,7 @@ fn user_substs_applied_to_res( fn method_callee<'a, 'tcx>( cx: &mut Cx<'a, 'tcx>, - expr: &hir::Expr, + expr: &hir::Expr<'tcx>, span: Span, overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>, ) -> Expr<'tcx> { @@ -867,7 +867,7 @@ impl ToBorrowKind for hir::Mutability { } } -fn convert_arm<'a, 'tcx>(cx: &mut Cx<'a, 'tcx>, arm: &'tcx hir::Arm) -> Arm<'tcx> { +fn convert_arm<'a, 'tcx>(cx: &mut Cx<'a, 'tcx>, arm: &'tcx hir::Arm<'tcx>) -> Arm<'tcx> { Arm { patterns: arm.pats.iter().map(|p| cx.pattern_from_hir(p)).collect(), guard: match arm.guard { @@ -886,7 +886,7 @@ fn convert_arm<'a, 'tcx>(cx: &mut Cx<'a, 'tcx>, arm: &'tcx hir::Arm) -> Arm<'tcx fn convert_path_expr<'a, 'tcx>( cx: &mut Cx<'a, 'tcx>, - expr: &'tcx hir::Expr, + expr: &'tcx hir::Expr<'tcx>, res: Res, ) -> ExprKind<'tcx> { let substs = cx.tables().node_substs(expr.hir_id); @@ -971,7 +971,7 @@ fn convert_path_expr<'a, 'tcx>( fn convert_var( cx: &mut Cx<'_, 'tcx>, - expr: &'tcx hir::Expr, + expr: &'tcx hir::Expr<'tcx>, var_hir_id: hir::HirId, ) -> ExprKind<'tcx> { let upvar_index = cx.tables().upvar_list.get(&cx.body_owner) @@ -1122,7 +1122,7 @@ fn bin_op(op: hir::BinOpKind) -> BinOp { fn overloaded_operator<'a, 'tcx>( cx: &mut Cx<'a, 'tcx>, - expr: &'tcx hir::Expr, + expr: &'tcx hir::Expr<'tcx>, args: Vec> ) -> ExprKind<'tcx> { let fun = method_callee(cx, expr, expr.span, None); @@ -1136,7 +1136,7 @@ fn overloaded_operator<'a, 'tcx>( fn overloaded_place<'a, 'tcx>( cx: &mut Cx<'a, 'tcx>, - expr: &'tcx hir::Expr, + expr: &'tcx hir::Expr<'tcx>, place_ty: Ty<'tcx>, overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>, args: Vec>, @@ -1184,7 +1184,7 @@ fn overloaded_place<'a, 'tcx>( fn capture_upvar<'tcx>( cx: &mut Cx<'_, 'tcx>, - closure_expr: &'tcx hir::Expr, + closure_expr: &'tcx hir::Expr<'tcx>, var_hir_id: hir::HirId, upvar_ty: Ty<'tcx> ) -> ExprRef<'tcx> { @@ -1225,7 +1225,7 @@ fn capture_upvar<'tcx>( /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExprRef. fn field_refs<'a, 'tcx>( cx: &mut Cx<'a, 'tcx>, - fields: &'tcx [hir::Field] + fields: &'tcx [hir::Field<'tcx>] ) -> Vec> { fields.iter() .map(|field| { diff --git a/src/librustc_mir/hair/cx/mod.rs b/src/librustc_mir/hair/cx/mod.rs index 7740042c783fc..77c39570fa026 100644 --- a/src/librustc_mir/hair/cx/mod.rs +++ b/src/librustc_mir/hair/cx/mod.rs @@ -153,7 +153,7 @@ impl<'a, 'tcx> Cx<'a, 'tcx> { } } - pub fn pattern_from_hir(&mut self, p: &hir::Pat) -> Pattern<'tcx> { + pub fn pattern_from_hir(&mut self, p: &hir::Pat<'_>) -> Pattern<'tcx> { let tcx = self.tcx.global_tcx(); let p = match tcx.hir().get_by_hir_id(p.hir_id) { Node::Pat(p) | Node::Binding(p) => p, diff --git a/src/librustc_mir/hair/cx/to_ref.rs b/src/librustc_mir/hair/cx/to_ref.rs index a462c61c2acba..f560351e869c7 100644 --- a/src/librustc_mir/hair/cx/to_ref.rs +++ b/src/librustc_mir/hair/cx/to_ref.rs @@ -1,14 +1,14 @@ use crate::hair::*; use rustc::hir; -use syntax::ptr::P; +use rustc::hir::ptr::P; pub trait ToRef { type Output; fn to_ref(self) -> Self::Output; } -impl<'a, 'tcx: 'a> ToRef for &'tcx hir::Expr { +impl<'a, 'tcx: 'a> ToRef for &'tcx hir::Expr<'tcx> { type Output = ExprRef<'tcx>; fn to_ref(self) -> ExprRef<'tcx> { @@ -16,7 +16,7 @@ impl<'a, 'tcx: 'a> ToRef for &'tcx hir::Expr { } } -impl<'a, 'tcx: 'a> ToRef for &'tcx P { +impl<'a, 'tcx: 'a> ToRef for &'tcx P<'tcx, hir::Expr<'tcx>> { type Output = ExprRef<'tcx>; fn to_ref(self) -> ExprRef<'tcx> { @@ -52,7 +52,7 @@ impl<'a, 'tcx: 'a, T, U> ToRef for &'tcx Vec } } -impl<'a, 'tcx: 'a, T, U> ToRef for &'tcx P<[T]> +impl<'a, 'tcx: 'a, T, U> ToRef for &'tcx P<'tcx, [T]> where &'tcx T: ToRef { type Output = Vec; diff --git a/src/librustc_mir/hair/mod.rs b/src/librustc_mir/hair/mod.rs index 4694241528b71..22660d31460c9 100644 --- a/src/librustc_mir/hair/mod.rs +++ b/src/librustc_mir/hair/mod.rs @@ -185,7 +185,7 @@ pub enum ExprKind<'tcx> { arms: Vec>, }, Block { - body: &'tcx hir::Block, + body: &'tcx hir::Block<'tcx>, }, Assign { lhs: ExprRef<'tcx>, @@ -280,7 +280,7 @@ pub enum ExprKind<'tcx> { #[derive(Clone, Debug)] pub enum ExprRef<'tcx> { - Hair(&'tcx hir::Expr), + Hair(&'tcx hir::Expr<'tcx>), Mirror(Box>), } diff --git a/src/librustc_mir/hair/pattern/check_match.rs b/src/librustc_mir/hair/pattern/check_match.rs index e7fd308070c9b..45004328cab67 100644 --- a/src/librustc_mir/hair/pattern/check_match.rs +++ b/src/librustc_mir/hair/pattern/check_match.rs @@ -17,13 +17,13 @@ use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc::hir::def::*; use rustc::hir::def_id::DefId; +use rustc::hir::ptr::P; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; use rustc::hir::{self, Pat, PatKind}; use smallvec::smallvec; use std::slice; -use syntax::ptr::P; use syntax_pos::{Span, DUMMY_SP, MultiSpan}; pub(crate) fn check_match<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) { @@ -61,7 +61,7 @@ impl<'a, 'tcx> Visitor<'tcx> for MatchVisitor<'a, 'tcx> { NestedVisitorMap::None } - fn visit_expr(&mut self, ex: &'tcx hir::Expr) { + fn visit_expr(&mut self, ex: &'tcx hir::Expr<'_>) { intravisit::walk_expr(self, ex); match ex.node { @@ -72,7 +72,7 @@ impl<'a, 'tcx> Visitor<'tcx> for MatchVisitor<'a, 'tcx> { } } - fn visit_local(&mut self, loc: &'tcx hir::Local) { + fn visit_local(&mut self, loc: &'tcx hir::Local<'_>) { intravisit::walk_local(self, loc); self.check_irrefutable(&loc.pat, match loc.source { @@ -86,7 +86,7 @@ impl<'a, 'tcx> Visitor<'tcx> for MatchVisitor<'a, 'tcx> { self.check_patterns(false, slice::from_ref(&loc.pat)); } - fn visit_body(&mut self, body: &'tcx hir::Body) { + fn visit_body(&mut self, body: &'tcx hir::Body<'_>) { intravisit::walk_body(self, body); for arg in &body.arguments { @@ -130,7 +130,7 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> { } impl<'a, 'tcx> MatchVisitor<'a, 'tcx> { - fn check_patterns(&self, has_guard: bool, pats: &[P]) { + fn check_patterns(&self, has_guard: bool, pats: &[P<'_, Pat<'_>>]) { check_legality_of_move_bindings(self, has_guard, pats); for pat in pats { check_legality_of_bindings_in_at_patterns(self, pat); @@ -139,8 +139,8 @@ impl<'a, 'tcx> MatchVisitor<'a, 'tcx> { fn check_match( &self, - scrut: &hir::Expr, - arms: &'tcx [hir::Arm], + scrut: &hir::Expr<'_>, + arms: &'tcx [hir::Arm<'tcx>], source: hir::MatchSource) { for arm in arms { @@ -175,10 +175,10 @@ impl<'a, 'tcx> MatchVisitor<'a, 'tcx> { patcx.report_inlining_errors(pat.span); have_errors = true; } - (pattern, &**pat) + (pattern, &***pat) }).collect(), arm.guard.as_ref().map(|g| match g { - hir::Guard::If(ref e) => &**e, + hir::Guard::If(ref e) => &***e, }) )).collect(); @@ -260,7 +260,7 @@ impl<'a, 'tcx> MatchVisitor<'a, 'tcx> { }) } - fn check_irrefutable(&self, pat: &'tcx Pat, origin: &str) { + fn check_irrefutable(&self, pat: &'tcx Pat<'_>, origin: &str) { let module = self.tcx.hir().get_module_parent_by_hir_id(pat.hir_id); MatchCheckCtxt::create_and_enter(self.tcx, self.param_env, module, |ref mut cx| { let mut patcx = PatternContext::new(self.tcx, @@ -308,7 +308,7 @@ impl<'a, 'tcx> MatchVisitor<'a, 'tcx> { } } -fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pat) { +fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>) { pat.walk(|p| { if let PatKind::Binding(_, _, ident, None) = p.node { if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) { @@ -344,7 +344,7 @@ fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pa } /// Checks for common cases of "catchall" patterns that may not be intended as such. -fn pat_is_catchall(pat: &Pat) -> bool { +fn pat_is_catchall(pat: &Pat<'_>) -> bool { match pat.node { PatKind::Binding(.., None) => true, PatKind::Binding(.., Some(ref s)) => pat_is_catchall(s), @@ -357,11 +357,10 @@ fn pat_is_catchall(pat: &Pat) -> bool { } // Check for unreachable patterns -fn check_arms<'a, 'tcx>( - cx: &mut MatchCheckCtxt<'a, 'tcx>, - arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat)>, Option<&hir::Expr>)], - source: hir::MatchSource, -) { +fn check_arms<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>, + arms: &[(Vec<(&'a Pattern<'tcx>, &hir::Pat<'_>)>, Option<&hir::Expr<'_>>)], + source: hir::MatchSource) +{ let mut seen = Matrix::empty(); let mut catchall = None; for (arm_index, &(ref pats, guard)) in arms.iter().enumerate() { @@ -544,11 +543,9 @@ fn maybe_point_at_variant( } // Legality of move bindings checking -fn check_legality_of_move_bindings( - cx: &MatchVisitor<'_, '_>, - has_guard: bool, - pats: &[P], -) { +fn check_legality_of_move_bindings(cx: &MatchVisitor<'_, '_>, + has_guard: bool, + pats: &[P<'_, Pat<'_>>]) { let mut by_ref_span = None; for pat in pats { pat.each_binding(|_, hir_id, span, _path| { @@ -562,7 +559,7 @@ fn check_legality_of_move_bindings( }) } let span_vec = &mut Vec::new(); - let check_move = |p: &Pat, sub: Option<&Pat>, span_vec: &mut Vec| { + let check_move = |p: &Pat<'_>, sub: Option<&Pat<'_>>, span_vec: &mut Vec| { // check legality of moving out of the enum // x @ Foo(..) is legal, but x @ Foo(y) isn't. @@ -593,7 +590,7 @@ fn check_legality_of_move_bindings( ty::BindByValue(..) => { let pat_ty = cx.tables.node_type(p.hir_id); if !pat_ty.is_copy_modulo_regions(cx.tcx, cx.param_env, pat.span) { - check_move(p, sub.as_ref().map(|p| &**p), span_vec); + check_move(p, sub.as_ref().map(|p| &***p), span_vec); } } _ => {} @@ -626,7 +623,7 @@ fn check_legality_of_move_bindings( /// Ensures that a pattern guard doesn't borrow by mutable reference or assign. // // FIXME: this should be done by borrowck. -fn check_for_mutation_in_guard(cx: &MatchVisitor<'_, '_>, guard: &hir::Guard) { +fn check_for_mutation_in_guard(cx: &MatchVisitor<'_, '_>, guard: &hir::Guard<'_>) { let mut checker = MutationChecker { cx, }; @@ -647,9 +644,9 @@ struct MutationChecker<'a, 'tcx: 'a> { } impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> { - fn matched_pat(&mut self, _: &Pat, _: &cmt_<'_>, _: euv::MatchMode) {} + fn matched_pat(&mut self, _: &Pat<'_>, _: &cmt_<'_>, _: euv::MatchMode) {} fn consume(&mut self, _: hir::HirId, _: Span, _: &cmt_<'_>, _: ConsumeMode) {} - fn consume_pat(&mut self, _: &Pat, _: &cmt_<'_>, _: ConsumeMode) {} + fn consume_pat(&mut self, _: &Pat<'_>, _: &cmt_<'_>, _: ConsumeMode) {} fn borrow(&mut self, _: hir::HirId, span: Span, @@ -687,7 +684,7 @@ impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> { /// Forbids bindings in `@` patterns. This is necessary for memory safety, /// because of the way rvalues are handled in the borrow check. (See issue /// #14587.) -fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat) { +fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_>) { AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat); } @@ -701,7 +698,7 @@ impl<'a, 'b, 'tcx, 'v> Visitor<'v> for AtBindingPatternVisitor<'a, 'b, 'tcx> { NestedVisitorMap::None } - fn visit_pat(&mut self, pat: &Pat) { + fn visit_pat(&mut self, pat: &Pat<'v>) { match pat.node { PatKind::Binding(.., ref subpat) => { if !self.bindings_allowed { diff --git a/src/librustc_mir/hair/pattern/mod.rs b/src/librustc_mir/hair/pattern/mod.rs index e0e14852c577a..fa2980d479b00 100644 --- a/src/librustc_mir/hair/pattern/mod.rs +++ b/src/librustc_mir/hair/pattern/mod.rs @@ -19,6 +19,7 @@ use rustc::ty::subst::{SubstsRef, Kind}; use rustc::ty::layout::{VariantIdx, Size}; use rustc::hir::{self, PatKind, RangeEnd}; use rustc::hir::def::{CtorOf, Res, DefKind, CtorKind}; +use rustc::hir::ptr::P; use rustc::hir::pat_util::EnumerateAndAdjustIterator; use rustc_data_structures::indexed_vec::Idx; @@ -26,7 +27,6 @@ use rustc_data_structures::indexed_vec::Idx; use std::cmp::Ordering; use std::fmt; use syntax::ast; -use syntax::ptr::P; use syntax::symbol::sym; use syntax_pos::Span; @@ -339,7 +339,7 @@ impl<'a, 'tcx> Pattern<'tcx> { tcx: TyCtxt<'tcx>, param_env_and_substs: ty::ParamEnvAnd<'tcx, SubstsRef<'tcx>>, tables: &'a ty::TypeckTables<'tcx>, - pat: &'tcx hir::Pat, + pat: &'tcx hir::Pat<'tcx>, ) -> Self { let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables); let result = pcx.lower_pattern(pat); @@ -367,7 +367,7 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> { } } - pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> { + pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Pattern<'tcx> { // When implicit dereferences have been inserted in this pattern, the unadjusted lowered // pattern has the type that results *after* dereferencing. For example, in this code: // @@ -407,7 +407,7 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> { fn lower_range_expr( &mut self, - expr: &'tcx hir::Expr, + expr: &'tcx hir::Expr<'tcx>, ) -> (PatternKind<'tcx>, Option>) { match self.lower_lit(expr) { PatternKind::AscribeUserType { @@ -418,7 +418,7 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> { } } - fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> { + fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Pattern<'tcx> { let mut ty = self.tables.node_type(pat.hir_id); let kind = match pat.node { @@ -652,12 +652,14 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> { } } - fn lower_patterns(&mut self, pats: &'tcx [P]) -> Vec> { + fn lower_patterns(&mut self, pats: &'tcx [P<'tcx, hir::Pat<'tcx>>]) -> Vec> { pats.iter().map(|p| self.lower_pattern(p)).collect() } - fn lower_opt_pattern(&mut self, pat: &'tcx Option>) -> Option> - { + fn lower_opt_pattern( + &mut self, + pat: &'tcx Option>> + ) -> Option> { pat.as_ref().map(|p| self.lower_pattern(p)) } @@ -699,9 +701,9 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> { &mut self, span: Span, ty: Ty<'tcx>, - prefix: &'tcx [P], - slice: &'tcx Option>, - suffix: &'tcx [P]) + prefix: &'tcx [P<'tcx, hir::Pat<'tcx>>], + slice: &'tcx Option>>, + suffix: &'tcx [P<'tcx, hir::Pat<'tcx>>]) -> PatternKind<'tcx> { let prefix = self.lower_patterns(prefix); @@ -808,7 +810,7 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> { /// it to `const_to_pat`. Any other path (like enum variants without fields) /// is converted to the corresponding pattern via `lower_variant_or_leaf`. fn lower_path(&mut self, - qpath: &hir::QPath, + qpath: &hir::QPath<'tcx>, id: hir::HirId, span: Span) -> Pattern<'tcx> { @@ -895,7 +897,7 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> { /// The special case for negation exists to allow things like `-128_i8` /// which would overflow if we tried to evaluate `128_i8` and then negate /// afterwards. - fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> { + fn lower_lit(&mut self, expr: &'tcx hir::Expr<'tcx>) -> PatternKind<'tcx> { match expr.node { hir::ExprKind::Lit(ref lit) => { let ty = self.tables.expr_ty(expr); diff --git a/src/librustc_mir/monomorphize/collector.rs b/src/librustc_mir/monomorphize/collector.rs index e530c56ed6f3a..b686e16a690f9 100644 --- a/src/librustc_mir/monomorphize/collector.rs +++ b/src/librustc_mir/monomorphize/collector.rs @@ -963,7 +963,7 @@ struct RootCollector<'a, 'tcx> { } impl ItemLikeVisitor<'v> for RootCollector<'_, 'v> { - fn visit_item(&mut self, item: &'v hir::Item) { + fn visit_item(&mut self, item: &'v hir::Item<'v>) { match item.node { hir::ItemKind::ExternCrate(..) | hir::ItemKind::Use(..) | @@ -1035,12 +1035,12 @@ impl ItemLikeVisitor<'v> for RootCollector<'_, 'v> { } } - fn visit_trait_item(&mut self, _: &'v hir::TraitItem) { + fn visit_trait_item(&mut self, _: &'v hir::TraitItem<'v>) { // Even if there's a default body with no explicit generics, // it's still generic over some `Self: Trait`, so not a root. } - fn visit_impl_item(&mut self, ii: &'v hir::ImplItem) { + fn visit_impl_item(&mut self, ii: &'v hir::ImplItem<'v>) { match ii.node { hir::ImplItemKind::Method(hir::MethodSig { .. }, _) => { let def_id = self.tcx.hir().local_def_id_from_hir_id(ii.hir_id); @@ -1121,7 +1121,7 @@ fn item_requires_monomorphization<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> boo fn create_mono_items_for_default_impls<'tcx>( tcx: TyCtxt<'tcx>, - item: &'tcx hir::Item, + item: &'tcx hir::Item<'tcx>, output: &mut Vec>, ) { match item.node { diff --git a/src/librustc_mir/transform/check_unsafety.rs b/src/librustc_mir/transform/check_unsafety.rs index 80a31efd0d3fe..dc79b36d12258 100644 --- a/src/librustc_mir/transform/check_unsafety.rs +++ b/src/librustc_mir/transform/check_unsafety.rs @@ -471,7 +471,7 @@ impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> { hir::intravisit::NestedVisitorMap::None } - fn visit_block(&mut self, block: &'tcx hir::Block) { + fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) { hir::intravisit::walk_block(self, block); if let hir::UnsafeBlock(hir::UserProvided) = block.rules { diff --git a/src/librustc_mir/transform/mod.rs b/src/librustc_mir/transform/mod.rs index 04dce326e69de..ba218cd82ada0 100644 --- a/src/librustc_mir/transform/mod.rs +++ b/src/librustc_mir/transform/mod.rs @@ -72,9 +72,9 @@ fn mir_keys<'tcx>(tcx: TyCtxt<'tcx>, krate: CrateNum) -> &'tcx DefIdSet { } impl<'a, 'tcx> Visitor<'tcx> for GatherCtors<'a, 'tcx> { fn visit_variant_data(&mut self, - v: &'tcx hir::VariantData, + v: &'tcx hir::VariantData<'tcx>, _: ast::Name, - _: &'tcx hir::Generics, + _: &'tcx hir::Generics<'tcx>, _: hir::HirId, _: Span) { if let hir::VariantData::Tuple(_, hir_id) = *v { diff --git a/src/librustc_passes/hir_stats.rs b/src/librustc_passes/hir_stats.rs index 6936aedb9de80..df9b31cf3b461 100644 --- a/src/librustc_passes/hir_stats.rs +++ b/src/librustc_passes/hir_stats.rs @@ -23,7 +23,7 @@ struct NodeData { } struct StatCollector<'k> { - krate: Option<&'k hir::Crate>, + krate: Option<&'k hir::Crate<'k>>, data: FxHashMap<&'static str, NodeData>, seen: FxHashSet, } diff --git a/src/librustc_passes/lib.rs b/src/librustc_passes/lib.rs index bf2f7634e55a1..764399975ba48 100644 --- a/src/librustc_passes/lib.rs +++ b/src/librustc_passes/lib.rs @@ -12,7 +12,7 @@ #![recursion_limit="256"] -#![deny(rust_2018_idioms)] +//#![deny(rust_2018_idioms)] #![deny(internal)] #![deny(unused_lifetimes)] diff --git a/src/librustc_plugin/lib.rs b/src/librustc_plugin/lib.rs index cb6f8ebd82e4e..d2714cf608ac2 100644 --- a/src/librustc_plugin/lib.rs +++ b/src/librustc_plugin/lib.rs @@ -58,8 +58,6 @@ #![recursion_limit="256"] -#![deny(rust_2018_idioms)] - pub use registry::Registry; mod error_codes; diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index c2cb2f4d1745e..d8397add8d146 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -1,6 +1,6 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")] -#![deny(rust_2018_idioms)] +//#![deny(rust_2018_idioms)] #![deny(internal)] #![deny(unused_lifetimes)] diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index fec7bf3b273ee..fc5e0fe72f80e 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -20,8 +20,9 @@ use GenericParameters::*; use RibKind::*; use smallvec::smallvec; +use rustc::arena::Arena; use rustc::hir::map::{Definitions, DefCollector}; -use rustc::hir::{self, PrimTy, Bool, Char, Float, Int, Uint, Str}; +use rustc::hir::{self, PrimTy, Bool, Char, Float, Int, Uint, Str, HirVec}; use rustc::middle::cstore::CrateStore; use rustc::session::Session; use rustc::lint; @@ -1751,23 +1752,25 @@ impl<'a, 'b: 'a> ty::DefIdTree for &'a Resolver<'b> { /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that /// the resolver is no longer needed as all the relevant information is inline. -impl<'a> hir::lowering::Resolver for Resolver<'a> { +impl<'a, 'hir> hir::lowering::Resolver<'hir> for Resolver<'a> { fn resolve_hir_path( &mut self, + arena: &'hir Arena<'hir>, path: &ast::Path, is_value: bool, - ) -> hir::Path { - self.resolve_hir_path_cb(path, is_value, + ) -> hir::Path<'hir> { + self.resolve_hir_path_cb(arena, path, is_value, |resolver, span, error| resolve_error(resolver, span, error)) } fn resolve_str_path( &mut self, + arena: &'hir Arena<'hir>, span: Span, crate_root: Option, components: &[Symbol], is_value: bool - ) -> hir::Path { + ) -> hir::Path<'hir> { let root = if crate_root.is_some() { kw::PathRoot } else { @@ -1785,7 +1788,7 @@ impl<'a> hir::lowering::Resolver for Resolver<'a> { segments, }; - self.resolve_hir_path(&path, is_value) + self.resolve_hir_path(arena, &path, is_value) } fn get_partial_res(&mut self, id: NodeId) -> Option { @@ -1810,8 +1813,13 @@ impl<'a> Resolver<'a> { /// isn't something that can be returned because it can't be made to live that long, /// and also it's a private type. Fortunately rustdoc doesn't need to know the error, /// just that an error occurred. - pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: bool) - -> Result { + pub fn resolve_str_path_error<'hir>( + &mut self, + arena: &'hir Arena<'hir>, + span: Span, + path_str: &str, + is_value: bool + ) -> Result, ()> { let mut errored = false; let path = if path_str.starts_with("::") { @@ -1834,7 +1842,7 @@ impl<'a> Resolver<'a> { .collect(), } }; - let path = self.resolve_hir_path_cb(&path, is_value, |_, _, _| errored = true); + let path = self.resolve_hir_path_cb(arena, &path, is_value, |_, _, _| errored = true); if errored || path.res == def::Res::Err { Err(()) } else { @@ -1843,12 +1851,13 @@ impl<'a> Resolver<'a> { } /// Like `resolve_hir_path`, but takes a callback in case there was an error. - fn resolve_hir_path_cb( + fn resolve_hir_path_cb<'hir, F>( &mut self, + arena: &'hir Arena<'hir>, path: &ast::Path, is_value: bool, error_callback: F, - ) -> hir::Path + ) -> hir::Path<'hir> where F: for<'c, 'b> FnOnce(&'c mut Resolver<'_>, Span, ResolutionError<'b>) { let namespace = if is_value { ValueNS } else { TypeNS }; @@ -1889,7 +1898,7 @@ impl<'a> Resolver<'a> { hir::Path { span, res: res.map_id(|_| panic!("unexpected node_id")), - segments: segments.into(), + segments: HirVec::from_iter(arena, segments), } } diff --git a/src/librustc_traits/lib.rs b/src/librustc_traits/lib.rs index 7311fd96dadc7..8c360255b558e 100644 --- a/src/librustc_traits/lib.rs +++ b/src/librustc_traits/lib.rs @@ -1,7 +1,7 @@ //! New recursive solver modeled on Chalk's recursive solver. Most of //! the guts are broken up into modules; see the comments in those modules. -#![deny(rust_2018_idioms)] +//#![deny(rust_2018_idioms)] #![deny(internal)] #![deny(unused_lifetimes)] diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index c4d841ede0797..8143c089fc2c0 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -6,7 +6,7 @@ use errors::{Applicability, DiagnosticId}; use crate::hir::{self, GenericArg, GenericArgs, ExprKind}; use crate::hir::def::{CtorOf, Res, DefKind}; use crate::hir::def_id::DefId; -use crate::hir::HirVec; +use crate::hir::ptr::P; use crate::lint; use crate::middle::lang_items::SizedTraitLangItem; use crate::middle::resolve_lifetime as rl; @@ -23,7 +23,6 @@ use crate::require_c_abi_if_c_variadic; use smallvec::SmallVec; use syntax::ast; use syntax::feature_gate::{GateIssue, emit_feature_err}; -use syntax::ptr::P; use syntax::util::lev_distance::find_best_match_for_name; use syntax::symbol::sym; use syntax_pos::{DUMMY_SP, Span, MultiSpan}; @@ -105,7 +104,7 @@ struct ConvertedBinding<'tcx> { enum ConvertedBindingKind<'tcx> { Equality(Ty<'tcx>), - Constraint(P<[hir::GenericBound]>), + Constraint(P<'tcx, [hir::GenericBound<'tcx>]>), } #[derive(PartialEq)] @@ -188,7 +187,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { pub fn ast_path_substs_for_ty(&self, span: Span, def_id: DefId, - item_segment: &hir::PathSegment) + item_segment: &hir::PathSegment<'tcx>) -> SubstsRef<'tcx> { let (substs, assoc_bindings, _) = item_segment.with_generic_args(|generic_args| { @@ -245,9 +244,6 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { seg: &hir::PathSegment, is_method_call: bool, ) -> bool { - let empty_args = P(hir::GenericArgs { - args: HirVec::new(), bindings: HirVec::new(), parenthesized: false, - }); let suppress_mismatch = Self::check_impl_trait(tcx, span, seg, &def); Self::check_generic_arg_count( tcx, @@ -256,7 +252,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { if let Some(ref args) = seg.args { args } else { - &empty_args + &tcx.common.empty_generic_args }, if is_method_call { GenericArgPosition::MethodCall @@ -467,10 +463,13 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { parent_substs: &[Kind<'tcx>], has_self: bool, self_ty: Option>, - args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs>, bool), - provided_kind: impl Fn(&GenericParamDef, &GenericArg) -> Kind<'tcx>, + args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs<'tcx>>, bool), + provided_kind: impl Fn(&GenericParamDef, &GenericArg<'tcx>) -> Kind<'tcx>, inferred_kind: impl Fn(Option<&[Kind<'tcx>]>, &GenericParamDef, bool) -> Kind<'tcx>, - ) -> SubstsRef<'tcx> { + ) -> SubstsRef<'tcx> + where + 'tcx: 'b + { // Collect the segments of the path; we need to substitute arguments // for parameters throughout the entire path (wherever there are // generic parameters). @@ -592,10 +591,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// `Output = u32` are returned in the `Vec` result. /// /// Note that the type listing given here is *exactly* what the user provided. - fn create_substs_for_ast_path<'a>(&self, + fn create_substs_for_ast_path(&self, span: Span, def_id: DefId, - generic_args: &'a hir::GenericArgs, + generic_args: &hir::GenericArgs<'tcx>, infer_args: bool, self_ty: Option>) -> (SubstsRef<'tcx>, Vec>, Option>) @@ -763,7 +762,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// If the `projections` argument is `None`, then assoc type bindings like `Foo` /// are disallowed. Otherwise, they are pushed onto the vector given. pub fn instantiate_mono_trait_ref(&self, - trait_ref: &hir::TraitRef, + trait_ref: &hir::TraitRef<'tcx>, self_ty: Ty<'tcx> ) -> ty::TraitRef<'tcx> { @@ -777,7 +776,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// The given trait-ref must actually be a trait. pub(super) fn instantiate_poly_trait_ref_inner(&self, - trait_ref: &hir::TraitRef, + trait_ref: &hir::TraitRef<'tcx>, self_ty: Ty<'tcx>, bounds: &mut Bounds<'tcx>, speculative: bool, @@ -837,7 +836,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly, /// however. pub fn instantiate_poly_trait_ref(&self, - poly_trait_ref: &hir::PolyTraitRef, + poly_trait_ref: &hir::PolyTraitRef<'tcx>, self_ty: Ty<'tcx>, bounds: &mut Bounds<'tcx> ) -> (ty::PolyTraitRef<'tcx>, Option>) @@ -849,7 +848,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { span: Span, trait_def_id: DefId, self_ty: Ty<'tcx>, - trait_segment: &hir::PathSegment + trait_segment: &hir::PathSegment<'tcx> ) -> ty::TraitRef<'tcx> { let (substs, assoc_bindings, _) = @@ -866,7 +865,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { span: Span, trait_def_id: DefId, self_ty: Ty<'tcx>, - trait_segment: &hir::PathSegment, + trait_segment: &hir::PathSegment<'tcx>, ) -> (SubstsRef<'tcx>, Vec>, Option>) { debug!("create_substs_for_ast_trait_ref(trait_segment={:?})", trait_segment); @@ -971,7 +970,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// for more details. fn add_bounds(&self, param_ty: Ty<'tcx>, - ast_bounds: &[hir::GenericBound], + ast_bounds: &[hir::GenericBound<'tcx>], bounds: &mut Bounds<'tcx>, ) { let mut trait_bounds = Vec::new(); @@ -1020,7 +1019,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// `span` should be the declaration size of the parameter. pub fn compute_bounds(&self, param_ty: Ty<'tcx>, - ast_bounds: &[hir::GenericBound], + ast_bounds: &[hir::GenericBound<'tcx>], sized_by_default: SizedByDefault, span: Span, ) -> Bounds<'tcx> { @@ -1190,7 +1189,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { fn ast_path_to_ty(&self, span: Span, did: DefId, - item_segment: &hir::PathSegment) + item_segment: &hir::PathSegment<'tcx>) -> Ty<'tcx> { let substs = self.ast_path_substs_for_ty(span, did, item_segment); @@ -1212,7 +1211,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { fn conv_object_ty_poly_trait_ref(&self, span: Span, - trait_bounds: &[hir::PolyTraitRef], + trait_bounds: &[hir::PolyTraitRef<'tcx>], lifetime: &hir::Lifetime) -> Ty<'tcx> { @@ -1580,7 +1579,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { span: Span, qself_ty: Ty<'tcx>, qself_res: Res, - assoc_segment: &hir::PathSegment, + assoc_segment: &hir::PathSegment<'tcx>, permit_variants: bool, ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> { let tcx = self.tcx(); @@ -1727,8 +1726,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { span: Span, opt_self_ty: Option>, item_def_id: DefId, - trait_segment: &hir::PathSegment, - item_segment: &hir::PathSegment) + trait_segment: &hir::PathSegment<'tcx>, + item_segment: &hir::PathSegment<'tcx>) -> Ty<'tcx> { let tcx = self.tcx(); @@ -1761,8 +1760,13 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs)) } - pub fn prohibit_generics<'a, T: IntoIterator>( - &self, segments: T) -> bool { + pub fn prohibit_generics<'a, T: IntoIterator>>( + &self, + segments: T + ) -> bool + where + 'tcx: 'a + { let mut has_err = false; for segment in segments { segment.with_generic_args(|generic_args| { @@ -1951,7 +1955,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // Check a type `Path` and convert it to a `Ty`. pub fn res_to_ty(&self, opt_self_ty: Option>, - path: &hir::Path, + path: &hir::Path<'tcx>, permit_variants: bool) -> Ty<'tcx> { let tcx = self.tcx(); @@ -2057,7 +2061,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// Parses the programmer's textual representation of a type into our /// internal notion of a type. - pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> { + pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.node); @@ -2253,7 +2257,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } pub fn ty_of_arg(&self, - ty: &hir::Ty, + ty: &hir::Ty<'tcx>, expected_ty: Option>) -> Ty<'tcx> { @@ -2269,7 +2273,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { pub fn ty_of_fn(&self, unsafety: hir::Unsafety, abi: abi::Abi, - decl: &hir::FnDecl) + decl: &hir::FnDecl<'tcx>) -> ty::PolyFnSig<'tcx> { debug!("ty_of_fn"); diff --git a/src/librustc_typeck/check/_match.rs b/src/librustc_typeck/check/_match.rs index f74dbe30d3c56..eed1e0d1dd3f7 100644 --- a/src/librustc_typeck/check/_match.rs +++ b/src/librustc_typeck/check/_match.rs @@ -4,6 +4,7 @@ use crate::util::nodemap::FxHashMap; use errors::{Applicability, DiagnosticBuilder}; use rustc::hir::{self, PatKind, Pat, ExprKind}; use rustc::hir::def::{Res, DefKind, CtorKind}; +use rustc::hir::ptr::P; use rustc::hir::pat_util::EnumerateAndAdjustIterator; use rustc::infer; use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; @@ -12,7 +13,6 @@ use rustc::ty::{self, Ty, TypeFoldable}; use rustc::ty::subst::Kind; use syntax::ast; use syntax::source_map::Spanned; -use syntax::ptr::P; use syntax::util::lev_distance::find_best_match_for_name; use syntax_pos::Span; use syntax_pos::hygiene::CompilerDesugaringKind; @@ -784,8 +784,8 @@ https://doc.rust-lang.org/reference/types.html#trait-objects"); fn if_fallback_coercion( &self, span: Span, - then_expr: &'tcx hir::Expr, - coercion: &mut CoerceMany<'tcx, '_, rustc::hir::Arm>, + then_expr: &'tcx hir::Expr<'tcx>, + coercion: &mut CoerceMany<'tcx, '_, rustc::hir::Arm<'tcx>>, ) { // If this `if` expr is the parent's function return expr, // the cause of the type coercion is the return type, point at it. (#25228) @@ -1022,9 +1022,9 @@ https://doc.rust-lang.org/reference/types.html#trait-objects"); fn check_pat_struct( &self, - pat: &'tcx hir::Pat, - qpath: &hir::QPath, - fields: &'tcx [Spanned], + pat: &'tcx hir::Pat<'tcx>, + qpath: &hir::QPath<'tcx>, + fields: &'tcx [Spanned>], etc: bool, expected: Ty<'tcx>, def_bm: ty::BindingMode, @@ -1055,9 +1055,9 @@ https://doc.rust-lang.org/reference/types.html#trait-objects"); fn check_pat_path( &self, - pat: &hir::Pat, - path_resolution: (Res, Option>, &'b [hir::PathSegment]), - qpath: &hir::QPath, + pat: &hir::Pat<'tcx>, + path_resolution: (Res, Option>, &'b [hir::PathSegment<'tcx>]), + qpath: &hir::QPath<'tcx>, expected: Ty<'tcx>, ) -> Ty<'tcx> { let tcx = self.tcx; @@ -1088,9 +1088,9 @@ https://doc.rust-lang.org/reference/types.html#trait-objects"); fn check_pat_tuple_struct( &self, - pat: &hir::Pat, - qpath: &hir::QPath, - subpats: &'tcx [P], + pat: &hir::Pat<'tcx>, + qpath: &hir::QPath<'tcx>, + subpats: &'tcx [P<'tcx, hir::Pat<'tcx>>], ddpos: Option, expected: Ty<'tcx>, def_bm: ty::BindingMode, diff --git a/src/librustc_typeck/check/callee.rs b/src/librustc_typeck/check/callee.rs index 0207f18ac81d5..ca56050aa2080 100644 --- a/src/librustc_typeck/check/callee.rs +++ b/src/librustc_typeck/check/callee.rs @@ -493,8 +493,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { #[derive(Debug)] pub struct DeferredCallResolution<'tcx> { - call_expr: &'tcx hir::Expr, - callee_expr: &'tcx hir::Expr, + call_expr: &'tcx hir::Expr<'tcx>, + callee_expr: &'tcx hir::Expr<'tcx>, adjusted_ty: Ty<'tcx>, adjustments: Vec>, fn_sig: ty::FnSig<'tcx>, diff --git a/src/librustc_typeck/check/cast.rs b/src/librustc_typeck/check/cast.rs index 53101499af1dc..002f6bc0e088d 100644 --- a/src/librustc_typeck/check/cast.rs +++ b/src/librustc_typeck/check/cast.rs @@ -48,7 +48,7 @@ use crate::util::common::ErrorReported; /// Reifies a cast check to be checked once we have full type information for /// a function context. pub struct CastCheck<'tcx> { - expr: &'tcx hir::Expr, + expr: &'tcx hir::Expr<'tcx>, expr_ty: Ty<'tcx>, cast_ty: Ty<'tcx>, cast_span: Span, diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs index 6c0deededdc73..4f97c8afd93b4 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -316,8 +316,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn sig_of_closure( &self, expr_def_id: DefId, - decl: &hir::FnDecl, - body: &hir::Body, + decl: &hir::FnDecl<'tcx>, + body: &hir::Body<'tcx>, expected_sig: Option>, ) -> ClosureSignatures<'tcx> { if let Some(e) = expected_sig { @@ -332,8 +332,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn sig_of_closure_no_expectation( &self, expr_def_id: DefId, - decl: &hir::FnDecl, - body: &hir::Body, + decl: &hir::FnDecl<'tcx>, + body: &hir::Body<'tcx>, ) -> ClosureSignatures<'tcx> { debug!("sig_of_closure_no_expectation()"); @@ -392,8 +392,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn sig_of_closure_with_expectation( &self, expr_def_id: DefId, - decl: &hir::FnDecl, - body: &hir::Body, + decl: &hir::FnDecl<'tcx>, + body: &hir::Body<'tcx>, expected_sig: ExpectedSig<'tcx>, ) -> ClosureSignatures<'tcx> { debug!( @@ -450,8 +450,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn sig_of_closure_with_mismatched_number_of_arguments( &self, expr_def_id: DefId, - decl: &hir::FnDecl, - body: &hir::Body, + decl: &hir::FnDecl<'tcx>, + body: &hir::Body<'tcx>, expected_sig: ExpectedSig<'tcx>, ) -> ClosureSignatures<'tcx> { let expr_map_node = self.tcx.hir().get_if_local(expr_def_id).unwrap(); @@ -482,8 +482,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn check_supplied_sig_against_expectation( &self, expr_def_id: DefId, - decl: &hir::FnDecl, - body: &hir::Body, + decl: &hir::FnDecl<'tcx>, + body: &hir::Body<'tcx>, expected_sigs: &ClosureSignatures<'tcx>, ) -> InferResult<'tcx, ()> { // Get the signature S that the user gave. @@ -590,7 +590,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn supplied_sig_of_closure( &self, expr_def_id: DefId, - decl: &hir::FnDecl, + decl: &hir::FnDecl<'tcx>, ) -> ty::PolyFnSig<'tcx> { let astconv: &dyn AstConv<'_> = self; @@ -623,7 +623,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Converts the types that the user supplied, in case that doing /// so should yield an error, but returns back a signature where /// all parameters are of type `TyErr`. - fn error_sig_of_closure(&self, decl: &hir::FnDecl) -> ty::PolyFnSig<'tcx> { + fn error_sig_of_closure(&self, decl: &hir::FnDecl<'tcx>) -> ty::PolyFnSig<'tcx> { let astconv: &dyn AstConv<'_> = self; let supplied_arguments = decl.inputs.iter().map(|a| { diff --git a/src/librustc_typeck/check/coercion.rs b/src/librustc_typeck/check/coercion.rs index a56196ccf82f5..ffad3e60f7ba2 100644 --- a/src/librustc_typeck/check/coercion.rs +++ b/src/librustc_typeck/check/coercion.rs @@ -54,6 +54,7 @@ use crate::check::{FnCtxt, Needs}; use errors::DiagnosticBuilder; use rustc::hir; use rustc::hir::def_id::DefId; +use rustc::hir::ptr::P; use rustc::infer::{Coercion, InferResult, InferOk}; use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc::traits::{self, ObligationCause, ObligationCauseCode}; @@ -67,7 +68,6 @@ use rustc::ty::relate::RelateResult; use smallvec::{smallvec, SmallVec}; use std::ops::Deref; use syntax::feature_gate; -use syntax::ptr::P; use syntax::symbol::sym; use syntax_pos; @@ -838,10 +838,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { cause: &ObligationCause<'tcx>, exprs: &[E], prev_ty: Ty<'tcx>, - new: &hir::Expr, + new: &hir::Expr<'tcx>, new_ty: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> - where E: AsCoercionSite + where E: AsCoercionSite<'tcx> { let prev_ty = self.resolve_type_vars_with_obligations(prev_ty); let new_ty = self.resolve_type_vars_with_obligations(new_ty); @@ -1006,7 +1006,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// } /// let final_ty = coerce.complete(fcx); /// ``` -pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> { +pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite<'tcx>> { expected_ty: Ty<'tcx>, final_ty: Option>, expressions: Expressions<'tcx, 'exprs, E>, @@ -1015,14 +1015,14 @@ pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> { /// The type of a `CoerceMany` that is storing up the expressions into /// a buffer. We use this in `check/mod.rs` for things like `break`. -pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, P>; +pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, P<'tcx, hir::Expr<'tcx>>>; -enum Expressions<'tcx, 'exprs, E: AsCoercionSite> { - Dynamic(Vec<&'tcx hir::Expr>), +enum Expressions<'tcx, 'exprs, E: AsCoercionSite<'tcx>> { + Dynamic(Vec<&'tcx hir::Expr<'tcx>>), UpFront(&'exprs [E]), } -impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { +impl<'tcx, 'exprs, E: AsCoercionSite<'tcx>> CoerceMany<'tcx, 'exprs, E> { /// The usual case; collect the set of expressions dynamically. /// If the full set of coercion sites is known before hand, /// consider `with_coercion_sites()` instead to avoid allocation. @@ -1330,38 +1330,38 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { /// Something that can be converted into an expression to which we can /// apply a coercion. -pub trait AsCoercionSite { - fn as_coercion_site(&self) -> &hir::Expr; +pub trait AsCoercionSite<'tcx> { + fn as_coercion_site(&self) -> &hir::Expr<'tcx>; } -impl AsCoercionSite for hir::Expr { - fn as_coercion_site(&self) -> &hir::Expr { +impl<'tcx> AsCoercionSite<'tcx> for hir::Expr<'tcx> { + fn as_coercion_site(&self) -> &hir::Expr<'tcx> { self } } -impl AsCoercionSite for P { - fn as_coercion_site(&self) -> &hir::Expr { +impl<'tcx> AsCoercionSite<'tcx> for P<'tcx, hir::Expr<'tcx>> { + fn as_coercion_site(&self) -> &hir::Expr<'tcx> { self } } -impl<'a, T> AsCoercionSite for &'a T - where T: AsCoercionSite +impl<'tcx, 'a, T> AsCoercionSite<'tcx> for &'a T + where T: AsCoercionSite<'tcx> { - fn as_coercion_site(&self) -> &hir::Expr { + fn as_coercion_site(&self) -> &hir::Expr<'tcx> { (**self).as_coercion_site() } } -impl AsCoercionSite for ! { - fn as_coercion_site(&self) -> &hir::Expr { +impl<'tcx> AsCoercionSite<'tcx> for ! { + fn as_coercion_site(&self) -> &hir::Expr<'tcx> { unreachable!() } } -impl AsCoercionSite for hir::Arm { - fn as_coercion_site(&self) -> &hir::Expr { +impl<'tcx> AsCoercionSite<'tcx> for hir::Arm<'tcx> { + fn as_coercion_site(&self) -> &hir::Expr<'tcx> { &self.body } } diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index 5df0010b63eb2..f4636920d66e8 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -19,8 +19,8 @@ use std::ops::Deref; struct ConfirmContext<'a, 'tcx> { fcx: &'a FnCtxt<'a, 'tcx>, span: Span, - self_expr: &'tcx hir::Expr, - call_expr: &'tcx hir::Expr, + self_expr: &'tcx hir::Expr<'tcx>, + call_expr: &'tcx hir::Expr<'tcx>, } impl<'a, 'tcx> Deref for ConfirmContext<'a, 'tcx> { @@ -39,11 +39,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub fn confirm_method( &self, span: Span, - self_expr: &'tcx hir::Expr, - call_expr: &'tcx hir::Expr, + self_expr: &'tcx hir::Expr<'tcx>, + call_expr: &'tcx hir::Expr<'tcx>, unadjusted_self_ty: Ty<'tcx>, pick: probe::Pick<'tcx>, - segment: &hir::PathSegment, + segment: &hir::PathSegment<'tcx>, ) -> ConfirmResult<'tcx> { debug!( "confirm(unadjusted_self_ty={:?}, pick={:?}, generic_args={:?})", @@ -61,8 +61,8 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { fn new( fcx: &'a FnCtxt<'a, 'tcx>, span: Span, - self_expr: &'tcx hir::Expr, - call_expr: &'tcx hir::Expr, + self_expr: &'tcx hir::Expr<'tcx>, + call_expr: &'tcx hir::Expr<'tcx>, ) -> ConfirmContext<'a, 'tcx> { ConfirmContext { fcx, @@ -76,7 +76,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { &mut self, unadjusted_self_ty: Ty<'tcx>, pick: probe::Pick<'tcx>, - segment: &hir::PathSegment, + segment: &hir::PathSegment<'tcx>, ) -> ConfirmResult<'tcx> { // Adjust the self expression the user provided and obtain the adjusted type. let self_ty = self.adjust_self_ty(unadjusted_self_ty, &pick); @@ -297,7 +297,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { fn instantiate_method_substs( &mut self, pick: &probe::Pick<'tcx>, - seg: &hir::PathSegment, + seg: &hir::PathSegment<'tcx>, parent_substs: SubstsRef<'tcx>, ) -> SubstsRef<'tcx> { // Determine the values for the generic parameters of the method. diff --git a/src/librustc_typeck/check/method/mod.rs b/src/librustc_typeck/check/method/mod.rs index b492197870b75..91b185c3367dd 100644 --- a/src/librustc_typeck/check/method/mod.rs +++ b/src/librustc_typeck/check/method/mod.rs @@ -177,10 +177,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub fn lookup_method( &self, self_ty: Ty<'tcx>, - segment: &hir::PathSegment, + segment: &hir::PathSegment<'tcx>, span: Span, - call_expr: &'tcx hir::Expr, - self_expr: &'tcx hir::Expr, + call_expr: &'tcx hir::Expr<'tcx>, + self_expr: &'tcx hir::Expr<'tcx>, ) -> Result, MethodError<'tcx>> { debug!("lookup(method_name={}, self_ty={:?}, call_expr={:?}, self_expr={:?})", segment.ident, @@ -251,7 +251,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { span: Span, method_name: ast::Ident, self_ty: Ty<'tcx>, - call_expr: &'tcx hir::Expr, + call_expr: &'tcx hir::Expr<'tcx>, scope: ProbeScope, ) -> probe::PickResult<'tcx> { let mode = probe::Mode::MethodCall; diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs index 71bcf2bc05638..4a4e72065bee7 100644 --- a/src/librustc_typeck/check/method/suggest.rs +++ b/src/librustc_typeck/check/method/suggest.rs @@ -743,8 +743,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { #[derive(Copy, Clone)] pub enum SelfSource<'a> { - QPath(&'a hir::Ty), - MethodCall(&'a hir::Expr /* rcvr */), + QPath(&'a hir::Ty<'a>), + MethodCall(&'a hir::Expr<'a> /* rcvr */), } #[derive(Copy, Clone)] diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index c857eac5d3c18..4d42630c1460e 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -92,6 +92,7 @@ use rustc::hir::def::{CtorOf, CtorKind, Res, DefKind}; use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; use rustc::hir::itemlikevisit::ItemLikeVisitor; +use rustc::hir::ptr::P; use crate::middle::lang_items; use crate::namespace::Namespace; use rustc::infer::{self, InferCtxt, InferOk, InferResult}; @@ -121,7 +122,6 @@ use syntax_pos::hygiene::CompilerDesugaringKind; use syntax::ast; use syntax::attr; use syntax::feature_gate::{GateIssue, emit_feature_err}; -use syntax::ptr::P; use syntax::source_map::{DUMMY_SP, original_sp}; use syntax::symbol::{Symbol, LocalInternedString, kw, sym}; use syntax::util::lev_distance::find_best_match_for_name; @@ -759,7 +759,7 @@ fn adt_destructor<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option( tcx: TyCtxt<'tcx>, id: hir::HirId, -) -> Option<(hir::BodyId, Option<&'tcx hir::FnDecl>)> { +) -> Option<(hir::BodyId, Option<&'tcx hir::FnDecl<'tcx>>)> { match tcx.hir().get_by_hir_id(id) { Node::Item(item) => { match item.node { @@ -2471,13 +2471,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .register_bound(self, self.param_env, ty, def_id, cause); } - pub fn to_ty(&self, ast_t: &hir::Ty) -> Ty<'tcx> { + pub fn to_ty(&self, ast_t: &hir::Ty<'tcx>) -> Ty<'tcx> { let t = AstConv::ast_ty_to_ty(self, ast_t); self.register_wf_obligation(t, ast_t.span, traits::MiscObligation); t } - pub fn to_ty_saving_user_provided_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> { + pub fn to_ty_saving_user_provided_ty(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { let ty = self.to_ty(ast_ty); debug!("to_ty_saving_user_provided_ty: ty={:?}", ty); @@ -3344,10 +3344,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Checks a method call. fn check_method_call( &self, - expr: &'tcx hir::Expr, - segment: &hir::PathSegment, + expr: &'tcx hir::Expr<'tcx>, + segment: &hir::PathSegment<'tcx>, span: Span, - args: &'tcx [hir::Expr], + args: &'tcx [hir::Expr<'tcx>], expected: Expectation<'tcx>, needs: Needs, ) -> Ty<'tcx> { @@ -3794,8 +3794,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn check_struct_fields_on_error( &self, - fields: &'tcx [hir::Field], - base_expr: &'tcx Option>, + fields: &'tcx [hir::Field<'tcx>], + base_expr: &'tcx Option>>, ) { for field in fields { self.check_expr(&field.expr); @@ -3806,7 +3806,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } pub fn check_struct_path(&self, - qpath: &QPath, + qpath: &QPath<'tcx>, hir_id: hir::HirId) -> Option<(&'tcx ty::VariantDef, Ty<'tcx>)> { let path_span = match *qpath { @@ -3863,14 +3863,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - fn check_expr_struct( - &self, - expr: &hir::Expr, - expected: Expectation<'tcx>, - qpath: &QPath, - fields: &'tcx [hir::Field], - base_expr: &'tcx Option>, - ) -> Ty<'tcx> { + fn check_expr_struct(&self, + expr: &hir::Expr<'tcx>, + expected: Expectation<'tcx>, + qpath: &QPath<'tcx>, + fields: &'tcx [hir::Field<'tcx>], + base_expr: &'tcx Option>>) -> Ty<'tcx> + { // Find the relevant variant let (variant, adt_ty) = if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id) { @@ -4702,7 +4701,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary. // The newly resolved definition is written into `type_dependent_defs`. fn finish_resolving_struct_path(&self, - qpath: &QPath, + qpath: &QPath<'tcx>, path_span: Span, hir_id: hir::HirId) -> (Res, Ty<'tcx>) @@ -4744,10 +4743,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Resolves associated value path into a base type and associated constant or method /// resolution. The newly resolved definition is written into `type_dependent_defs`. pub fn resolve_ty_and_res_ufcs<'b>(&self, - qpath: &'b QPath, + qpath: &'b QPath<'tcx>, hir_id: hir::HirId, span: Span) - -> (Res, Option>, &'b [hir::PathSegment]) + -> (Res, Option>, &'b [hir::PathSegment<'tcx>]) { debug!("resolve_ty_and_res_ufcs: qpath={:?} hir_id={:?} span={:?}", qpath, hir_id, span); let (ty, qself, item_segment) = match *qpath { @@ -5039,13 +5038,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } /// Given a function block's `HirId`, returns its `FnDecl` if it exists, or `None` otherwise. - fn get_parent_fn_decl(&self, blk_id: hir::HirId) -> Option<(hir::FnDecl, ast::Ident)> { + fn get_parent_fn_decl(&self, blk_id: hir::HirId) -> Option<(hir::FnDecl<'tcx>, ast::Ident)> { let parent = self.tcx.hir().get_by_hir_id(self.tcx.hir().get_parent_item(blk_id)); self.get_node_fn_decl(parent).map(|(fn_decl, ident, _)| (fn_decl, ident)) } /// Given a function `Node`, return its `FnDecl` if it exists, or `None` otherwise. - fn get_node_fn_decl(&self, node: Node<'_>) -> Option<(hir::FnDecl, ast::Ident, bool)> { + fn get_node_fn_decl<'hir>( + &self, + node: Node<'hir> + ) -> Option<(hir::FnDecl<'hir>, ast::Ident, bool)> { match node { Node::Item(&hir::Item { ident, node: hir::ItemKind::Fn(ref decl, ..), .. @@ -5071,7 +5073,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Given a `HirId`, return the `FnDecl` of the method it is enclosed by and whether a /// suggestion can be made, `None` otherwise. - pub fn get_fn_decl(&self, blk_id: hir::HirId) -> Option<(hir::FnDecl, bool)> { + pub fn get_fn_decl(&self, blk_id: hir::HirId) -> Option<(hir::FnDecl<'tcx>, bool)> { // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or // `while` before reaching it, as block tail returns are not available in them. self.tcx.hir().get_return_block(blk_id).and_then(|blk_id| { @@ -5088,7 +5090,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub fn suggest_mismatched_types_on_tail( &self, err: &mut DiagnosticBuilder<'tcx>, - expression: &'tcx hir::Expr, + expression: &'tcx hir::Expr<'tcx>, expected: Ty<'tcx>, found: Ty<'tcx>, cause_span: Span, @@ -5212,7 +5214,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn suggest_missing_return_type( &self, err: &mut DiagnosticBuilder<'tcx>, - fn_decl: &hir::FnDecl, + fn_decl: &hir::FnDecl<'tcx>, expected: Ty<'tcx>, found: Ty<'tcx>, can_suggest: bool, @@ -5349,7 +5351,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Instantiates the given path, which must refer to an item with the given // number of type parameters and type. pub fn instantiate_value_path(&self, - segments: &[hir::PathSegment], + segments: &[hir::PathSegment<'tcx>], self_ty: Option>, res: Res, span: Span, diff --git a/src/librustc_typeck/check/regionck.rs b/src/librustc_typeck/check/regionck.rs index bf3381d206b5a..77a1fc844875b 100644 --- a/src/librustc_typeck/check/regionck.rs +++ b/src/librustc_typeck/check/regionck.rs @@ -282,7 +282,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { } /// Try to resolve the type for the given node. - pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr) -> Ty<'tcx> { + pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr<'tcx>) -> Ty<'tcx> { let ty = self.tables.borrow().expr_ty_adjusted(expr); self.resolve_type(ty) } @@ -453,7 +453,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> { fn visit_fn( &mut self, fk: intravisit::FnKind<'tcx>, - _: &'tcx hir::FnDecl, + _: &'tcx hir::FnDecl<'tcx>, body_id: hir::BodyId, span: Span, hir_id: hir::HirId, @@ -486,7 +486,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> { //visit_pat: visit_pat, // (..) see above - fn visit_arm(&mut self, arm: &'tcx hir::Arm) { + fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) { // see above for p in &arm.pats { self.constrain_bindings_in_pat(p); @@ -494,14 +494,14 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> { intravisit::walk_arm(self, arm); } - fn visit_local(&mut self, l: &'tcx hir::Local) { + fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { // see above self.constrain_bindings_in_pat(&l.pat); self.link_local(l); intravisit::walk_local(self, l); } - fn visit_expr(&mut self, expr: &'tcx hir::Expr) { + fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { debug!( "regionck::visit_expr(e={:?}, repeating_scope={:?})", expr, self.repeating_scope @@ -585,21 +585,21 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> { hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => { if is_method_call { - self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter()); + self.constrain_call(expr, Some(&lhs), Some(&***rhs).into_iter()); } intravisit::walk_expr(self, expr); } hir::ExprKind::Index(ref lhs, ref rhs) if is_method_call => { - self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter()); + self.constrain_call(expr, Some(&lhs), Some(&***rhs).into_iter()); intravisit::walk_expr(self, expr); } hir::ExprKind::Binary(_, ref lhs, ref rhs) if is_method_call => { // As `ExprKind::MethodCall`, but the call is via an overloaded op. - self.constrain_call(expr, Some(&lhs), Some(&**rhs).into_iter()); + self.constrain_call(expr, Some(&lhs), Some(&***rhs).into_iter()); intravisit::walk_expr(self, expr); } @@ -618,7 +618,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> { hir::ExprKind::Unary(hir::UnDeref, ref base) => { // For *a, the lifetime of a must enclose the deref if is_method_call { - self.constrain_call(expr, Some(base), None::.iter()); + self.constrain_call(expr, Some(base), None::>.iter()); } // For overloaded derefs, base_ty is the input to `Deref::deref`, // but it's a reference type uing the same region as the output. @@ -632,7 +632,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> { hir::ExprKind::Unary(_, ref lhs) if is_method_call => { // As above. - self.constrain_call(expr, Some(&lhs), None::.iter()); + self.constrain_call(expr, Some(&lhs), None::>.iter()); intravisit::walk_expr(self, expr); } @@ -718,7 +718,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> { } impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { - fn constrain_cast(&mut self, cast_expr: &hir::Expr, source_expr: &hir::Expr) { + fn constrain_cast(&mut self, cast_expr: &hir::Expr<'tcx>, source_expr: &hir::Expr<'tcx>) { debug!( "constrain_cast(cast_expr={:?}, source_expr={:?})", cast_expr, source_expr @@ -730,7 +730,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { self.walk_cast(cast_expr, source_ty, target_ty); } - fn walk_cast(&mut self, cast_expr: &hir::Expr, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) { + fn walk_cast(&mut self, cast_expr: &hir::Expr<'tcx>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) { debug!("walk_cast(from_ty={:?}, to_ty={:?})", from_ty, to_ty); match (&from_ty.sty, &to_ty.sty) { /*From:*/ @@ -758,13 +758,13 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { } } - fn check_expr_fn_block(&mut self, expr: &'tcx hir::Expr, body_id: hir::BodyId) { + fn check_expr_fn_block(&mut self, expr: &'tcx hir::Expr<'tcx>, body_id: hir::BodyId) { let repeating_scope = self.set_repeating_scope(body_id.hir_id); intravisit::walk_expr(self, expr); self.set_repeating_scope(repeating_scope); } - fn constrain_callee(&mut self, callee_expr: &hir::Expr) { + fn constrain_callee(&mut self, callee_expr: &hir::Expr<'tcx>) { let callee_ty = self.resolve_node_type(callee_expr.hir_id); match callee_ty.sty { ty::FnDef(..) | ty::FnPtr(_) => {} @@ -780,12 +780,15 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { } } - fn constrain_call<'b, I: Iterator>( + fn constrain_call<'b, I: Iterator>>( &mut self, - call_expr: &hir::Expr, - receiver: Option<&hir::Expr>, + call_expr: &hir::Expr<'tcx>, + receiver: Option<&hir::Expr<'tcx>>, arg_exprs: I, - ) { + ) + where + 'tcx: 'b + { //! Invoked on every call site (i.e., normal calls, method calls, //! and overloaded operators). Constrains the regions which appear //! in the type of the function. Also constrains the regions that @@ -842,7 +845,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { /// Invoked on any adjustments that occur. Checks that if this is a region pointer being /// dereferenced, the lifetime of the pointer includes the deref expr. - fn constrain_adjustments(&mut self, expr: &hir::Expr) -> mc::McResult> { + fn constrain_adjustments(&mut self, expr: &hir::Expr<'tcx>) -> mc::McResult> { debug!("constrain_adjustments(expr={:?})", expr); let mut cmt = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?; @@ -967,7 +970,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { /// Invoked on any index expression that occurs. Checks that if this is a slice /// being indexed, the lifetime of the pointer includes the deref expr. - fn constrain_index(&mut self, index_expr: &hir::Expr, indexed_ty: Ty<'tcx>) { + fn constrain_index(&mut self, index_expr: &hir::Expr<'tcx>, indexed_ty: Ty<'tcx>) { debug!( "constrain_index(index_expr=?, indexed_ty={}", self.ty_to_string(indexed_ty) @@ -1045,7 +1048,12 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the /// resulting pointer is linked to the lifetime of its guarantor (if any). - fn link_addr_of(&mut self, expr: &hir::Expr, mutability: hir::Mutability, base: &hir::Expr) { + fn link_addr_of( + &mut self, + expr: &hir::Expr<'tcx>, + mutability: hir::Mutability, + base: &hir::Expr<'tcx> + ) { debug!("link_addr_of(expr={:?}, base={:?})", expr, base); let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base))); @@ -1073,7 +1081,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { /// Computes the guarantors for any ref bindings in a match and /// then ensures that the lifetime of the resulting pointer is /// linked to the lifetime of its guarantor (if any). - fn link_match(&self, discr: &hir::Expr, arms: &[hir::Arm]) { + fn link_match(&self, discr: &hir::Expr<'tcx>, arms: &[hir::Arm<'tcx>]) { debug!("regionck::for_match()"); let discr_cmt = Rc::new(ignore_err!(self.with_mc(|mc| mc.cat_expr(discr)))); debug!("discr_cmt={:?}", discr_cmt); @@ -1134,7 +1142,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { /// autoref'd. fn link_autoref( &self, - expr: &hir::Expr, + expr: &hir::Expr<'tcx>, expr_cmt: &mc::cmt_<'tcx>, autoref: &adjustment::AutoBorrow<'tcx>, ) { diff --git a/src/librustc_typeck/check/upvar.rs b/src/librustc_typeck/check/upvar.rs index bba108aa282a9..de8054f5ca9dc 100644 --- a/src/librustc_typeck/check/upvar.rs +++ b/src/librustc_typeck/check/upvar.rs @@ -80,7 +80,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, closure_hir_id: hir::HirId, span: Span, - body: &hir::Body, + body: &hir::Body<'tcx>, capture_clause: hir::CaptureClause, ) { /*! diff --git a/src/librustc_typeck/check/writeback.rs b/src/librustc_typeck/check/writeback.rs index 5be822897407b..c69e9d0ca3b29 100644 --- a/src/librustc_typeck/check/writeback.rs +++ b/src/librustc_typeck/check/writeback.rs @@ -102,7 +102,7 @@ struct WritebackCx<'cx, 'tcx: 'cx> { tables: ty::TypeckTables<'tcx>, - body: &'tcx hir::Body, + body: &'tcx hir::Body<'tcx>, rustc_dump_user_substs: bool, } @@ -792,7 +792,7 @@ struct Resolver<'cx, 'tcx: 'cx> { tcx: TyCtxt<'tcx>, infcx: &'cx InferCtxt<'cx, 'tcx>, span: &'cx dyn Locatable, - body: &'tcx hir::Body, + body: &'tcx hir::Body<'tcx>, } impl<'cx, 'tcx> Resolver<'cx, 'tcx> { diff --git a/src/librustc_typeck/check_unused.rs b/src/librustc_typeck/check_unused.rs index c724500b9ede8..3b50b52a7456c 100644 --- a/src/librustc_typeck/check_unused.rs +++ b/src/librustc_typeck/check_unused.rs @@ -154,7 +154,8 @@ fn unused_crates_lint<'tcx>(tcx: TyCtxt<'tcx>) { // If the extern crate isn't in the extern prelude, // there is no way it can be written as an `use`. let orig_name = extern_crate.orig_name.unwrap_or(item.ident.name); - if !tcx.extern_prelude.get(&orig_name).map_or(false, |from_item| !from_item) { + if !tcx.lowered_hir() + .extern_prelude.get(&orig_name).map_or(false, |from_item| !from_item) { continue; } diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index d4b2c200297d2..49cd5b21af831 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -165,7 +165,7 @@ impl ItemCtxt<'tcx> { ItemCtxt { tcx, item_def_id } } - pub fn to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> { + pub fn to_ty(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { AstConv::ast_ty_to_ty(self, ast_ty) } } @@ -338,7 +338,7 @@ impl ItemCtxt<'tcx> { /// bounds for a type parameter `X` if `X::Foo` is used. fn type_parameter_bounds_in_generics( &self, - ast_generics: &hir::Generics, + ast_generics: &hir::Generics<'tcx>, param_id: hir::HirId, ty: Ty<'tcx>, only_self_bounds: OnlySelfBounds, @@ -1344,11 +1344,11 @@ pub fn checked_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, fail: bool) -> Op node: ExprKind::Path(QPath::Resolved(_, ref path)), .. }) => { - Some(&**path) + Some(&***path) } Node::Expr(&hir::Expr { node: ExprKind::Struct(ref path, ..), .. }) => { if let QPath::Resolved(_, ref path) = **path { - Some(&**path) + Some(&***path) } else { None } @@ -1788,8 +1788,8 @@ fn impl_polarity<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> hir::ImplPolarity { /// `resolve_lifetime::early_bound_lifetimes`. fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>( tcx: TyCtxt<'tcx>, - generics: &'a hir::Generics, -) -> impl Iterator + Captures<'tcx> { + generics: &'a hir::Generics<'tcx>, +) -> impl Iterator> + Captures<'tcx> { generics .params .iter() @@ -2205,7 +2205,7 @@ fn explicit_predicates_of<'tcx>( fn predicates_from_bound<'tcx>( astconv: &dyn AstConv<'tcx>, param_ty: Ty<'tcx>, - bound: &hir::GenericBound, + bound: &hir::GenericBound<'tcx>, ) -> Vec<(ty::Predicate<'tcx>, Span)> { match *bound { hir::GenericBound::Trait(ref tr, hir::TraitBoundModifier::None) => { @@ -2227,7 +2227,7 @@ fn predicates_from_bound<'tcx>( fn compute_sig_of_foreign_fn_decl<'tcx>( tcx: TyCtxt<'tcx>, def_id: DefId, - decl: &hir::FnDecl, + decl: &hir::FnDecl<'tcx>, abi: abi::Abi, ) -> ty::PolyFnSig<'tcx> { let unsafety = if abi == abi::Abi::RustIntrinsic { diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index 79674e4baeba0..fe05101306388 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -71,7 +71,7 @@ This API is completely unstable and subject to change. #![recursion_limit="256"] -#![deny(rust_2018_idioms)] +//#![deny(rust_2018_idioms)] #![deny(internal)] #![deny(unused_lifetimes)] #![allow(explicit_outlives_requirements)] @@ -376,7 +376,7 @@ pub fn check_crate<'tcx>(tcx: TyCtxt<'tcx>) -> Result<(), ErrorReported> { /// A quasi-deprecated helper used in rustdoc and clippy to get /// the type from a HIR node. -pub fn hir_ty_to_ty<'tcx>(tcx: TyCtxt<'tcx>, hir_ty: &hir::Ty) -> Ty<'tcx> { +pub fn hir_ty_to_ty<'tcx>(tcx: TyCtxt<'tcx>, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { // In case there are any projections, etc., find the "environment" // def-ID that will be used to determine the traits/predicates in // scope. This is derived from the enclosing item-like thing. @@ -389,7 +389,7 @@ pub fn hir_ty_to_ty<'tcx>(tcx: TyCtxt<'tcx>, hir_ty: &hir::Ty) -> Ty<'tcx> { pub fn hir_trait_to_predicates<'tcx>( tcx: TyCtxt<'tcx>, - hir_trait: &hir::TraitRef, + hir_trait: &hir::TraitRef<'tcx>, ) -> (ty::PolyTraitRef<'tcx>, Bounds<'tcx>) { // In case there are any projections, etc., find the "environment" // def-ID that will be used to determine the traits/predicates in diff --git a/src/librustc_typeck/namespace.rs b/src/librustc_typeck/namespace.rs index 9b6c5bd9f429f..04de12d72c04c 100644 --- a/src/librustc_typeck/namespace.rs +++ b/src/librustc_typeck/namespace.rs @@ -19,7 +19,7 @@ impl From for Namespace { } } -impl<'a> From <&'a hir::ImplItemKind> for Namespace { +impl<'a> From <&'a hir::ImplItemKind<'a>> for Namespace { fn from(impl_kind: &'a hir::ImplItemKind) -> Self { match *impl_kind { hir::ImplItemKind::Existential(..) | diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 5a5540e7e3855..8f1e8370e8ab4 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -451,7 +451,7 @@ fn build_macro(cx: &DocContext<'_>, did: DefId, name: ast::Name) -> clean::ItemE let imported_from = cx.tcx.original_crate_name(did.krate); match cx.cstore.load_macro_untracked(did, cx.sess()) { LoadedMacro::MacroDef(def) => { - let matchers: hir::HirVec = if let ast::ItemKind::MacroDef(ref def) = def.node { + let matchers: Vec = if let ast::ItemKind::MacroDef(ref def) = def.node { let tts: Vec<_> = def.stream().into_trees().collect(); tts.chunks(4).map(|arm| arm[0].span()).collect() } else { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 43cb3dd7261c8..50c8344b620f3 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -19,6 +19,7 @@ use rustc::middle::stability; use rustc::mir::interpret::{GlobalId, ConstValue}; use rustc::hir::{self, HirVec}; use rustc::hir::def::{self, Res, DefKind, CtorKind}; +use rustc::hir::ptr::P; use rustc::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc::ty::subst::{InternalSubsts, SubstsRef, UnpackedKind}; use rustc::ty::{self, DefIdTree, TyCtxt, Region, RegionVid, Ty, AdtKind}; @@ -29,7 +30,6 @@ use syntax::ast::{self, AttrStyle, Ident}; use syntax::attr; use syntax::ext::base::MacroKind; use syntax::source_map::{dummy_spanned, Spanned}; -use syntax::ptr::P; use syntax::symbol::{Symbol, kw, sym}; use syntax::symbol::InternedString; use syntax_pos::{self, Pos, FileName}; @@ -78,48 +78,48 @@ fn get_deprecation(cx: &DocContext<'_>, def_id: DefId) -> Option { cx.tcx.lookup_deprecation(def_id).clean(cx) } -pub trait Clean { - fn clean(&self, cx: &DocContext<'_>) -> T; +pub trait Clean<'tcx, T> { + fn clean(&self, cx: &DocContext<'tcx>) -> T; } -impl, U> Clean> for [T] { - fn clean(&self, cx: &DocContext<'_>) -> Vec { +impl<'tcx, T: Clean<'tcx, U>, U> Clean<'tcx, Vec> for [T] { + fn clean(&self, cx: &DocContext<'tcx>) -> Vec { self.iter().map(|x| x.clean(cx)).collect() } } -impl, U, V: Idx> Clean> for IndexVec { - fn clean(&self, cx: &DocContext<'_>) -> IndexVec { +impl<'tcx, T: Clean<'tcx, U>, U, V: Idx> Clean<'tcx, IndexVec> for IndexVec { + fn clean(&self, cx: &DocContext<'tcx>) -> IndexVec { self.iter().map(|x| x.clean(cx)).collect() } } -impl, U> Clean for P { - fn clean(&self, cx: &DocContext<'_>) -> U { +impl<'tcx, T: Clean<'tcx, U>, U> Clean<'tcx, U> for P<'_, T> { + fn clean(&self, cx: &DocContext<'tcx>) -> U { (**self).clean(cx) } } -impl, U> Clean for Rc { - fn clean(&self, cx: &DocContext<'_>) -> U { +impl<'tcx, T: Clean<'tcx, U>, U> Clean<'tcx, U> for Rc { + fn clean(&self, cx: &DocContext<'tcx>) -> U { (**self).clean(cx) } } -impl, U> Clean> for Option { - fn clean(&self, cx: &DocContext<'_>) -> Option { +impl<'tcx, T: Clean<'tcx, U>, U> Clean<'tcx, Option> for Option { + fn clean(&self, cx: &DocContext<'tcx>) -> Option { self.as_ref().map(|v| v.clean(cx)) } } -impl Clean for ty::Binder where T: Clean { - fn clean(&self, cx: &DocContext<'_>) -> U { +impl<'tcx, T, U> Clean<'tcx, U> for ty::Binder where T: Clean<'tcx, U> { + fn clean(&self, cx: &DocContext<'tcx>) -> U { self.skip_binder().clean(cx) } } -impl, U> Clean> for P<[T]> { - fn clean(&self, cx: &DocContext<'_>) -> Vec { +impl<'tcx, T: Clean<'tcx, U>, U> Clean<'tcx, Vec> for P<'_, [T]> { + fn clean(&self, cx: &DocContext<'tcx>) -> Vec { self.iter().map(|x| x.clean(cx)).collect() } } @@ -138,8 +138,8 @@ pub struct Crate { pub masked_crates: FxHashSet, } -impl<'a, 'tcx> Clean for visit_ast::RustdocVisitor<'a, 'tcx> { - fn clean(&self, cx: &DocContext<'_>) -> Crate { +impl<'a, 'tcx> Clean<'tcx, Crate> for visit_ast::RustdocVisitor<'a, 'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Crate { use crate::visit_lib::LibEmbargoVisitor; { @@ -232,8 +232,8 @@ pub struct ExternalCrate { pub keywords: Vec<(DefId, String, Attributes)>, } -impl Clean for CrateNum { - fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate { +impl<'tcx> Clean<'tcx, ExternalCrate> for CrateNum { + fn clean(&self, cx: &DocContext<'tcx>) -> ExternalCrate { let root = DefId { krate: *self, index: CRATE_DEF_INDEX }; let krate_span = cx.tcx.def_span(root); let krate_src = cx.sess().source_map().span_to_filename(krate_span); @@ -600,8 +600,8 @@ pub struct Module { pub is_crate: bool, } -impl Clean for doctree::Module { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for doctree::Module<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { let name = if self.name.is_some() { self.name.expect("No name provided").clean(cx) } else { @@ -1042,8 +1042,8 @@ impl AttributesExt for Attributes { } } -impl Clean for [ast::Attribute] { - fn clean(&self, cx: &DocContext<'_>) -> Attributes { +impl<'tcx> Clean<'tcx, Attributes> for [ast::Attribute] { + fn clean(&self, cx: &DocContext<'tcx>) -> Attributes { Attributes::from_ast(cx.sess().diagnostic(), self) } } @@ -1098,8 +1098,8 @@ impl GenericBound { } } -impl Clean for hir::GenericBound { - fn clean(&self, cx: &DocContext<'_>) -> GenericBound { +impl<'tcx> Clean<'tcx, GenericBound> for hir::GenericBound<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> GenericBound { match *self { hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)), hir::GenericBound::Trait(ref t, modifier) => { @@ -1169,8 +1169,8 @@ fn external_path(cx: &DocContext<'_>, name: &str, trait_did: Option, has_ } } -impl<'a, 'tcx> Clean for (&'a ty::TraitRef<'tcx>, Vec) { - fn clean(&self, cx: &DocContext<'_>) -> GenericBound { +impl<'a, 'tcx> Clean<'tcx, GenericBound> for (&'a ty::TraitRef<'_>, Vec) { + fn clean(&self, cx: &DocContext<'tcx>) -> GenericBound { let (trait_ref, ref bounds) = *self; inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait); let path = external_path(cx, &cx.tcx.item_name(trait_ref.def_id).as_str(), @@ -1213,14 +1213,14 @@ impl<'a, 'tcx> Clean for (&'a ty::TraitRef<'tcx>, Vec } } -impl<'tcx> Clean for ty::TraitRef<'tcx> { - fn clean(&self, cx: &DocContext<'_>) -> GenericBound { +impl<'tcx> Clean<'tcx, GenericBound> for ty::TraitRef<'_> { + fn clean(&self, cx: &DocContext<'tcx>) -> GenericBound { (self, vec![]).clean(cx) } } -impl<'tcx> Clean>> for InternalSubsts<'tcx> { - fn clean(&self, cx: &DocContext<'_>) -> Option> { +impl<'tcx> Clean<'tcx, Option>> for InternalSubsts<'_> { + fn clean(&self, cx: &DocContext<'tcx>) -> Option> { let mut v = Vec::new(); v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives)); v.extend(self.types().map(|t| GenericBound::TraitBound(PolyTrait { @@ -1246,8 +1246,8 @@ impl Lifetime { } } -impl Clean for hir::Lifetime { - fn clean(&self, cx: &DocContext<'_>) -> Lifetime { +impl<'tcx> Clean<'tcx, Lifetime> for hir::Lifetime { + fn clean(&self, cx: &DocContext<'tcx>) -> Lifetime { if self.hir_id != hir::DUMMY_HIR_ID { let def = cx.tcx.named_region(self.hir_id); match def { @@ -1265,7 +1265,7 @@ impl Clean for hir::Lifetime { } } -impl Clean for hir::GenericParam { +impl<'tcx> Clean<'tcx, Lifetime> for hir::GenericParam<'_> { fn clean(&self, _: &DocContext<'_>) -> Lifetime { match self.kind { hir::GenericParamKind::Lifetime { .. } => { @@ -1289,7 +1289,7 @@ impl Clean for hir::GenericParam { } } -impl Clean for hir::ConstArg { +impl<'tcx> Clean<'tcx, Constant> for hir::ConstArg { fn clean(&self, cx: &DocContext<'_>) -> Constant { Constant { type_: cx.tcx.type_of(cx.tcx.hir().body_owner_def_id(self.value.body)).clean(cx), @@ -1298,14 +1298,14 @@ impl Clean for hir::ConstArg { } } -impl Clean for ty::GenericParamDef { +impl<'tcx> Clean<'tcx, Lifetime> for ty::GenericParamDef { fn clean(&self, _cx: &DocContext<'_>) -> Lifetime { Lifetime(self.name.to_string()) } } -impl Clean> for ty::RegionKind { - fn clean(&self, cx: &DocContext<'_>) -> Option { +impl<'tcx> Clean<'tcx, Option> for ty::RegionKind { + fn clean(&self, cx: &DocContext<'tcx>) -> Option { match *self { ty::ReStatic => Some(Lifetime::statik()), ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())), @@ -1343,8 +1343,8 @@ impl WherePredicate { } } -impl Clean for hir::WherePredicate { - fn clean(&self, cx: &DocContext<'_>) -> WherePredicate { +impl<'tcx> Clean<'tcx, WherePredicate> for hir::WherePredicate<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> WherePredicate { match *self { hir::WherePredicate::BoundPredicate(ref wbp) => { WherePredicate::BoundPredicate { @@ -1370,8 +1370,8 @@ impl Clean for hir::WherePredicate { } } -impl<'a> Clean> for ty::Predicate<'a> { - fn clean(&self, cx: &DocContext<'_>) -> Option { +impl<'tcx> Clean<'tcx, Option> for ty::Predicate<'_> { + fn clean(&self, cx: &DocContext<'tcx>) -> Option { use rustc::ty::Predicate; match *self { @@ -1389,8 +1389,8 @@ impl<'a> Clean> for ty::Predicate<'a> { } } -impl<'a> Clean for ty::TraitPredicate<'a> { - fn clean(&self, cx: &DocContext<'_>) -> WherePredicate { +impl<'tcx> Clean<'tcx, WherePredicate> for ty::TraitPredicate<'_> { + fn clean(&self, cx: &DocContext<'tcx>) -> WherePredicate { WherePredicate::BoundPredicate { ty: self.trait_ref.self_ty().clean(cx), bounds: vec![self.trait_ref.clean(cx)] @@ -1398,17 +1398,17 @@ impl<'a> Clean for ty::TraitPredicate<'a> { } } -impl<'tcx> Clean for ty::SubtypePredicate<'tcx> { +impl<'tcx> Clean<'tcx, WherePredicate> for ty::SubtypePredicate<'_> { fn clean(&self, _cx: &DocContext<'_>) -> WherePredicate { panic!("subtype predicates are an internal rustc artifact \ and should not be seen by rustdoc") } } -impl<'tcx> Clean> for - ty::OutlivesPredicate,ty::Region<'tcx>> { +impl<'tcx> Clean<'tcx, Option> for + ty::OutlivesPredicate,ty::Region<'_>> { - fn clean(&self, cx: &DocContext<'_>) -> Option { + fn clean(&self, cx: &DocContext<'tcx>) -> Option { let ty::OutlivesPredicate(ref a, ref b) = *self; match (a, b) { @@ -1425,8 +1425,8 @@ impl<'tcx> Clean> for } } -impl<'tcx> Clean> for ty::OutlivesPredicate, ty::Region<'tcx>> { - fn clean(&self, cx: &DocContext<'_>) -> Option { +impl<'tcx> Clean<'tcx, Option> for ty::OutlivesPredicate, ty::Region<'_>> { + fn clean(&self, cx: &DocContext<'tcx>) -> Option { let ty::OutlivesPredicate(ref ty, ref lt) = *self; match lt { @@ -1441,8 +1441,8 @@ impl<'tcx> Clean> for ty::OutlivesPredicate, ty: } } -impl<'tcx> Clean for ty::ProjectionPredicate<'tcx> { - fn clean(&self, cx: &DocContext<'_>) -> WherePredicate { +impl<'tcx> Clean<'tcx, WherePredicate> for ty::ProjectionPredicate<'_> { + fn clean(&self, cx: &DocContext<'tcx>) -> WherePredicate { WherePredicate::EqPredicate { lhs: self.projection_ty.clean(cx), rhs: self.ty.clean(cx) @@ -1450,8 +1450,8 @@ impl<'tcx> Clean for ty::ProjectionPredicate<'tcx> { } } -impl<'tcx> Clean for ty::ProjectionTy<'tcx> { - fn clean(&self, cx: &DocContext<'_>) -> Type { +impl<'tcx> Clean<'tcx, Type> for ty::ProjectionTy<'_> { + fn clean(&self, cx: &DocContext<'tcx>) -> Type { let trait_ = match self.trait_ref(cx.tcx).clean(cx) { GenericBound::TraitBound(t, _) => t.trait_, GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"), @@ -1530,8 +1530,8 @@ impl GenericParamDef { } } -impl Clean for ty::GenericParamDef { - fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef { +impl<'tcx> Clean<'tcx, GenericParamDef> for ty::GenericParamDef { + fn clean(&self, cx: &DocContext<'tcx>) -> GenericParamDef { let (name, kind) = match self.kind { ty::GenericParamDefKind::Lifetime => { (self.name.to_string(), GenericParamDefKind::Lifetime) @@ -1566,8 +1566,8 @@ impl Clean for ty::GenericParamDef { } } -impl Clean for hir::GenericParam { - fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef { +impl<'tcx> Clean<'tcx, GenericParamDef> for hir::GenericParam<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> GenericParamDef { let (name, kind) = match self.kind { hir::GenericParamKind::Lifetime { .. } => { let name = if self.bounds.len() > 0 { @@ -1616,8 +1616,8 @@ pub struct Generics { pub where_predicates: Vec, } -impl Clean for hir::Generics { - fn clean(&self, cx: &DocContext<'_>) -> Generics { +impl<'tcx> Clean<'tcx, Generics> for hir::Generics<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Generics { // Synthetic type-parameters are inserted after normal ones. // In order for normal parameters to be able to refer to synthetic ones, // scans them first. @@ -1685,9 +1685,9 @@ impl Clean for hir::Generics { } } -impl<'a, 'tcx> Clean for (&'a ty::Generics, +impl<'a, 'tcx> Clean<'tcx, Generics> for (&'a ty::Generics, &'a &'tcx ty::GenericPredicates<'tcx>) { - fn clean(&self, cx: &DocContext<'_>) -> Generics { + fn clean(&self, cx: &DocContext<'tcx>) -> Generics { use self::WherePredicate as WP; let (gens, preds) = *self; @@ -1884,11 +1884,13 @@ pub struct Method { pub ret_types: Vec, } -impl<'a> Clean for (&'a hir::MethodSig, &'a hir::Generics, hir::BodyId, - Option) { - fn clean(&self, cx: &DocContext<'_>) -> Method { +impl<'tcx, 'a> Clean<'tcx, Method> for (&'a hir::MethodSig<'tcx>, + &'a hir::Generics<'tcx>, + hir::BodyId, + Option) { + fn clean(&self, cx: &DocContext<'tcx>) -> Method { let (generics, decl) = enter_impl_trait(cx, || { - (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)) + (self.1.clean(cx), (&**self.0.decl, self.2).clean(cx)) }); let (all_types, ret_types) = get_all_types(&generics, &decl, cx); Method { @@ -1920,8 +1922,8 @@ pub struct Function { pub ret_types: Vec, } -impl Clean for doctree::Function { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for doctree::Function<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { let (generics, decl) = enter_impl_trait(cx, || { (self.generics.clean(cx), (&self.decl, self.body).clean(cx)) }); @@ -1994,8 +1996,8 @@ pub struct Arguments { pub values: Vec, } -impl<'a> Clean for (&'a [hir::Ty], &'a [ast::Ident]) { - fn clean(&self, cx: &DocContext<'_>) -> Arguments { +impl<'tcx, 'a> Clean<'tcx, Arguments> for (&'a [hir::Ty<'tcx>], &'a [ast::Ident]) { + fn clean(&self, cx: &DocContext<'tcx>) -> Arguments { Arguments { values: self.0.iter().enumerate().map(|(i, ty)| { let mut name = self.1.get(i).map(|ident| ident.to_string()) @@ -2012,8 +2014,8 @@ impl<'a> Clean for (&'a [hir::Ty], &'a [ast::Ident]) { } } -impl<'a> Clean for (&'a [hir::Ty], hir::BodyId) { - fn clean(&self, cx: &DocContext<'_>) -> Arguments { +impl<'tcx, 'a> Clean<'tcx, Arguments> for (&'a [hir::Ty<'tcx>], hir::BodyId) { + fn clean(&self, cx: &DocContext<'tcx>) -> Arguments { let body = cx.tcx.hir().body(self.1); Arguments { @@ -2027,10 +2029,10 @@ impl<'a> Clean for (&'a [hir::Ty], hir::BodyId) { } } -impl<'a, A: Copy> Clean for (&'a hir::FnDecl, A) - where (&'a [hir::Ty], A): Clean +impl<'tcx, 'a, A: Copy> Clean<'tcx, FnDecl> for (&'a hir::FnDecl<'tcx>, A) + where (&'a [hir::Ty<'tcx>], A): Clean<'tcx, Arguments> { - fn clean(&self, cx: &DocContext<'_>) -> FnDecl { + fn clean(&self, cx: &DocContext<'tcx>) -> FnDecl { FnDecl { inputs: (&self.0.inputs[..], self.1).clean(cx), output: self.0.output.clean(cx), @@ -2039,8 +2041,8 @@ impl<'a, A: Copy> Clean for (&'a hir::FnDecl, A) } } -impl<'tcx> Clean for (DefId, ty::PolyFnSig<'tcx>) { - fn clean(&self, cx: &DocContext<'_>) -> FnDecl { +impl<'tcx> Clean<'tcx, FnDecl> for (DefId, ty::PolyFnSig<'tcx>) { + fn clean(&self, cx: &DocContext<'tcx>) -> FnDecl { let (did, sig) = *self; let mut names = if cx.tcx.hir().as_local_hir_id(did).is_some() { vec![].into_iter() @@ -2099,8 +2101,8 @@ pub enum FunctionRetTy { DefaultReturn, } -impl Clean for hir::FunctionRetTy { - fn clean(&self, cx: &DocContext<'_>) -> FunctionRetTy { +impl<'tcx> Clean<'tcx, FunctionRetTy> for hir::FunctionRetTy<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> FunctionRetTy { match *self { hir::Return(ref typ) => Return(typ.clean(cx)), hir::DefaultReturn(..) => DefaultReturn, @@ -2128,8 +2130,8 @@ pub struct Trait { pub is_auto: bool, } -impl Clean for doctree::Trait { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for doctree::Trait<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { let attrs = self.attrs.clean(cx); let is_spotlight = attrs.has_doc_flag(sym::spotlight); Item { @@ -2159,8 +2161,8 @@ pub struct TraitAlias { pub bounds: Vec, } -impl Clean for doctree::TraitAlias { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for doctree::TraitAlias<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { let attrs = self.attrs.clean(cx); Item { name: Some(self.name.clean(cx)), @@ -2178,7 +2180,7 @@ impl Clean for doctree::TraitAlias { } } -impl Clean for hir::IsAuto { +impl<'tcx> Clean<'tcx, bool> for hir::IsAuto { fn clean(&self, _: &DocContext<'_>) -> bool { match *self { hir::IsAuto::Yes => true, @@ -2187,14 +2189,14 @@ impl Clean for hir::IsAuto { } } -impl Clean for hir::TraitRef { - fn clean(&self, cx: &DocContext<'_>) -> Type { +impl<'tcx> Clean<'tcx, Type> for hir::TraitRef<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Type { resolve_type(cx, self.path.clean(cx), self.hir_ref_id) } } -impl Clean for hir::PolyTraitRef { - fn clean(&self, cx: &DocContext<'_>) -> PolyTrait { +impl<'tcx> Clean<'tcx, PolyTrait> for hir::PolyTraitRef<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> PolyTrait { PolyTrait { trait_: self.trait_ref.clean(cx), generic_params: self.bound_generic_params.clean(cx) @@ -2202,8 +2204,8 @@ impl Clean for hir::PolyTraitRef { } } -impl Clean for hir::TraitItem { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for hir::TraitItem<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { let inner = match self.node { hir::TraitItemKind::Const(ref ty, default) => { AssocConstItem(ty.clean(cx), @@ -2214,7 +2216,7 @@ impl Clean for hir::TraitItem { } hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref names)) => { let (generics, decl) = enter_impl_trait(cx, || { - (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx)) + (self.generics.clean(cx), (&**sig.decl, &names[..]).clean(cx)) }); let (all_types, ret_types) = get_all_types(&generics, &decl, cx); TyMethodItem(TyMethod { @@ -2243,8 +2245,8 @@ impl Clean for hir::TraitItem { } } -impl Clean for hir::ImplItem { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for hir::ImplItem<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { let inner = match self.node { hir::ImplItemKind::Const(ref ty, expr) => { AssocConstItem(ty.clean(cx), @@ -2276,8 +2278,8 @@ impl Clean for hir::ImplItem { } } -impl Clean for ty::AssocItem { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for ty::AssocItem { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { let inner = match self.kind { ty::AssocKind::Const => { let ty = cx.tcx.type_of(self.def_id); @@ -2741,8 +2743,8 @@ impl From for PrimitiveType { } } -impl Clean for hir::Ty { - fn clean(&self, cx: &DocContext<'_>) -> Type { +impl<'tcx> Clean<'tcx, Type> for hir::Ty<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Type { use rustc::hir::*; match self.node { @@ -2898,7 +2900,7 @@ impl Clean for hir::Ty { DefKind::Trait, cx.tcx.associated_item(p.res.def_id()).container.id(), ), - segments: segments.into(), + segments: P::from_slice(&cx.tcx.arena, &segments), }; Type::QPath { name: p.segments.last().expect("segments were empty").ident.name.clean(cx), @@ -2915,7 +2917,7 @@ impl Clean for hir::Ty { let trait_path = hir::Path { span: self.span, res, - segments: vec![].into(), + segments: hir::HirVec::new(), }; Type::QPath { name: segment.ident.name.clean(cx), @@ -2946,8 +2948,8 @@ impl Clean for hir::Ty { } } -impl<'tcx> Clean for Ty<'tcx> { - fn clean(&self, cx: &DocContext<'_>) -> Type { +impl<'tcx> Clean<'tcx, Type> for Ty<'_> { + fn clean(&self, cx: &DocContext<'tcx>) -> Type { debug!("cleaning type: {:?}", self); match self.sty { ty::Never => Never, @@ -3148,8 +3150,8 @@ impl<'tcx> Clean for Ty<'tcx> { } } -impl<'tcx> Clean for ty::Const<'tcx> { - fn clean(&self, cx: &DocContext<'_>) -> Constant { +impl<'tcx> Clean<'tcx, Constant> for ty::Const<'_> { + fn clean(&self, cx: &DocContext<'tcx>) -> Constant { Constant { type_: self.ty.clean(cx), expr: format!("{}", self), @@ -3157,8 +3159,8 @@ impl<'tcx> Clean for ty::Const<'tcx> { } } -impl Clean for hir::StructField { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for hir::StructField<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { let local_did = cx.tcx.hir().local_def_id_from_hir_id(self.hir_id); Item { @@ -3174,8 +3176,8 @@ impl Clean for hir::StructField { } } -impl Clean for ty::FieldDef { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for ty::FieldDef { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { Item { name: Some(self.ident.name).clean(cx), attrs: cx.tcx.get_attrs(self.did).clean(cx), @@ -3197,8 +3199,8 @@ pub enum Visibility { Restricted(DefId, Path), } -impl Clean> for hir::Visibility { - fn clean(&self, cx: &DocContext<'_>) -> Option { +impl<'tcx> Clean<'tcx, Option> for hir::Visibility<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Option { Some(match self.node { hir::VisibilityKind::Public => Visibility::Public, hir::VisibilityKind::Inherited => Visibility::Inherited, @@ -3212,7 +3214,7 @@ impl Clean> for hir::Visibility { } } -impl Clean> for ty::Visibility { +impl<'tcx> Clean<'tcx, Option> for ty::Visibility { fn clean(&self, _: &DocContext<'_>) -> Option { Some(if *self == ty::Visibility::Public { Public } else { Inherited }) } @@ -3234,8 +3236,8 @@ pub struct Union { pub fields_stripped: bool, } -impl Clean for doctree::Struct { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for doctree::Struct<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), @@ -3254,8 +3256,8 @@ impl Clean for doctree::Struct { } } -impl Clean for doctree::Union { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for doctree::Union<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), @@ -3284,8 +3286,8 @@ pub struct VariantStruct { pub fields_stripped: bool, } -impl Clean for ::rustc::hir::VariantData { - fn clean(&self, cx: &DocContext<'_>) -> VariantStruct { +impl<'tcx> Clean<'tcx, VariantStruct> for ::rustc::hir::VariantData<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> VariantStruct { VariantStruct { struct_type: doctree::struct_type_from_def(self), fields: self.fields().iter().map(|x| x.clean(cx)).collect(), @@ -3301,8 +3303,8 @@ pub struct Enum { pub variants_stripped: bool, } -impl Clean for doctree::Enum { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for doctree::Enum<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), @@ -3325,8 +3327,8 @@ pub struct Variant { pub kind: VariantKind, } -impl Clean for doctree::Variant { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for doctree::Variant<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), @@ -3342,8 +3344,8 @@ impl Clean for doctree::Variant { } } -impl Clean for ty::VariantDef { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for ty::VariantDef { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { let kind = match self.ctor_kind { CtorKind::Const => VariantKind::CLike, CtorKind::Fn => { @@ -3390,8 +3392,8 @@ pub enum VariantKind { Struct(VariantStruct), } -impl Clean for hir::VariantData { - fn clean(&self, cx: &DocContext<'_>) -> VariantKind { +impl<'tcx> Clean<'tcx, VariantKind> for hir::VariantData<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> VariantKind { match self { hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)), hir::VariantData::Tuple(..) => @@ -3426,8 +3428,8 @@ impl Span { } } -impl Clean for syntax_pos::Span { - fn clean(&self, cx: &DocContext<'_>) -> Span { +impl<'tcx> Clean<'tcx, Span> for syntax_pos::Span { + fn clean(&self, cx: &DocContext<'tcx>) -> Span { if self.is_dummy() { return Span::empty(); } @@ -3460,8 +3462,8 @@ impl Path { } } -impl Clean for hir::Path { - fn clean(&self, cx: &DocContext<'_>) -> Path { +impl<'tcx> Clean<'tcx, Path> for hir::Path<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Path { Path { global: self.is_global(), res: self.res, @@ -3499,8 +3501,8 @@ pub enum GenericArgs { } } -impl Clean for hir::GenericArgs { - fn clean(&self, cx: &DocContext<'_>) -> GenericArgs { +impl<'tcx> Clean<'tcx, GenericArgs> for hir::GenericArgs<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> GenericArgs { if self.parenthesized { let output = self.bindings[0].ty().clean(cx); GenericArgs::Parenthesized { @@ -3533,8 +3535,8 @@ pub struct PathSegment { pub args: GenericArgs, } -impl Clean for hir::PathSegment { - fn clean(&self, cx: &DocContext<'_>) -> PathSegment { +impl<'tcx> Clean<'tcx, PathSegment> for hir::PathSegment<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> PathSegment { PathSegment { name: self.ident.name.clean(cx), args: self.with_generic_args(|generic_args| generic_args.clean(cx)) @@ -3603,21 +3605,21 @@ fn qpath_to_string(p: &hir::QPath) -> String { s } -impl Clean for Ident { +impl<'tcx> Clean<'tcx, String> for Ident { #[inline] fn clean(&self, cx: &DocContext<'_>) -> String { self.name.clean(cx) } } -impl Clean for ast::Name { +impl<'tcx> Clean<'tcx, String> for ast::Name { #[inline] fn clean(&self, _: &DocContext<'_>) -> String { self.to_string() } } -impl Clean for InternedString { +impl<'tcx> Clean<'tcx, String> for InternedString { #[inline] fn clean(&self, _: &DocContext<'_>) -> String { self.to_string() @@ -3630,8 +3632,8 @@ pub struct Typedef { pub generics: Generics, } -impl Clean for doctree::Typedef { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for doctree::Typedef<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), @@ -3654,8 +3656,8 @@ pub struct Existential { pub generics: Generics, } -impl Clean for doctree::Existential { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for doctree::Existential<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), @@ -3680,10 +3682,10 @@ pub struct BareFunctionDecl { pub abi: Abi, } -impl Clean for hir::BareFnTy { - fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl { +impl<'tcx> Clean<'tcx, BareFunctionDecl> for hir::BareFnTy<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> BareFunctionDecl { let (generic_params, decl) = enter_impl_trait(cx, || { - (self.generic_params.clean(cx), (&*self.decl, &self.arg_names[..]).clean(cx)) + (self.generic_params.clean(cx), (&**self.decl, &self.arg_names[..]).clean(cx)) }); BareFunctionDecl { unsafety: self.unsafety, @@ -3704,8 +3706,8 @@ pub struct Static { pub expr: String, } -impl Clean for doctree::Static { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for doctree::Static<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { debug!("cleaning static {}: {:?}", self.name.clean(cx), self); Item { name: Some(self.name.clean(cx)), @@ -3730,8 +3732,8 @@ pub struct Constant { pub expr: String, } -impl Clean for doctree::Constant { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for doctree::Constant<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), @@ -3754,7 +3756,7 @@ pub enum Mutability { Immutable, } -impl Clean for hir::Mutability { +impl<'tcx> Clean<'tcx, Mutability> for hir::Mutability { fn clean(&self, _: &DocContext<'_>) -> Mutability { match self { &hir::MutMutable => Mutable, @@ -3769,7 +3771,7 @@ pub enum ImplPolarity { Negative, } -impl Clean for hir::ImplPolarity { +impl<'tcx> Clean<'tcx, ImplPolarity> for hir::ImplPolarity { fn clean(&self, _: &DocContext<'_>) -> ImplPolarity { match self { &hir::ImplPolarity::Positive => ImplPolarity::Positive, @@ -3800,8 +3802,8 @@ pub fn get_auto_trait_and_blanket_impls( .chain(BlanketImplFinder::new(cx).get_blanket_impls(ty, param_env_def_id)) } -impl Clean> for doctree::Impl { - fn clean(&self, cx: &DocContext<'_>) -> Vec { +impl<'tcx> Clean<'tcx, Vec> for doctree::Impl<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Vec { let mut ret = Vec::new(); let trait_ = self.trait_.clean(cx); let items = self.items.clean(cx); @@ -3901,8 +3903,8 @@ fn build_deref_target_impls(cx: &DocContext<'_>, } } -impl Clean> for doctree::ExternCrate { - fn clean(&self, cx: &DocContext<'_>) -> Vec { +impl<'tcx> Clean<'tcx, Vec> for doctree::ExternCrate<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Vec { let please_inline = self.vis.node.is_pub() && self.attrs.iter().any(|a| { a.check_name(sym::doc) && match a.meta_item_list() { @@ -3940,8 +3942,8 @@ impl Clean> for doctree::ExternCrate { } } -impl Clean> for doctree::Import { - fn clean(&self, cx: &DocContext<'_>) -> Vec { +impl<'tcx> Clean<'tcx, Vec> for doctree::Import<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Vec { // We consider inlining the documentation of `pub use` statements, but we // forcefully don't inline if this is not public or if the // #[doc(no_inline)] attribute is present. @@ -4016,8 +4018,8 @@ pub struct ImportSource { pub did: Option, } -impl Clean> for hir::ForeignMod { - fn clean(&self, cx: &DocContext<'_>) -> Vec { +impl<'tcx> Clean<'tcx, Vec> for hir::ForeignMod<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Vec { let mut items = self.items.clean(cx); for item in &mut items { if let ForeignFunctionItem(ref mut f) = item.inner { @@ -4028,12 +4030,12 @@ impl Clean> for hir::ForeignMod { } } -impl Clean for hir::ForeignItem { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for hir::ForeignItem<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { let inner = match self.node { hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => { let (generics, decl) = enter_impl_trait(cx, || { - (generics.clean(cx), (&**decl, &names[..]).clean(cx)) + (generics.clean(cx), (&***decl, &names[..]).clean(cx)) }); let (all_types, ret_types) = get_all_types(&generics, &decl, cx); ForeignFunctionItem(Function { @@ -4245,8 +4247,8 @@ pub struct Macro { pub imported_from: Option, } -impl Clean for doctree::Macro { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for doctree::Macro<'_> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { let name = self.name.clean(cx); Item { name: Some(name.clone()), @@ -4274,8 +4276,8 @@ pub struct ProcMacro { pub helpers: Vec, } -impl Clean for doctree::ProcMacro { - fn clean(&self, cx: &DocContext<'_>) -> Item { +impl<'tcx> Clean<'tcx, Item> for doctree::ProcMacro<'_> { + fn clean(&self, cx: &DocContext<'tcx>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), @@ -4308,7 +4310,7 @@ pub struct Deprecation { pub note: Option, } -impl Clean for attr::Stability { +impl<'tcx> Clean<'tcx, Stability> for attr::Stability { fn clean(&self, _: &DocContext<'_>) -> Stability { Stability { level: stability::StabilityLevel::from_attr_level(&self.level), @@ -4335,13 +4337,13 @@ impl Clean for attr::Stability { } } -impl<'a> Clean for &'a attr::Stability { +impl<'tcx, 'a> Clean<'tcx, Stability> for &'a attr::Stability { fn clean(&self, dc: &DocContext<'_>) -> Stability { (**self).clean(dc) } } -impl Clean for attr::Deprecation { +impl<'tcx> Clean<'tcx, Deprecation> for attr::Deprecation { fn clean(&self, _: &DocContext<'_>) -> Deprecation { Deprecation { since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()), @@ -4377,8 +4379,8 @@ impl TypeBinding { } } -impl Clean for hir::TypeBinding { - fn clean(&self, cx: &DocContext<'_>) -> TypeBinding { +impl<'tcx> Clean<'tcx, TypeBinding> for hir::TypeBinding<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> TypeBinding { TypeBinding { name: self.ident.name.clean(cx), kind: self.kind.clean(cx), @@ -4386,8 +4388,8 @@ impl Clean for hir::TypeBinding { } } -impl Clean for hir::TypeBindingKind { - fn clean(&self, cx: &DocContext<'_>) -> TypeBindingKind { +impl<'tcx> Clean<'tcx, TypeBindingKind> for hir::TypeBindingKind<'tcx> { + fn clean(&self, cx: &DocContext<'tcx>) -> TypeBindingKind { match *self { hir::TypeBindingKind::Equality { ref ty } => TypeBindingKind::Equality { diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 985bb02614b61..1c06d80c9ed1b 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -25,9 +25,8 @@ use parking_lot::ReentrantMutex; use std::cell::RefCell; use std::mem; -use rustc_data_structures::sync::{self, Lrc}; +use rustc_data_structures::sync::{self, Lrc, Lock}; use std::sync::Arc; -use std::rc::Rc; use crate::visit_ast::RustdocVisitor; use crate::config::{Options as RustdocOptions, RenderOptions}; @@ -45,7 +44,7 @@ pub type ExternalPaths = FxHashMap, clean::TypeKind)>; pub struct DocContext<'tcx> { pub tcx: TyCtxt<'tcx>, - pub resolver: Rc>>, + pub resolver: Lrc>>, /// The stack of module NodeIds up till this point pub crate_name: Option, pub cstore: Lrc, diff --git a/src/librustdoc/doctree.rs b/src/librustdoc/doctree.rs index 7a528e50e9c3f..2767b452ee1f6 100644 --- a/src/librustdoc/doctree.rs +++ b/src/librustdoc/doctree.rs @@ -6,44 +6,44 @@ use syntax::ast; use syntax::ast::{Name, NodeId}; use syntax::attr; use syntax::ext::base::MacroKind; -use syntax::ptr::P; use syntax::source_map::Spanned; use syntax_pos::{self, Span}; use rustc::hir; use rustc::hir::def_id::CrateNum; +use rustc::hir::ptr::P; -pub struct Module { +pub struct Module<'a> { pub name: Option, - pub attrs: hir::HirVec, + pub attrs: hir::HirVec<'a, ast::Attribute>, pub where_outer: Span, pub where_inner: Span, - pub extern_crates: Vec, - pub imports: Vec, - pub structs: Vec, - pub unions: Vec, - pub enums: Vec, - pub fns: Vec, - pub mods: Vec, + pub extern_crates: Vec>, + pub imports: Vec>, + pub structs: Vec>, + pub unions: Vec>, + pub enums: Vec>, + pub fns: Vec>, + pub mods: Vec>, pub id: NodeId, - pub typedefs: Vec, - pub existentials: Vec, - pub statics: Vec, - pub constants: Vec, - pub traits: Vec, - pub vis: hir::Visibility, + pub typedefs: Vec>, + pub existentials: Vec>, + pub statics: Vec>, + pub constants: Vec>, + pub traits: Vec>, + pub vis: hir::Visibility<'a>, pub stab: Option, pub depr: Option, - pub impls: Vec, - pub foreigns: Vec, - pub macros: Vec, - pub proc_macros: Vec, - pub trait_aliases: Vec, + pub impls: Vec>, + pub foreigns: Vec>, + pub macros: Vec>, + pub proc_macros: Vec>, + pub trait_aliases: Vec>, pub is_crate: bool, } -impl Module { - pub fn new(name: Option) -> Module { +impl Module<'_> { + pub fn new(name: Option) -> Self { Module { name : name, id: ast::CRATE_NODE_ID, @@ -85,156 +85,156 @@ pub enum StructType { Unit, } -pub struct Struct { - pub vis: hir::Visibility, +pub struct Struct<'a> { + pub vis: hir::Visibility<'a>, pub stab: Option, pub depr: Option, pub id: hir::HirId, pub struct_type: StructType, pub name: Name, - pub generics: hir::Generics, - pub attrs: hir::HirVec, - pub fields: hir::HirVec, + pub generics: hir::Generics<'a>, + pub attrs: hir::HirVec<'a, ast::Attribute>, + pub fields: Vec>, pub whence: Span, } -pub struct Union { - pub vis: hir::Visibility, +pub struct Union<'a> { + pub vis: hir::Visibility<'a>, pub stab: Option, pub depr: Option, pub id: hir::HirId, pub struct_type: StructType, pub name: Name, - pub generics: hir::Generics, - pub attrs: hir::HirVec, - pub fields: hir::HirVec, + pub generics: hir::Generics<'a>, + pub attrs: hir::HirVec<'a, ast::Attribute>, + pub fields: Vec>, pub whence: Span, } -pub struct Enum { - pub vis: hir::Visibility, +pub struct Enum<'a> { + pub vis: hir::Visibility<'a>, pub stab: Option, pub depr: Option, - pub variants: hir::HirVec, - pub generics: hir::Generics, - pub attrs: hir::HirVec, + pub variants: Vec>, + pub generics: hir::Generics<'a>, + pub attrs: hir::HirVec<'a, ast::Attribute>, pub id: hir::HirId, pub whence: Span, pub name: Name, } -pub struct Variant { +pub struct Variant<'a> { pub name: Name, pub id: hir::HirId, - pub attrs: hir::HirVec, - pub def: hir::VariantData, + pub attrs: hir::HirVec<'a, ast::Attribute>, + pub def: hir::VariantData<'a>, pub stab: Option, pub depr: Option, pub whence: Span, } -pub struct Function { - pub decl: hir::FnDecl, - pub attrs: hir::HirVec, +pub struct Function<'a> { + pub decl: hir::FnDecl<'a>, + pub attrs: hir::HirVec<'a, ast::Attribute>, pub id: hir::HirId, pub name: Name, - pub vis: hir::Visibility, + pub vis: hir::Visibility<'a>, pub stab: Option, pub depr: Option, pub header: hir::FnHeader, pub whence: Span, - pub generics: hir::Generics, + pub generics: hir::Generics<'a>, pub body: hir::BodyId, } -pub struct Typedef { - pub ty: P, - pub gen: hir::Generics, +pub struct Typedef<'a> { + pub ty: P<'a, hir::Ty<'a>>, + pub gen: hir::Generics<'a>, pub name: Name, pub id: hir::HirId, - pub attrs: hir::HirVec, + pub attrs: hir::HirVec<'a, ast::Attribute>, pub whence: Span, - pub vis: hir::Visibility, + pub vis: hir::Visibility<'a>, pub stab: Option, pub depr: Option, } -pub struct Existential { - pub exist_ty: hir::ExistTy, +pub struct Existential<'a> { + pub exist_ty: hir::ExistTy<'a>, pub name: Name, pub id: hir::HirId, - pub attrs: hir::HirVec, + pub attrs: hir::HirVec<'a, ast::Attribute>, pub whence: Span, - pub vis: hir::Visibility, + pub vis: hir::Visibility<'a>, pub stab: Option, pub depr: Option, } #[derive(Debug)] -pub struct Static { - pub type_: P, +pub struct Static<'a> { + pub type_: P<'a, hir::Ty<'a>>, pub mutability: hir::Mutability, pub expr: hir::BodyId, pub name: Name, - pub attrs: hir::HirVec, - pub vis: hir::Visibility, + pub attrs: hir::HirVec<'a, ast::Attribute>, + pub vis: hir::Visibility<'a>, pub stab: Option, pub depr: Option, pub id: hir::HirId, pub whence: Span, } -pub struct Constant { - pub type_: P, +pub struct Constant<'a> { + pub type_: P<'a, hir::Ty<'a>>, pub expr: hir::BodyId, pub name: Name, - pub attrs: hir::HirVec, - pub vis: hir::Visibility, + pub attrs: hir::HirVec<'a, ast::Attribute>, + pub vis: hir::Visibility<'a>, pub stab: Option, pub depr: Option, pub id: hir::HirId, pub whence: Span, } -pub struct Trait { +pub struct Trait<'a> { pub is_auto: hir::IsAuto, pub unsafety: hir::Unsafety, pub name: Name, - pub items: hir::HirVec, - pub generics: hir::Generics, - pub bounds: hir::HirVec, - pub attrs: hir::HirVec, + pub items: Vec>, + pub generics: hir::Generics<'a>, + pub bounds: Vec>, + pub attrs: hir::HirVec<'a, ast::Attribute>, pub id: hir::HirId, pub whence: Span, - pub vis: hir::Visibility, + pub vis: hir::Visibility<'a>, pub stab: Option, pub depr: Option, } -pub struct TraitAlias { +pub struct TraitAlias<'a> { pub name: Name, - pub generics: hir::Generics, - pub bounds: hir::HirVec, - pub attrs: hir::HirVec, + pub generics: hir::Generics<'a>, + pub bounds: Vec>, + pub attrs: hir::HirVec<'a, ast::Attribute>, pub id: hir::HirId, pub whence: Span, - pub vis: hir::Visibility, + pub vis: hir::Visibility<'a>, pub stab: Option, pub depr: Option, } #[derive(Debug)] -pub struct Impl { +pub struct Impl<'a> { pub unsafety: hir::Unsafety, pub polarity: hir::ImplPolarity, pub defaultness: hir::Defaultness, - pub generics: hir::Generics, - pub trait_: Option, - pub for_: P, - pub items: hir::HirVec, - pub attrs: hir::HirVec, + pub generics: hir::Generics<'a>, + pub trait_: Option>, + pub for_: P<'a, hir::Ty<'a>>, + pub items: Vec>, + pub attrs: hir::HirVec<'a, ast::Attribute>, pub whence: Span, - pub vis: hir::Visibility, + pub vis: hir::Visibility<'a>, pub stab: Option, pub depr: Option, pub id: hir::HirId, @@ -242,42 +242,42 @@ pub struct Impl { // For Macro we store the DefId instead of the NodeId, since we also create // these imported macro_rules (which only have a DUMMY_NODE_ID). -pub struct Macro { +pub struct Macro<'a> { pub name: Name, pub def_id: hir::def_id::DefId, - pub attrs: hir::HirVec, + pub attrs: hir::HirVec<'a, ast::Attribute>, pub whence: Span, - pub matchers: hir::HirVec, + pub matchers: Vec, pub stab: Option, pub depr: Option, pub imported_from: Option, } -pub struct ExternCrate { +pub struct ExternCrate<'a> { pub name: Name, pub cnum: CrateNum, pub path: Option, - pub vis: hir::Visibility, - pub attrs: hir::HirVec, + pub vis: hir::Visibility<'a>, + pub attrs: hir::HirVec<'a, ast::Attribute>, pub whence: Span, } -pub struct Import { +pub struct Import<'a> { pub name: Name, pub id: hir::HirId, - pub vis: hir::Visibility, - pub attrs: hir::HirVec, - pub path: hir::Path, + pub vis: hir::Visibility<'a>, + pub attrs: hir::HirVec<'a, ast::Attribute>, + pub path: hir::Path<'a>, pub glob: bool, pub whence: Span, } -pub struct ProcMacro { +pub struct ProcMacro<'a> { pub name: Name, pub id: hir::HirId, pub kind: MacroKind, pub helpers: Vec, - pub attrs: hir::HirVec, + pub attrs: hir::HirVec<'a, ast::Attribute>, pub whence: Span, pub stab: Option, pub depr: Option, diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 3b4d65352a34c..28b4bf7d61005 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -1,4 +1,4 @@ -#![deny(rust_2018_idioms)] +//#![deny(rust_2018_idioms)] #![deny(internal)] #![deny(unused_lifetimes)] @@ -24,6 +24,7 @@ #![recursion_limit="256"] +extern crate arena; extern crate getopts; extern crate env_logger; extern crate rustc; diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 7fbfc3e1fc0f4..ca6b7b6f757ce 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -65,11 +65,17 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { if let Some(id) = parent_id.or(self.mod_ids.last().cloned()) { // FIXME: `with_scope` requires the `NodeId` of a module. let node_id = cx.tcx.hir().hir_to_node_id(id); - let result = cx.enter_resolver(|resolver| { - resolver.with_scope(node_id, |resolver| { - resolver.resolve_str_path_error(DUMMY_SP, &path_str, ns == ValueNS) + let result = cx.enter_resolver(|resolver| resolver.with_scope( + node_id, + |resolver| { + resolver.resolve_str_path_error( + &cx.tcx.arena, + DUMMY_SP, + &path_str, + ns == ValueNS, + ) }) - }); + ); if let Ok(result) = result { // In case this is a trait item, skip the @@ -130,7 +136,12 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { // FIXME: `with_scope` requires the `NodeId` of a module. let node_id = cx.tcx.hir().hir_to_node_id(id); let ty = cx.enter_resolver(|resolver| resolver.with_scope(node_id, |resolver| { - resolver.resolve_str_path_error(DUMMY_SP, &path, false) + resolver.resolve_str_path_error( + &cx.tcx.arena, + DUMMY_SP, + &path, + false + ) }))?; match ty.res { Res::Def(DefKind::Struct, did) diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 5bce5d6ba5de1..e6aca70426e6d 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -78,28 +78,29 @@ pub fn run(options: Options) -> i32 { let display_warnings = options.display_warnings; let tests = interface::run_compiler(config, |compiler| -> Result<_, ErrorReported> { - let lower_to_hir = compiler.lower_to_hir()?; - - let mut opts = scrape_test_config(lower_to_hir.peek().0.borrow().krate()); - opts.display_warnings |= options.display_warnings; - let mut collector = Collector::new( - compiler.crate_name()?.peek().to_string(), - options.cfgs, - options.libs, - options.codegen_options, - options.externs, - false, - opts, - options.maybe_sysroot, - Some(compiler.source_map().clone()), - None, - options.linker, - options.edition, - options.persist_doctests, - ); - let mut global_ctxt = compiler.global_ctxt()?.take(); + global_ctxt.enter(|tcx| { + let lower_to_hir = tcx.lower_ast_to_hir(())?; + + let mut opts = scrape_test_config(lower_to_hir.forest.krate()); + opts.display_warnings |= options.display_warnings; + let mut collector = Collector::new( + compiler.crate_name()?.peek().to_string(), + options.cfgs, + options.libs, + options.codegen_options, + options.externs, + false, + opts, + options.maybe_sysroot, + Some(compiler.source_map().clone()), + None, + options.linker, + options.edition, + options.persist_doctests, + ); + let krate = tcx.hir().krate(); let mut hir_collector = HirCollector { sess: compiler.session(), @@ -111,9 +112,8 @@ pub fn run(options: Options) -> i32 { hir_collector.visit_testable("".to_string(), &krate.attrs, |this| { intravisit::walk_crate(this, krate); }); - }); - - Ok(collector.tests) + Ok(collector.tests) + }) }).expect("compiler aborted in rustdoc!"); test_args.insert(0, "rustdoctest".to_string()); diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index eb9de43e38861..e2015228e4eed 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -4,6 +4,7 @@ use rustc::hir::{self, Node}; use rustc::hir::def::{Res, DefKind}; use rustc::hir::def_id::{DefId, LOCAL_CRATE}; +use rustc::hir::ptr::{P, IteratorExt}; use rustc::middle::privacy::AccessLevel; use rustc::util::nodemap::{FxHashSet, FxHashMap}; use syntax::ast; @@ -29,8 +30,8 @@ use crate::doctree::*; // framework from syntax?. pub struct RustdocVisitor<'a, 'tcx> { - pub module: Module, - pub attrs: hir::HirVec, + pub module: Module<'tcx>, + pub attrs: hir::HirVec<'tcx, ast::Attribute>, pub cx: &'a core::DocContext<'tcx>, view_item_stack: FxHashSet, inlining: bool, @@ -77,7 +78,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { .and_then(|def_id| self.cx.tcx.lookup_deprecation(def_id)) } - pub fn visit(&mut self, krate: &hir::Crate) { + pub fn visit(&mut self, krate: &hir::Crate<'tcx>) { self.attrs = krate.attrs.clone(); self.module = self.visit_mod_contents(krate.span, @@ -96,9 +97,9 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { self.cx.renderinfo.borrow_mut().exact_paths = self.exact_paths.take().unwrap(); } - pub fn visit_variant_data(&mut self, item: &hir::Item, - name: ast::Name, sd: &hir::VariantData, - generics: &hir::Generics) -> Struct { + pub fn visit_variant_data(&mut self, item: &hir::Item<'tcx>, + name: ast::Name, sd: &hir::VariantData<'tcx>, + generics: &hir::Generics<'tcx>) -> Struct<'tcx> { debug!("Visiting struct"); let struct_type = struct_type_from_def(&*sd); Struct { @@ -115,9 +116,9 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { } } - pub fn visit_union_data(&mut self, item: &hir::Item, - name: ast::Name, sd: &hir::VariantData, - generics: &hir::Generics) -> Union { + pub fn visit_union_data(&mut self, item: &hir::Item<'tcx>, + name: ast::Name, sd: &hir::VariantData<'tcx>, + generics: &hir::Generics<'tcx>) -> Union<'tcx> { debug!("Visiting union"); let struct_type = struct_type_from_def(&*sd); Union { @@ -134,9 +135,9 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { } } - pub fn visit_enum_def(&mut self, it: &hir::Item, - name: ast::Name, def: &hir::EnumDef, - params: &hir::Generics) -> Enum { + pub fn visit_enum_def(&mut self, it: &hir::Item<'tcx>, + name: ast::Name, def: &hir::EnumDef<'tcx>, + params: &hir::Generics<'tcx>) -> Enum<'tcx> { debug!("Visiting enum"); Enum { name, @@ -159,10 +160,10 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { } } - pub fn visit_fn(&mut self, om: &mut Module, item: &hir::Item, - name: ast::Name, fd: &hir::FnDecl, + pub fn visit_fn(&mut self, om: &mut Module<'tcx>, item: &hir::Item<'tcx>, + name: ast::Name, fd: &hir::FnDecl<'tcx>, header: hir::FnHeader, - gen: &hir::Generics, + gen: &hir::Generics<'tcx>, body: hir::BodyId) { debug!("Visiting fn"); let macro_kind = item.attrs.iter().filter_map(|a| { @@ -232,10 +233,10 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { } } - pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec, - vis: hir::Visibility, id: hir::HirId, - m: &hir::Mod, - name: Option) -> Module { + pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<'tcx, ast::Attribute>, + vis: hir::Visibility<'tcx>, id: hir::HirId, + m: &hir::Mod<'tcx>, + name: Option) -> Module<'tcx> { let mut om = Module::new(name); om.where_outer = span; om.where_inner = m.inner; @@ -269,7 +270,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { res: Res, renamed: Option, glob: bool, - om: &mut Module, + om: &mut Module<'tcx>, please_inline: bool) -> bool { fn inherits_doc_hidden(cx: &core::DocContext<'_>, mut node: hir::HirId) -> bool { @@ -362,10 +363,10 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { // Generate a fresh `extern {}` block if we want to inline a foreign item. om.foreigns.push(hir::ForeignMod { abi: tcx.hir().get_foreign_abi_by_hir_id(it.hir_id), - items: vec![hir::ForeignItem { + items: P::from_slice(&tcx.arena, &[hir::ForeignItem { ident: renamed.unwrap_or(it.ident), .. it.clone() - }].into(), + }]), }); true } @@ -379,8 +380,8 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { ret } - pub fn visit_item(&mut self, item: &hir::Item, - renamed: Option, om: &mut Module) { + pub fn visit_item(&mut self, item: &hir::Item<'tcx>, + renamed: Option, om: &mut Module<'tcx>) { debug!("Visiting item {:?}", item); let ident = renamed.unwrap_or(item.ident); @@ -395,7 +396,8 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { om.foreigns.push(if self.inlining { hir::ForeignMod { abi: fm.abi, - items: fm.items.iter().filter(|i| i.vis.node.is_pub()).cloned().collect(), + items: fm.items.iter().filter(|i| i.vis.node.is_pub()) + .cloned().collect_hir_vec(&self.cx.tcx.arena), } } else { fm.clone() @@ -605,9 +607,9 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { // Convert each `exported_macro` into a doc item. fn visit_local_macro( &self, - def: &hir::MacroDef, + def: &hir::MacroDef<'tcx>, renamed: Option - ) -> Macro { + ) -> Macro<'tcx> { debug!("visit_local_macro: {}", def.name); let tts = def.body.trees().collect::>(); // Extract the spans of all matchers. They represent the "interface" of the macro.