1
Fork 0

Prefer Default::default over FxHash*::default in struct constructors

This commit is contained in:
Oliver Scherer 2018-10-16 16:57:53 +02:00
parent ee81739dc1
commit 3c9258e604
82 changed files with 237 additions and 362 deletions

View file

@ -169,19 +169,13 @@ impl Ord for Interned<String> {
} }
} }
struct TyIntern<T> { #[derive(Default)]
struct TyIntern<T: Hash + Clone + Eq> {
items: Vec<T>, items: Vec<T>,
set: HashMap<T, Interned<T>>, set: HashMap<T, Interned<T>>,
} }
impl<T: Hash + Clone + Eq> TyIntern<T> { impl<T: Hash + Clone + Eq> TyIntern<T> {
fn new() -> TyIntern<T> {
TyIntern {
items: Vec::new(),
set: HashMap::new(),
}
}
fn intern_borrow<B>(&mut self, item: &B) -> Interned<T> fn intern_borrow<B>(&mut self, item: &B) -> Interned<T>
where where
B: Eq + Hash + ToOwned<Owned=T> + ?Sized, B: Eq + Hash + ToOwned<Owned=T> + ?Sized,
@ -212,19 +206,13 @@ impl<T: Hash + Clone + Eq> TyIntern<T> {
} }
} }
#[derive(Default)]
pub struct Interner { pub struct Interner {
strs: Mutex<TyIntern<String>>, strs: Mutex<TyIntern<String>>,
paths: Mutex<TyIntern<PathBuf>>, paths: Mutex<TyIntern<PathBuf>>,
} }
impl Interner { impl Interner {
fn new() -> Interner {
Interner {
strs: Mutex::new(TyIntern::new()),
paths: Mutex::new(TyIntern::new()),
}
}
pub fn intern_str(&self, s: &str) -> Interned<String> { pub fn intern_str(&self, s: &str) -> Interned<String> {
self.strs.lock().unwrap().intern_borrow(s) self.strs.lock().unwrap().intern_borrow(s)
} }
@ -238,7 +226,7 @@ impl Interner {
} }
lazy_static! { lazy_static! {
pub static ref INTERNER: Interner = Interner::new(); pub static ref INTERNER: Interner = Interner::default();
} }
/// This is essentially a HashMap which allows storing any type in its input and /// This is essentially a HashMap which allows storing any type in its input and

View file

@ -114,10 +114,9 @@ impl<T> TypedArenaChunk<T> {
const PAGE: usize = 4096; const PAGE: usize = 4096;
impl<T> TypedArena<T> { impl<T> Default for TypedArena<T> {
/// Creates a new `TypedArena`. /// Creates a new `TypedArena`.
#[inline] fn default() -> TypedArena<T> {
pub fn new() -> TypedArena<T> {
TypedArena { TypedArena {
// We set both `ptr` and `end` to 0 so that the first call to // We set both `ptr` and `end` to 0 so that the first call to
// alloc() will trigger a grow(). // alloc() will trigger a grow().
@ -127,7 +126,9 @@ impl<T> TypedArena<T> {
_own: PhantomData, _own: PhantomData,
} }
} }
}
impl<T> TypedArena<T> {
/// Allocates an object in the `TypedArena`, returning a reference to it. /// Allocates an object in the `TypedArena`, returning a reference to it.
#[inline] #[inline]
pub fn alloc(&self, object: T) -> &mut T { pub fn alloc(&self, object: T) -> &mut T {
@ -296,15 +297,17 @@ pub struct DroplessArena {
unsafe impl Send for DroplessArena {} unsafe impl Send for DroplessArena {}
impl DroplessArena { impl Default for DroplessArena {
pub fn new() -> DroplessArena { fn default() -> DroplessArena {
DroplessArena { DroplessArena {
ptr: Cell::new(0 as *mut u8), ptr: Cell::new(0 as *mut u8),
end: Cell::new(0 as *mut u8), end: Cell::new(0 as *mut u8),
chunks: RefCell::new(vec![]), chunks: Default::default(),
} }
} }
}
impl DroplessArena {
pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool { pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
let ptr = ptr as *const u8 as *mut u8; let ptr = ptr as *const u8 as *mut u8;
for chunk in &*self.chunks.borrow() { for chunk in &*self.chunks.borrow() {
@ -419,18 +422,13 @@ impl DroplessArena {
} }
} }
#[derive(Default)]
// FIXME(@Zoxc): this type is entirely unused in rustc
pub struct SyncTypedArena<T> { pub struct SyncTypedArena<T> {
lock: MTLock<TypedArena<T>>, lock: MTLock<TypedArena<T>>,
} }
impl<T> SyncTypedArena<T> { impl<T> SyncTypedArena<T> {
#[inline(always)]
pub fn new() -> SyncTypedArena<T> {
SyncTypedArena {
lock: MTLock::new(TypedArena::new())
}
}
#[inline(always)] #[inline(always)]
pub fn alloc(&self, object: T) -> &mut T { pub fn alloc(&self, object: T) -> &mut T {
// Extend the lifetime of the result since it's limited to the lock guard // Extend the lifetime of the result since it's limited to the lock guard
@ -452,18 +450,12 @@ impl<T> SyncTypedArena<T> {
} }
} }
#[derive(Default)]
pub struct SyncDroplessArena { pub struct SyncDroplessArena {
lock: MTLock<DroplessArena>, lock: MTLock<DroplessArena>,
} }
impl SyncDroplessArena { impl SyncDroplessArena {
#[inline(always)]
pub fn new() -> SyncDroplessArena {
SyncDroplessArena {
lock: MTLock::new(DroplessArena::new())
}
}
#[inline(always)] #[inline(always)]
pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool { pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
self.lock.lock().in_arena(ptr) self.lock.lock().in_arena(ptr)

View file

@ -51,8 +51,8 @@ pub struct CguReuseTracker {
impl CguReuseTracker { impl CguReuseTracker {
pub fn new() -> CguReuseTracker { pub fn new() -> CguReuseTracker {
let data = TrackerData { let data = TrackerData {
actual_reuse: FxHashMap::default(), actual_reuse: Default::default(),
expected_reuse: FxHashMap::default(), expected_reuse: Default::default(),
}; };
CguReuseTracker { CguReuseTracker {

View file

@ -36,7 +36,7 @@ impl<M: DepTrackingMapConfig> DepTrackingMap<M> {
DepTrackingMap { DepTrackingMap {
phantom: PhantomData, phantom: PhantomData,
graph, graph,
map: FxHashMap::default(), map: Default::default(),
} }
} }
} }

View file

@ -101,11 +101,11 @@ impl DepGraph {
DepGraph { DepGraph {
data: Some(Lrc::new(DepGraphData { data: Some(Lrc::new(DepGraphData {
previous_work_products: prev_work_products, previous_work_products: prev_work_products,
dep_node_debug: Lock::new(FxHashMap::default()), dep_node_debug: Lock::new(Default::default()),
current: Lock::new(CurrentDepGraph::new()), current: Lock::new(CurrentDepGraph::new()),
previous: prev_graph, previous: prev_graph,
colors: Lock::new(DepNodeColorMap::new(prev_graph_node_count)), colors: Lock::new(DepNodeColorMap::new(prev_graph_node_count)),
loaded_from_cache: Lock::new(FxHashMap::default()), loaded_from_cache: Lock::new(Default::default()),
})), })),
fingerprints: Lrc::new(Lock::new(fingerprints)), fingerprints: Lrc::new(Lock::new(fingerprints)),
} }
@ -209,7 +209,7 @@ impl DepGraph {
|key| OpenTask::Regular(Lock::new(RegularOpenTask { |key| OpenTask::Regular(Lock::new(RegularOpenTask {
node: key, node: key,
reads: SmallVec::new(), reads: SmallVec::new(),
read_set: FxHashSet::default(), read_set: Default::default(),
})), })),
|data, key, task| data.borrow_mut().complete_task(key, task)) |data, key, task| data.borrow_mut().complete_task(key, task))
} }
@ -353,7 +353,7 @@ impl DepGraph {
let (result, open_task) = ty::tls::with_context(|icx| { let (result, open_task) = ty::tls::with_context(|icx| {
let task = OpenTask::Anon(Lock::new(AnonOpenTask { let task = OpenTask::Anon(Lock::new(AnonOpenTask {
reads: SmallVec::new(), reads: SmallVec::new(),
read_set: FxHashSet::default(), read_set: Default::default(),
})); }));
let r = { let r = {
@ -937,7 +937,7 @@ impl CurrentDepGraph {
CurrentDepGraph { CurrentDepGraph {
nodes: IndexVec::new(), nodes: IndexVec::new(),
edges: IndexVec::new(), edges: IndexVec::new(),
node_to_node_index: FxHashMap::default(), node_to_node_index: Default::default(),
anon_id_seed: stable_hasher.finish(), anon_id_seed: stable_hasher.finish(),
forbidden_edge, forbidden_edge,
total_read_count: 0, total_read_count: 0,

View file

@ -13,7 +13,7 @@ use rustc_data_structures::fx::FxHashMap;
use super::dep_node::DepNode; use super::dep_node::DepNode;
use super::serialized::{SerializedDepGraph, SerializedDepNodeIndex}; use super::serialized::{SerializedDepGraph, SerializedDepNodeIndex};
#[derive(Debug, RustcEncodable, RustcDecodable)] #[derive(Debug, RustcEncodable, RustcDecodable, Default)]
pub struct PreviousDepGraph { pub struct PreviousDepGraph {
data: SerializedDepGraph, data: SerializedDepGraph,
index: FxHashMap<DepNode, SerializedDepNodeIndex>, index: FxHashMap<DepNode, SerializedDepNodeIndex>,

View file

@ -19,7 +19,7 @@ newtype_index! {
} }
/// Data for use when recompiling the **current crate**. /// Data for use when recompiling the **current crate**.
#[derive(Debug, RustcEncodable, RustcDecodable)] #[derive(Debug, RustcEncodable, RustcDecodable, Default)]
pub struct SerializedDepGraph { pub struct SerializedDepGraph {
/// The set of all DepNodes in the graph /// The set of all DepNodes in the graph
pub nodes: IndexVec<SerializedDepNodeIndex, DepNode>, pub nodes: IndexVec<SerializedDepNodeIndex, DepNode>,
@ -36,16 +36,6 @@ pub struct SerializedDepGraph {
} }
impl SerializedDepGraph { impl SerializedDepGraph {
pub fn new() -> SerializedDepGraph {
SerializedDepGraph {
nodes: IndexVec::new(),
fingerprints: IndexVec::new(),
edge_list_indices: IndexVec::new(),
edge_list_data: Vec::new(),
}
}
#[inline] #[inline]
pub fn edge_targets_from(&self, pub fn edge_targets_from(&self,
source: SerializedDepNodeIndex) source: SerializedDepNodeIndex)

View file

@ -421,10 +421,10 @@ impl Definitions {
node_to_def_index: NodeMap(), node_to_def_index: NodeMap(),
def_index_to_node: [vec![], vec![]], def_index_to_node: [vec![], vec![]],
node_to_hir_id: IndexVec::new(), node_to_hir_id: IndexVec::new(),
parent_modules_of_macro_defs: FxHashMap::default(), parent_modules_of_macro_defs: Default::default(),
expansions_that_defined: FxHashMap::default(), expansions_that_defined: Default::default(),
next_disambiguator: FxHashMap::default(), next_disambiguator: Default::default(),
def_index_to_span: FxHashMap::default(), def_index_to_span: Default::default(),
} }
} }

View file

@ -51,7 +51,7 @@ impl<'a, 'hir: 'a> OuterVisitor<'a, 'hir> {
HirIdValidator { HirIdValidator {
hir_map, hir_map,
owner_def_index: None, owner_def_index: None,
hir_ids_seen: FxHashMap::default(), hir_ids_seen: Default::default(),
errors: Vec::new(), errors: Vec::new(),
} }
} }

View file

@ -370,7 +370,7 @@ impl<'a> HashStable<StableHashingContext<'a>> for Span {
// recursing every time. // recursing every time.
thread_local! { thread_local! {
static CACHE: RefCell<FxHashMap<hygiene::Mark, u64>> = static CACHE: RefCell<FxHashMap<hygiene::Mark, u64>> =
RefCell::new(FxHashMap::default()); RefCell::new(Default::default());
} }
let sub_hash: u64 = CACHE.with(|cache| { let sub_hash: u64 = CACHE.with(|cache| {

View file

@ -32,7 +32,7 @@ for &'gcx ty::List<T>
hasher: &mut StableHasher<W>) { hasher: &mut StableHasher<W>) {
thread_local! { thread_local! {
static CACHE: RefCell<FxHashMap<(usize, usize), Fingerprint>> = static CACHE: RefCell<FxHashMap<(usize, usize), Fingerprint>> =
RefCell::new(FxHashMap::default()); RefCell::new(Default::default());
} }
let hash = CACHE.with(|cache| { let hash = CACHE.with(|cache| {

View file

@ -62,7 +62,7 @@ impl<'a, 'gcx, 'tcx> TypeFreshener<'a, 'gcx, 'tcx> {
TypeFreshener { TypeFreshener {
infcx, infcx,
freshen_count: 0, freshen_count: 0,
freshen_map: FxHashMap::default(), freshen_map: Default::default(),
} }
} }

View file

@ -614,7 +614,7 @@ impl<'cx, 'gcx, 'tcx> LexicalResolver<'cx, 'gcx, 'tcx> {
dup_found: bool, dup_found: bool,
} }
let mut state = WalkState { let mut state = WalkState {
set: FxHashSet::default(), set: Default::default(),
stack: vec![orig_node_idx], stack: vec![orig_node_idx],
result: Vec::new(), result: Vec::new(),
dup_found: false, dup_found: false,

View file

@ -478,7 +478,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'gcx> {
pub fn infer_ctxt(self) -> InferCtxtBuilder<'a, 'gcx, 'tcx> { pub fn infer_ctxt(self) -> InferCtxtBuilder<'a, 'gcx, 'tcx> {
InferCtxtBuilder { InferCtxtBuilder {
global_tcx: self, global_tcx: self,
arena: SyncDroplessArena::new(), arena: SyncDroplessArena::default(),
fresh_tables: None, fresh_tables: None,
} }
} }
@ -526,15 +526,15 @@ impl<'a, 'gcx, 'tcx> InferCtxtBuilder<'a, 'gcx, 'tcx> {
f(InferCtxt { f(InferCtxt {
tcx, tcx,
in_progress_tables, in_progress_tables,
projection_cache: RefCell::new(traits::ProjectionCache::new()), projection_cache: Default::default(),
type_variables: RefCell::new(type_variable::TypeVariableTable::new()), type_variables: RefCell::new(type_variable::TypeVariableTable::new()),
int_unification_table: RefCell::new(ut::UnificationTable::new()), int_unification_table: RefCell::new(ut::UnificationTable::new()),
float_unification_table: RefCell::new(ut::UnificationTable::new()), float_unification_table: RefCell::new(ut::UnificationTable::new()),
region_constraints: RefCell::new(Some(RegionConstraintCollector::new())), region_constraints: RefCell::new(Some(RegionConstraintCollector::new())),
lexical_region_resolutions: RefCell::new(None), lexical_region_resolutions: RefCell::new(None),
selection_cache: traits::SelectionCache::new(), selection_cache: Default::default(),
evaluation_cache: traits::EvaluationCache::new(), evaluation_cache: Default::default(),
reported_trait_errors: RefCell::new(FxHashMap::default()), reported_trait_errors: Default::default(),
tainted_by_errors_flag: Cell::new(false), tainted_by_errors_flag: Cell::new(false),
err_count_on_creation: tcx.sess.err_count(), err_count_on_creation: tcx.sess.err_count(),
in_snapshot: Cell::new(false), in_snapshot: Cell::new(false),

View file

@ -81,8 +81,8 @@ impl<'a, 'gcx: 'tcx, 'tcx: 'a> OutlivesEnvironment<'tcx> {
pub fn new(param_env: ty::ParamEnv<'tcx>) -> Self { pub fn new(param_env: ty::ParamEnv<'tcx>) -> Self {
let mut env = OutlivesEnvironment { let mut env = OutlivesEnvironment {
param_env, param_env,
free_region_map: FreeRegionMap::new(), free_region_map: Default::default(),
region_bound_pairs_map: FxHashMap::default(), region_bound_pairs_map: Default::default(),
region_bound_pairs_accum: vec![], region_bound_pairs_accum: vec![],
}; };

View file

@ -11,7 +11,7 @@
use ty::{self, Lift, TyCtxt, Region}; use ty::{self, Lift, TyCtxt, Region};
use rustc_data_structures::transitive_relation::TransitiveRelation; use rustc_data_structures::transitive_relation::TransitiveRelation;
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)] #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)]
pub struct FreeRegionMap<'tcx> { pub struct FreeRegionMap<'tcx> {
// Stores the relation `a < b`, where `a` and `b` are regions. // Stores the relation `a < b`, where `a` and `b` are regions.
// //
@ -21,10 +21,6 @@ pub struct FreeRegionMap<'tcx> {
} }
impl<'tcx> FreeRegionMap<'tcx> { impl<'tcx> FreeRegionMap<'tcx> {
pub fn new() -> Self {
FreeRegionMap { relation: TransitiveRelation::new() }
}
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
self.relation.is_empty() self.relation.is_empty()
} }

View file

@ -345,8 +345,8 @@ impl<'tcx> RegionConstraintCollector<'tcx> {
RegionConstraintCollector { RegionConstraintCollector {
var_infos: VarInfos::default(), var_infos: VarInfos::default(),
data: RegionConstraintData::default(), data: RegionConstraintData::default(),
lubs: FxHashMap::default(), lubs: Default::default(),
glbs: FxHashMap::default(), glbs: Default::default(),
bound_count: 0, bound_count: 0,
undo_log: Vec::new(), undo_log: Vec::new(),
unification_table: ut::UnificationTable::new(), unification_table: ut::UnificationTable::new(),

View file

@ -159,9 +159,9 @@ impl LintStore {
pre_expansion_passes: Some(vec![]), pre_expansion_passes: Some(vec![]),
early_passes: Some(vec![]), early_passes: Some(vec![]),
late_passes: Some(vec![]), late_passes: Some(vec![]),
by_name: FxHashMap::default(), by_name: Default::default(),
future_incompatible: FxHashMap::default(), future_incompatible: Default::default(),
lint_groups: FxHashMap::default(), lint_groups: Default::default(),
} }
} }

View file

@ -175,7 +175,7 @@ impl<'a> LintLevelsBuilder<'a> {
sess, sess,
sets, sets,
cur: 0, cur: 0,
id_to_set: FxHashMap::default(), id_to_set: Default::default(),
warn_about_weird_lints: sess.buffered_lints.borrow().is_some(), warn_about_weird_lints: sess.buffered_lints.borrow().is_some(),
} }
} }

View file

@ -50,6 +50,7 @@ struct MarkSymbolVisitor<'a, 'tcx: 'a> {
worklist: Vec<ast::NodeId>, worklist: Vec<ast::NodeId>,
tcx: TyCtxt<'a, 'tcx, 'tcx>, tcx: TyCtxt<'a, 'tcx, 'tcx>,
tables: &'a ty::TypeckTables<'tcx>, tables: &'a ty::TypeckTables<'tcx>,
// TODO: remove this `Box`
live_symbols: Box<FxHashSet<ast::NodeId>>, live_symbols: Box<FxHashSet<ast::NodeId>>,
repr_has_repr_c: bool, repr_has_repr_c: bool,
in_pat: bool, in_pat: bool,
@ -429,7 +430,7 @@ fn find_live<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
worklist, worklist,
tcx, tcx,
tables: &ty::TypeckTables::empty(None), tables: &ty::TypeckTables::empty(None),
live_symbols: box FxHashSet::default(), live_symbols: box Default::default(),
repr_has_repr_c: false, repr_has_repr_c: false,
in_pat: false, in_pat: false,
inherited_pub_visibility: false, inherited_pub_visibility: false,

View file

@ -31,8 +31,8 @@ pub struct LibFeatures {
impl LibFeatures { impl LibFeatures {
fn new() -> LibFeatures { fn new() -> LibFeatures {
LibFeatures { LibFeatures {
stable: FxHashMap::default(), stable: Default::default(),
unstable: FxHashSet::default(), unstable: Default::default(),
} }
} }

View file

@ -1347,7 +1347,7 @@ fn region_scope_tree<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
parent: None, parent: None,
var_parent: None, var_parent: None,
}, },
terminating_scopes: FxHashSet::default(), terminating_scopes: Default::default(),
}; };
let body = tcx.hir.body(body_id); let body = tcx.hir.body(body_id);

View file

@ -216,6 +216,7 @@ struct NamedRegionMap {
} }
/// See `NamedRegionMap`. /// See `NamedRegionMap`.
#[derive(Default)]
pub struct ResolveLifetimes { pub struct ResolveLifetimes {
defs: FxHashMap<LocalDefId, Lrc<FxHashMap<ItemLocalId, Region>>>, defs: FxHashMap<LocalDefId, Lrc<FxHashMap<ItemLocalId, Region>>>,
late_bound: FxHashMap<LocalDefId, Lrc<FxHashSet<ItemLocalId>>>, late_bound: FxHashMap<LocalDefId, Lrc<FxHashSet<ItemLocalId>>>,
@ -392,11 +393,7 @@ fn resolve_lifetimes<'tcx>(
let named_region_map = krate(tcx); let named_region_map = krate(tcx);
let mut rl = ResolveLifetimes { let mut rl = ResolveLifetimes::default();
defs: FxHashMap::default(),
late_bound: FxHashMap::default(),
object_lifetime_defaults: FxHashMap::default(),
};
for (k, v) in named_region_map.defs { for (k, v) in named_region_map.defs {
let hir_id = tcx.hir.node_to_hir_id(k); let hir_id = tcx.hir.node_to_hir_id(k);
@ -2017,7 +2014,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
map: self.map, map: self.map,
outer_index: ty::INNERMOST, outer_index: ty::INNERMOST,
have_bound_regions: false, have_bound_regions: false,
lifetimes: FxHashSet::default(), lifetimes: Default::default(),
}; };
gather.visit_ty(input); gather.visit_ty(input);
@ -2536,15 +2533,13 @@ fn insert_late_bound_lifetimes(
debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})", debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})",
decl, generics); decl, generics);
let mut constrained_by_input = ConstrainedCollector { let mut constrained_by_input = ConstrainedCollector::default();
regions: FxHashSet::default(),
};
for arg_ty in &decl.inputs { for arg_ty in &decl.inputs {
constrained_by_input.visit_ty(arg_ty); constrained_by_input.visit_ty(arg_ty);
} }
let mut appears_in_output = AllCollector { let mut appears_in_output = AllCollector {
regions: FxHashSet::default(), regions: Default::default(),
}; };
intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output); intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
@ -2556,7 +2551,7 @@ fn insert_late_bound_lifetimes(
// Subtle point: because we disallow nested bindings, we can just // Subtle point: because we disallow nested bindings, we can just
// ignore binders here and scrape up all names we see. // ignore binders here and scrape up all names we see.
let mut appears_in_where_clause = AllCollector { let mut appears_in_where_clause = AllCollector {
regions: FxHashSet::default(), regions: Default::default(),
}; };
appears_in_where_clause.visit_generics(generics); appears_in_where_clause.visit_generics(generics);
@ -2610,6 +2605,7 @@ fn insert_late_bound_lifetimes(
return; return;
#[derive(Default)]
struct ConstrainedCollector { struct ConstrainedCollector {
regions: FxHashSet<hir::LifetimeName>, regions: FxHashSet<hir::LifetimeName>,
} }

View file

@ -405,9 +405,9 @@ impl<'a, 'tcx> Index<'tcx> {
staged_api.insert(LOCAL_CRATE, is_staged_api); staged_api.insert(LOCAL_CRATE, is_staged_api);
let mut index = Index { let mut index = Index {
staged_api, staged_api,
stab_map: FxHashMap::default(), stab_map: Default::default(),
depr_map: FxHashMap::default(), depr_map: Default::default(),
active_features: FxHashSet::default(), active_features: Default::default(),
}; };
let ref active_lib_features = tcx.features().declared_lib_features; let ref active_lib_features = tcx.features().declared_lib_features;

View file

@ -453,8 +453,8 @@ pub struct AllocMap<'tcx, M> {
impl<'tcx, M: fmt::Debug + Eq + Hash + Clone> AllocMap<'tcx, M> { impl<'tcx, M: fmt::Debug + Eq + Hash + Clone> AllocMap<'tcx, M> {
pub fn new() -> Self { pub fn new() -> Self {
AllocMap { AllocMap {
id_to_type: FxHashMap::default(), id_to_type: Default::default(),
type_interner: FxHashMap::default(), type_interner: Default::default(),
next_id: AllocId(0), next_id: AllocId(0),
} }
} }

View file

@ -121,7 +121,7 @@ impl<'tcx> CodegenUnit<'tcx> {
pub fn new(name: InternedString) -> CodegenUnit<'tcx> { pub fn new(name: InternedString) -> CodegenUnit<'tcx> {
CodegenUnit { CodegenUnit {
name: name, name: name,
items: FxHashMap::default(), items: Default::default(),
size_estimate: None, size_estimate: None,
} }
} }
@ -251,7 +251,7 @@ impl<'a, 'gcx: 'tcx, 'tcx: 'a> CodegenUnitNameBuilder<'a, 'gcx, 'tcx> {
pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self { pub fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Self {
CodegenUnitNameBuilder { CodegenUnitNameBuilder {
tcx, tcx,
cache: FxHashMap::default(), cache: Default::default(),
} }
} }

View file

@ -54,14 +54,12 @@ pub struct TypeSizeInfo {
pub variants: Vec<VariantInfo>, pub variants: Vec<VariantInfo>,
} }
#[derive(PartialEq, Eq, Debug)] #[derive(PartialEq, Eq, Debug, Default)]
pub struct CodeStats { pub struct CodeStats {
type_sizes: FxHashSet<TypeSizeInfo>, type_sizes: FxHashSet<TypeSizeInfo>,
} }
impl CodeStats { impl CodeStats {
pub fn new() -> Self { CodeStats { type_sizes: FxHashSet::default() } }
pub fn record_type_size<S: ToString>(&mut self, pub fn record_type_size<S: ToString>(&mut self,
kind: DataTypeKind, kind: DataTypeKind,
type_desc: S, type_desc: S,

View file

@ -1147,7 +1147,7 @@ pub fn build_session_(
working_dir, working_dir,
lint_store: RwLock::new(lint::LintStore::new()), lint_store: RwLock::new(lint::LintStore::new()),
buffered_lints: Lock::new(Some(lint::LintBuffer::new())), buffered_lints: Lock::new(Some(lint::LintBuffer::new())),
one_time_diagnostics: Lock::new(FxHashSet::default()), one_time_diagnostics: Default::default(),
plugin_llvm_passes: OneThread::new(RefCell::new(Vec::new())), plugin_llvm_passes: OneThread::new(RefCell::new(Vec::new())),
plugin_attributes: OneThread::new(RefCell::new(Vec::new())), plugin_attributes: OneThread::new(RefCell::new(Vec::new())),
crate_types: Once::new(), crate_types: Once::new(),
@ -1173,7 +1173,7 @@ pub fn build_session_(
normalize_ty_after_erasing_regions: AtomicUsize::new(0), normalize_ty_after_erasing_regions: AtomicUsize::new(0),
normalize_projection_ty: AtomicUsize::new(0), normalize_projection_ty: AtomicUsize::new(0),
}, },
code_stats: Lock::new(CodeStats::new()), code_stats: Default::default(),
optimization_fuel_crate, optimization_fuel_crate,
optimization_fuel_limit, optimization_fuel_limit,
print_fuel_crate, print_fuel_crate,
@ -1207,7 +1207,7 @@ pub fn build_session_(
}, },
has_global_allocator: Once::new(), has_global_allocator: Once::new(),
has_panic_handler: Once::new(), has_panic_handler: Once::new(),
driver_lint_caps: FxHashMap::default(), driver_lint_caps: Default::default(),
}; };
validate_commandline_args_with_session_available(&sess); validate_commandline_args_with_session_available(&sess);

View file

@ -1404,7 +1404,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
let cleaned_pred = pred.fold_with(&mut ParamToVarFolder { let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
infcx: self, infcx: self,
var_map: FxHashMap::default() var_map: Default::default()
}); });
let cleaned_pred = super::project::normalize( let cleaned_pred = super::project::normalize(

View file

@ -48,7 +48,7 @@ pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
pub use self::select::{EvaluationCache, SelectionContext, SelectionCache}; pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError}; pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
pub use self::specialize::{OverlapError, specialization_graph, translate_substs}; pub use self::specialize::{OverlapError, specialization_graph, translate_substs};
pub use self::specialize::{SpecializesCache, find_associated_item}; pub use self::specialize::find_associated_item;
pub use self::engine::{TraitEngine, TraitEngineExt}; pub use self::engine::{TraitEngine, TraitEngineExt};
pub use self::util::elaborate_predicates; pub use self::util::elaborate_predicates;
pub use self::util::supertraits; pub use self::util::supertraits;

View file

@ -1601,6 +1601,7 @@ fn assoc_ty_def<'cx, 'gcx, 'tcx>(
/// FIXME: we probably also want some sort of cross-infcx cache here to /// FIXME: we probably also want some sort of cross-infcx cache here to
/// reduce the amount of duplication. Let's see what we get with the Chalk /// reduce the amount of duplication. Let's see what we get with the Chalk
/// reforms. /// reforms.
#[derive(Default)]
pub struct ProjectionCache<'tcx> { pub struct ProjectionCache<'tcx> {
map: SnapshotMap<ProjectionCacheKey<'tcx>, ProjectionCacheEntry<'tcx>>, map: SnapshotMap<ProjectionCacheKey<'tcx>, ProjectionCacheEntry<'tcx>>,
} }
@ -1643,12 +1644,6 @@ pub struct ProjectionCacheSnapshot {
} }
impl<'tcx> ProjectionCache<'tcx> { impl<'tcx> ProjectionCache<'tcx> {
pub fn new() -> Self {
ProjectionCache {
map: SnapshotMap::new()
}
}
pub fn clear(&mut self) { pub fn clear(&mut self) {
self.map.clear(); self.map.clear();
} }

View file

@ -166,7 +166,7 @@ struct TraitObligationStack<'prev, 'tcx: 'prev> {
previous: TraitObligationStackList<'prev, 'tcx>, previous: TraitObligationStackList<'prev, 'tcx>,
} }
#[derive(Clone)] #[derive(Clone, Default)]
pub struct SelectionCache<'tcx> { pub struct SelectionCache<'tcx> {
hashmap: Lock< hashmap: Lock<
FxHashMap<ty::TraitRef<'tcx>, WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>, FxHashMap<ty::TraitRef<'tcx>, WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
@ -444,7 +444,7 @@ impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
} }
} }
#[derive(Clone)] #[derive(Clone, Default)]
pub struct EvaluationCache<'tcx> { pub struct EvaluationCache<'tcx> {
hashmap: Lock<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>, hashmap: Lock<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>,
} }
@ -3789,26 +3789,14 @@ impl<'tcx> TraitObligation<'tcx> {
} }
impl<'tcx> SelectionCache<'tcx> { impl<'tcx> SelectionCache<'tcx> {
pub fn new() -> SelectionCache<'tcx> {
SelectionCache {
hashmap: Lock::new(FxHashMap::default()),
}
}
pub fn clear(&self) { pub fn clear(&self) {
*self.hashmap.borrow_mut() = FxHashMap::default() self.hashmap.borrow_mut().clear();
} }
} }
impl<'tcx> EvaluationCache<'tcx> { impl<'tcx> EvaluationCache<'tcx> {
pub fn new() -> EvaluationCache<'tcx> {
EvaluationCache {
hashmap: Lock::new(FxHashMap::default()),
}
}
pub fn clear(&self) { pub fn clear(&self) {
*self.hashmap.borrow_mut() = FxHashMap::default() self.hashmap.borrow_mut().clear();
} }
} }

View file

@ -22,7 +22,7 @@
use super::{SelectionContext, FulfillmentContext}; use super::{SelectionContext, FulfillmentContext};
use super::util::impl_trait_ref_and_oblig; use super::util::impl_trait_ref_and_oblig;
use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::fx::FxHashSet;
use hir::def_id::DefId; use hir::def_id::DefId;
use infer::{InferCtxt, InferOk}; use infer::{InferCtxt, InferOk};
use ty::subst::{Subst, Substs}; use ty::subst::{Subst, Substs};
@ -284,26 +284,6 @@ fn fulfill_implication<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
}) })
} }
pub struct SpecializesCache {
map: FxHashMap<(DefId, DefId), bool>,
}
impl SpecializesCache {
pub fn new() -> Self {
SpecializesCache {
map: FxHashMap::default()
}
}
pub fn check(&self, a: DefId, b: DefId) -> Option<bool> {
self.map.get(&(a, b)).cloned()
}
pub fn insert(&mut self, a: DefId, b: DefId, result: bool) {
self.map.insert((a, b), result);
}
}
// Query provider for `specialization_graph_of`. // Query provider for `specialization_graph_of`.
pub(super) fn specialization_graph_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, pub(super) fn specialization_graph_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
trait_id: DefId) trait_id: DefId)

View file

@ -59,7 +59,7 @@ struct PredicateSet<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
impl<'a, 'gcx, 'tcx> PredicateSet<'a, 'gcx, 'tcx> { impl<'a, 'gcx, 'tcx> PredicateSet<'a, 'gcx, 'tcx> {
fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PredicateSet<'a, 'gcx, 'tcx> { fn new(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> PredicateSet<'a, 'gcx, 'tcx> {
PredicateSet { tcx: tcx, set: FxHashSet::default() } PredicateSet { tcx: tcx, set: Default::default() }
} }
fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool { fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool {

View file

@ -89,13 +89,14 @@ pub struct AllArenas<'tcx> {
impl<'tcx> AllArenas<'tcx> { impl<'tcx> AllArenas<'tcx> {
pub fn new() -> Self { pub fn new() -> Self {
AllArenas { AllArenas {
global: WorkerLocal::new(|_| GlobalArenas::new()), global: WorkerLocal::new(|_| GlobalArenas::default()),
interner: SyncDroplessArena::new(), interner: SyncDroplessArena::default(),
} }
} }
} }
/// Internal storage /// Internal storage
#[derive(Default)]
pub struct GlobalArenas<'tcx> { pub struct GlobalArenas<'tcx> {
// internings // internings
layout: TypedArena<LayoutDetails>, layout: TypedArena<LayoutDetails>,
@ -111,21 +112,6 @@ pub struct GlobalArenas<'tcx> {
const_allocs: TypedArena<interpret::Allocation>, const_allocs: TypedArena<interpret::Allocation>,
} }
impl<'tcx> GlobalArenas<'tcx> {
pub fn new() -> GlobalArenas<'tcx> {
GlobalArenas {
layout: TypedArena::new(),
generics: TypedArena::new(),
trait_def: TypedArena::new(),
adt_def: TypedArena::new(),
steal_mir: TypedArena::new(),
mir: TypedArena::new(),
tables: TypedArena::new(),
const_allocs: TypedArena::new(),
}
}
}
type InternedSet<'tcx, T> = Lock<FxHashSet<Interned<'tcx, T>>>; type InternedSet<'tcx, T> = Lock<FxHashSet<Interned<'tcx, T>>>;
pub struct CtxtInterners<'tcx> { pub struct CtxtInterners<'tcx> {
@ -462,15 +448,15 @@ impl<'tcx> TypeckTables<'tcx> {
adjustments: ItemLocalMap(), adjustments: ItemLocalMap(),
pat_binding_modes: ItemLocalMap(), pat_binding_modes: ItemLocalMap(),
pat_adjustments: ItemLocalMap(), pat_adjustments: ItemLocalMap(),
upvar_capture_map: FxHashMap::default(), upvar_capture_map: Default::default(),
closure_kind_origins: ItemLocalMap(), closure_kind_origins: ItemLocalMap(),
liberated_fn_sigs: ItemLocalMap(), liberated_fn_sigs: ItemLocalMap(),
fru_field_types: ItemLocalMap(), fru_field_types: ItemLocalMap(),
cast_kinds: ItemLocalMap(), cast_kinds: ItemLocalMap(),
used_trait_imports: Lrc::new(DefIdSet()), used_trait_imports: Lrc::new(DefIdSet()),
tainted_by_errors: false, tainted_by_errors: false,
free_region_map: FreeRegionMap::new(), free_region_map: Default::default(),
concrete_existential_types: FxHashMap::default(), concrete_existential_types: Default::default(),
} }
} }
@ -1231,14 +1217,14 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
extern_providers, extern_providers,
on_disk_query_result_cache, on_disk_query_result_cache,
), ),
rcache: Lock::new(FxHashMap::default()), rcache: Default::default(),
selection_cache: traits::SelectionCache::new(), selection_cache: Default::default(),
evaluation_cache: traits::EvaluationCache::new(), evaluation_cache: Default::default(),
crate_name: Symbol::intern(crate_name), crate_name: Symbol::intern(crate_name),
data_layout, data_layout,
layout_interner: Lock::new(FxHashSet::default()), layout_interner: Default::default(),
stability_interner: Lock::new(FxHashSet::default()), stability_interner: Default::default(),
allocation_interner: Lock::new(FxHashSet::default()), allocation_interner: Default::default(),
alloc_map: Lock::new(interpret::AllocMap::new()), alloc_map: Lock::new(interpret::AllocMap::new()),
tx_to_llvm_workers: Lock::new(tx), tx_to_llvm_workers: Lock::new(tx),
output_filenames: Arc::new(output_filenames.clone()), output_filenames: Arc::new(output_filenames.clone()),

View file

@ -753,7 +753,7 @@ impl LateBoundRegionsCollector {
fn new(just_constrained: bool) -> Self { fn new(just_constrained: bool) -> Self {
LateBoundRegionsCollector { LateBoundRegionsCollector {
current_index: ty::INNERMOST, current_index: ty::INNERMOST,
regions: FxHashSet::default(), regions: Default::default(),
just_constrained, just_constrained,
} }
} }

View file

@ -1841,8 +1841,7 @@ impl<'a> HashStable<StableHashingContext<'a>> for AdtDef {
hcx: &mut StableHashingContext<'a>, hcx: &mut StableHashingContext<'a>,
hasher: &mut StableHasher<W>) { hasher: &mut StableHasher<W>) {
thread_local! { thread_local! {
static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = static CACHE: RefCell<FxHashMap<usize, Fingerprint>> = Default::default();
RefCell::new(FxHashMap::default());
} }
let hash: Fingerprint = CACHE.with(|cache| { let hash: Fingerprint = CACHE.with(|cache| {

View file

@ -136,14 +136,14 @@ impl<'sess> OnDiskCache<'sess> {
OnDiskCache { OnDiskCache {
serialized_data: data, serialized_data: data,
file_index_to_stable_id: footer.file_index_to_stable_id, file_index_to_stable_id: footer.file_index_to_stable_id,
file_index_to_file: Lock::new(FxHashMap::default()), file_index_to_file: Default::default(),
prev_cnums: footer.prev_cnums, prev_cnums: footer.prev_cnums,
cnum_map: Once::new(), cnum_map: Once::new(),
source_map: sess.source_map(), source_map: sess.source_map(),
current_diagnostics: Lock::new(FxHashMap::default()), current_diagnostics: Default::default(),
query_result_index: footer.query_result_index.into_iter().collect(), query_result_index: footer.query_result_index.into_iter().collect(),
prev_diagnostics_index: footer.diagnostics_index.into_iter().collect(), prev_diagnostics_index: footer.diagnostics_index.into_iter().collect(),
synthetic_expansion_infos: Lock::new(FxHashMap::default()), synthetic_expansion_infos: Default::default(),
alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index), alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index),
} }
} }
@ -151,15 +151,15 @@ impl<'sess> OnDiskCache<'sess> {
pub fn new_empty(source_map: &'sess SourceMap) -> OnDiskCache<'sess> { pub fn new_empty(source_map: &'sess SourceMap) -> OnDiskCache<'sess> {
OnDiskCache { OnDiskCache {
serialized_data: Vec::new(), serialized_data: Vec::new(),
file_index_to_stable_id: FxHashMap::default(), file_index_to_stable_id: Default::default(),
file_index_to_file: Lock::new(FxHashMap::default()), file_index_to_file: Default::default(),
prev_cnums: vec![], prev_cnums: vec![],
cnum_map: Once::new(), cnum_map: Once::new(),
source_map, source_map,
current_diagnostics: Lock::new(FxHashMap::default()), current_diagnostics: Default::default(),
query_result_index: FxHashMap::default(), query_result_index: Default::default(),
prev_diagnostics_index: FxHashMap::default(), prev_diagnostics_index: Default::default(),
synthetic_expansion_infos: Lock::new(FxHashMap::default()), synthetic_expansion_infos: Default::default(),
alloc_decoding_state: AllocDecodingState::new(Vec::new()), alloc_decoding_state: AllocDecodingState::new(Vec::new()),
} }
} }
@ -190,10 +190,10 @@ impl<'sess> OnDiskCache<'sess> {
let mut encoder = CacheEncoder { let mut encoder = CacheEncoder {
tcx, tcx,
encoder, encoder,
type_shorthands: FxHashMap::default(), type_shorthands: Default::default(),
predicate_shorthands: FxHashMap::default(), predicate_shorthands: Default::default(),
expn_info_shorthands: FxHashMap::default(), expn_info_shorthands: Default::default(),
interpret_allocs: FxHashMap::default(), interpret_allocs: Default::default(),
interpret_allocs_inverse: Vec::new(), interpret_allocs_inverse: Vec::new(),
source_map: CachingSourceMapView::new(tcx.sess.source_map()), source_map: CachingSourceMapView::new(tcx.sess.source_map()),
file_to_file_index, file_to_file_index,

View file

@ -55,8 +55,8 @@ impl<T> QueryValue<T> {
} }
} }
impl<'tcx, M: QueryConfig<'tcx>> QueryCache<'tcx, M> { impl<'tcx, M: QueryConfig<'tcx>> Default for QueryCache<'tcx, M> {
pub(super) fn new() -> QueryCache<'tcx, M> { fn default() -> QueryCache<'tcx, M> {
QueryCache { QueryCache {
results: FxHashMap::default(), results: FxHashMap::default(),
active: FxHashMap::default(), active: FxHashMap::default(),
@ -699,7 +699,7 @@ macro_rules! define_queries_inner {
providers, providers,
fallback_extern_providers: Box::new(fallback_extern_providers), fallback_extern_providers: Box::new(fallback_extern_providers),
on_disk_cache, on_disk_cache,
$($name: Lock::new(QueryCache::new())),* $($name: Default::default()),*
} }
} }

View file

@ -22,9 +22,9 @@ pub use rustc_data_structures::fx::FxHashSet;
macro_rules! define_id_collections { macro_rules! define_id_collections {
($map_name:ident, $set_name:ident, $key:ty) => { ($map_name:ident, $set_name:ident, $key:ty) => {
pub type $map_name<T> = FxHashMap<$key, T>; pub type $map_name<T> = FxHashMap<$key, T>;
pub fn $map_name<T>() -> $map_name<T> { FxHashMap::default() } pub fn $map_name<T>() -> $map_name<T> { Default::default() }
pub type $set_name = FxHashSet<$key>; pub type $set_name = FxHashSet<$key>;
pub fn $set_name() -> $set_name { FxHashSet::default() } pub fn $set_name() -> $set_name { Default::default() }
} }
} }

View file

@ -182,7 +182,7 @@ impl PrintContext {
fn prepare_late_bound_region_info<'tcx, T>(&mut self, value: &ty::Binder<T>) fn prepare_late_bound_region_info<'tcx, T>(&mut self, value: &ty::Binder<T>)
where T: TypeFoldable<'tcx> where T: TypeFoldable<'tcx>
{ {
let mut collector = LateBoundRegionNameCollector(FxHashSet::default()); let mut collector = LateBoundRegionNameCollector(Default::default());
value.visit_with(&mut collector); value.visit_with(&mut collector);
self.used_region_names = Some(collector.0); self.used_region_names = Some(collector.0);
self.region_index = 0; self.region_index = 0;

View file

@ -103,7 +103,7 @@ fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId)
// tuple structs/variants) do not have an associated body // tuple structs/variants) do not have an associated body
// and do not need borrowchecking. // and do not need borrowchecking.
return Lrc::new(BorrowCheckResult { return Lrc::new(BorrowCheckResult {
used_mut_nodes: FxHashSet::default(), used_mut_nodes: Default::default(),
signalled_any_error: SignalledError::NoErrorsSeen, signalled_any_error: SignalledError::NoErrorsSeen,
}) })
} }
@ -120,7 +120,7 @@ fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId)
region_scope_tree, region_scope_tree,
owner_def_id, owner_def_id,
body, body,
used_mut_nodes: RefCell::new(FxHashSet::default()), used_mut_nodes: Default::default(),
signalled_any_error: Cell::new(SignalledError::NoErrorsSeen), signalled_any_error: Cell::new(SignalledError::NoErrorsSeen),
}; };
@ -235,7 +235,7 @@ pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>(
region_scope_tree, region_scope_tree,
owner_def_id, owner_def_id,
body, body,
used_mut_nodes: RefCell::new(FxHashSet::default()), used_mut_nodes: Default::default(),
signalled_any_error: Cell::new(SignalledError::NoErrorsSeen), signalled_any_error: Cell::new(SignalledError::NoErrorsSeen),
}; };

View file

@ -45,7 +45,7 @@ struct UnusedMutCx<'a, 'tcx: 'a> {
impl<'a, 'tcx> UnusedMutCx<'a, 'tcx> { impl<'a, 'tcx> UnusedMutCx<'a, 'tcx> {
fn check_unused_mut_pat(&self, pats: &[P<hir::Pat>]) { fn check_unused_mut_pat(&self, pats: &[P<hir::Pat>]) {
let tcx = self.bccx.tcx; let tcx = self.bccx.tcx;
let mut mutables: FxHashMap<_, Vec<_>> = FxHashMap::default(); let mut mutables: FxHashMap<_, Vec<_>> = Default::default();
for p in pats { for p in pats {
p.each_binding(|_, hir_id, span, ident| { p.each_binding(|_, hir_id, span, ident| {
// Skip anything that looks like `_foo` // Skip anything that looks like `_foo`

View file

@ -502,7 +502,7 @@ fn thin_lto(cgcx: &CodegenContext,
// If we don't compile incrementally, we don't need to load the // If we don't compile incrementally, we don't need to load the
// import data from LLVM. // import data from LLVM.
assert!(green_modules.is_empty()); assert!(green_modules.is_empty());
ThinLTOImports::new() ThinLTOImports::default()
}; };
info!("thin LTO import map loaded"); info!("thin LTO import map loaded");
timeline.record("import-map-loaded"); timeline.record("import-map-loaded");
@ -873,19 +873,13 @@ impl ThinModule {
} }
} }
#[derive(Debug)] #[derive(Debug, Default)]
pub struct ThinLTOImports { pub struct ThinLTOImports {
// key = llvm name of importing module, value = list of modules it imports from // key = llvm name of importing module, value = list of modules it imports from
imports: FxHashMap<String, Vec<String>>, imports: FxHashMap<String, Vec<String>>,
} }
impl ThinLTOImports { impl ThinLTOImports {
fn new() -> ThinLTOImports {
ThinLTOImports {
imports: FxHashMap::default(),
}
}
fn modules_imported_by(&self, llvm_module_name: &str) -> &[String] { fn modules_imported_by(&self, llvm_module_name: &str) -> &[String] {
self.imports.get(llvm_module_name).map(|v| &v[..]).unwrap_or(&[]) self.imports.get(llvm_module_name).map(|v| &v[..]).unwrap_or(&[])
} }
@ -910,9 +904,7 @@ impl ThinLTOImports {
.unwrap() .unwrap()
.push(imported_module_name.to_owned()); .push(imported_module_name.to_owned());
} }
let mut map = ThinLTOImports { let mut map = ThinLTOImports::default();
imports: FxHashMap::default(),
};
llvm::LLVMRustGetThinLTOModuleImports(data, llvm::LLVMRustGetThinLTOModuleImports(data,
imported_module_callback, imported_module_callback,
&mut map as *mut _ as *mut libc::c_void); &mut map as *mut _ as *mut libc::c_void);

View file

@ -70,7 +70,7 @@ use time_graph;
use mono_item::{MonoItem, BaseMonoItemExt, MonoItemExt}; use mono_item::{MonoItem, BaseMonoItemExt, MonoItemExt};
use type_::Type; use type_::Type;
use type_of::LayoutLlvmExt; use type_of::LayoutLlvmExt;
use rustc::util::nodemap::{FxHashMap, FxHashSet, DefIdSet}; use rustc::util::nodemap::{FxHashMap, DefIdSet};
use CrateInfo; use CrateInfo;
use rustc_data_structures::small_c_str::SmallCStr; use rustc_data_structures::small_c_str::SmallCStr;
use rustc_data_structures::sync::Lrc; use rustc_data_structures::sync::Lrc;
@ -1030,7 +1030,7 @@ fn collect_and_partition_mono_items<'a, 'tcx>(
}).collect(); }).collect();
if tcx.sess.opts.debugging_opts.print_mono_items.is_some() { if tcx.sess.opts.debugging_opts.print_mono_items.is_some() {
let mut item_to_cgus: FxHashMap<_, Vec<_>> = FxHashMap::default(); let mut item_to_cgus: FxHashMap<_, Vec<_>> = Default::default();
for cgu in &codegen_units { for cgu in &codegen_units {
for (&mono_item, &linkage) in cgu.items() { for (&mono_item, &linkage) in cgu.items() {
@ -1092,17 +1092,17 @@ impl CrateInfo {
compiler_builtins: None, compiler_builtins: None,
profiler_runtime: None, profiler_runtime: None,
sanitizer_runtime: None, sanitizer_runtime: None,
is_no_builtins: FxHashSet::default(), is_no_builtins: Default::default(),
native_libraries: FxHashMap::default(), native_libraries: Default::default(),
used_libraries: tcx.native_libraries(LOCAL_CRATE), used_libraries: tcx.native_libraries(LOCAL_CRATE),
link_args: tcx.link_args(LOCAL_CRATE), link_args: tcx.link_args(LOCAL_CRATE),
crate_name: FxHashMap::default(), crate_name: Default::default(),
used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic), used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic), used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
used_crate_source: FxHashMap::default(), used_crate_source: Default::default(),
wasm_imports: FxHashMap::default(), wasm_imports: Default::default(),
lang_item_to_crate: FxHashMap::default(), lang_item_to_crate: Default::default(),
missing_lang_items: FxHashMap::default(), missing_lang_items: Default::default(),
}; };
let lang_items = tcx.lang_items(); let lang_items = tcx.lang_items();

View file

@ -295,22 +295,22 @@ impl<'a, 'tcx> CodegenCx<'a, 'tcx> {
llcx, llcx,
stats: RefCell::new(Stats::default()), stats: RefCell::new(Stats::default()),
codegen_unit, codegen_unit,
instances: RefCell::new(FxHashMap::default()), instances: Default::default(),
vtables: RefCell::new(FxHashMap::default()), vtables: Default::default(),
const_cstr_cache: RefCell::new(FxHashMap::default()), const_cstr_cache: Default::default(),
const_unsized: RefCell::new(FxHashMap::default()), const_unsized: Default::default(),
const_globals: RefCell::new(FxHashMap::default()), const_globals: Default::default(),
statics_to_rauw: RefCell::new(Vec::new()), statics_to_rauw: RefCell::new(Vec::new()),
used_statics: RefCell::new(Vec::new()), used_statics: RefCell::new(Vec::new()),
lltypes: RefCell::new(FxHashMap::default()), lltypes: Default::default(),
scalar_lltypes: RefCell::new(FxHashMap::default()), scalar_lltypes: Default::default(),
pointee_infos: RefCell::new(FxHashMap::default()), pointee_infos: Default::default(),
isize_ty, isize_ty,
dbg_cx, dbg_cx,
eh_personality: Cell::new(None), eh_personality: Cell::new(None),
eh_unwind_resume: Cell::new(None), eh_unwind_resume: Cell::new(None),
rust_try_fn: Cell::new(None), rust_try_fn: Cell::new(None),
intrinsics: RefCell::new(FxHashMap::default()), intrinsics: Default::default(),
local_gen_sym_counter: Cell::new(0), local_gen_sym_counter: Cell::new(0),
} }
} }

View file

@ -96,6 +96,7 @@ pub struct UniqueTypeId(ast::Name);
// created so far. The metadata nodes are indexed by UniqueTypeId, and, for // created so far. The metadata nodes are indexed by UniqueTypeId, and, for
// faster lookup, also by Ty. The TypeMap is responsible for creating // faster lookup, also by Ty. The TypeMap is responsible for creating
// UniqueTypeIds. // UniqueTypeIds.
#[derive(Default)]
pub struct TypeMap<'ll, 'tcx> { pub struct TypeMap<'ll, 'tcx> {
// The UniqueTypeIds created so far // The UniqueTypeIds created so far
unique_id_interner: Interner, unique_id_interner: Interner,
@ -108,15 +109,6 @@ pub struct TypeMap<'ll, 'tcx> {
} }
impl TypeMap<'ll, 'tcx> { impl TypeMap<'ll, 'tcx> {
pub fn new() -> Self {
TypeMap {
unique_id_interner: Interner::new(),
type_to_metadata: FxHashMap::default(),
unique_id_to_metadata: FxHashMap::default(),
type_to_unique_id: FxHashMap::default(),
}
}
// Adds a Ty to metadata mapping to the TypeMap. The method will fail if // Adds a Ty to metadata mapping to the TypeMap. The method will fail if
// the mapping already exists. // the mapping already exists.
fn register_type_with_metadata( fn register_type_with_metadata(

View file

@ -100,11 +100,11 @@ impl<'a, 'tcx> CrateDebugContext<'a, 'tcx> {
llcontext, llcontext,
llmod, llmod,
builder, builder,
created_files: RefCell::new(FxHashMap::default()), created_files: Default::default(),
created_enum_disr_types: RefCell::new(FxHashMap::default()), created_enum_disr_types: Default::default(),
type_map: RefCell::new(TypeMap::new()), type_map: Default::default(),
namespace_map: RefCell::new(DefIdMap()), namespace_map: RefCell::new(DefIdMap()),
composite_types_completed: RefCell::new(FxHashSet::default()), composite_types_completed: Default::default(),
} }
} }
} }

View file

@ -28,7 +28,6 @@ use std::path::Path;
use std::sync::{mpsc, Arc}; use std::sync::{mpsc, Arc};
use rustc_data_structures::owning_ref::OwningRef; use rustc_data_structures::owning_ref::OwningRef;
use rustc_data_structures::sync::Lrc;
use flate2::Compression; use flate2::Compression;
use flate2::write::DeflateEncoder; use flate2::write::DeflateEncoder;
@ -42,7 +41,6 @@ use rustc::middle::cstore::EncodedMetadata;
use rustc::middle::cstore::MetadataLoader; use rustc::middle::cstore::MetadataLoader;
use rustc::dep_graph::DepGraph; use rustc::dep_graph::DepGraph;
use rustc_target::spec::Target; use rustc_target::spec::Target;
use rustc_data_structures::fx::FxHashMap;
use rustc_mir::monomorphize::collector; use rustc_mir::monomorphize::collector;
use link::out_filename; use link::out_filename;
@ -132,7 +130,7 @@ impl CodegenBackend for MetadataOnlyCodegenBackend {
::symbol_names::provide(providers); ::symbol_names::provide(providers);
providers.target_features_whitelist = |_tcx, _cnum| { providers.target_features_whitelist = |_tcx, _cnum| {
Lrc::new(FxHashMap::default()) // Just a dummy Default::default() // Just a dummy
}; };
providers.is_reachable_non_generic = |_tcx, _defid| true; providers.is_reachable_non_generic = |_tcx, _defid| true;
providers.exported_symbols = |_tcx, _crate| Arc::new(Vec::new()); providers.exported_symbols = |_tcx, _crate| Arc::new(Vec::new());

View file

@ -187,11 +187,11 @@ impl<O: ForestObligation> ObligationForest<O> {
pub fn new() -> ObligationForest<O> { pub fn new() -> ObligationForest<O> {
ObligationForest { ObligationForest {
nodes: vec![], nodes: vec![],
done_cache: FxHashSet::default(), done_cache: Default::default(),
waiting_cache: FxHashMap::default(), waiting_cache: Default::default(),
scratch: Some(vec![]), scratch: Some(vec![]),
obligation_tree_id_generator: (0..).map(|i| ObligationTreeId(i)), obligation_tree_id_generator: (0..).map(|i| ObligationTreeId(i)),
error_cache: FxHashMap::default(), error_cache: Default::default(),
} }
} }
@ -303,7 +303,7 @@ impl<O: ForestObligation> ObligationForest<O> {
self.error_cache self.error_cache
.entry(node.obligation_tree_id) .entry(node.obligation_tree_id)
.or_insert_with(|| FxHashSet::default()) .or_default()
.insert(node.obligation.as_predicate().clone()); .insert(node.obligation.as_predicate().clone());
} }

View file

@ -35,16 +35,20 @@ enum UndoLog<K, V> {
Noop, Noop,
} }
impl<K, V> SnapshotMap<K, V> impl<K, V> Default for SnapshotMap<K, V>
where K: Hash + Clone + Eq where K: Hash + Clone + Eq
{ {
pub fn new() -> Self { fn default() -> Self {
SnapshotMap { SnapshotMap {
map: FxHashMap::default(), map: FxHashMap::default(),
undo_log: vec![], undo_log: vec![],
} }
} }
}
impl<K, V> SnapshotMap<K, V>
where K: Hash + Clone + Eq
{
pub fn clear(&mut self) { pub fn clear(&mut self) {
self.map.clear(); self.map.clear();
self.undo_log.clear(); self.undo_log.clear();

View file

@ -133,7 +133,7 @@ cfg_if! {
pub type MTRef<'a, T> = &'a mut T; pub type MTRef<'a, T> = &'a mut T;
#[derive(Debug)] #[derive(Debug, Default)]
pub struct MTLock<T>(T); pub struct MTLock<T>(T);
impl<T> MTLock<T> { impl<T> MTLock<T> {
@ -228,7 +228,7 @@ cfg_if! {
pub type MTRef<'a, T> = &'a T; pub type MTRef<'a, T> = &'a T;
#[derive(Debug)] #[derive(Debug, Default)]
pub struct MTLock<T>(Lock<T>); pub struct MTLock<T>(Lock<T>);
impl<T> MTLock<T> { impl<T> MTLock<T> {

View file

@ -51,8 +51,8 @@ struct Edge {
target: Index, target: Index,
} }
impl<T: Clone + Debug + Eq + Hash> TransitiveRelation<T> { impl<T: Clone + Debug + Eq + Hash> Default for TransitiveRelation<T> {
pub fn new() -> TransitiveRelation<T> { fn default() -> TransitiveRelation<T> {
TransitiveRelation { TransitiveRelation {
elements: vec![], elements: vec![],
map: FxHashMap::default(), map: FxHashMap::default(),
@ -60,7 +60,9 @@ impl<T: Clone + Debug + Eq + Hash> TransitiveRelation<T> {
closure: Lock::new(None), closure: Lock::new(None),
} }
} }
}
impl<T: Clone + Debug + Eq + Hash> TransitiveRelation<T> {
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
self.edges.is_empty() self.edges.is_empty()
} }
@ -95,7 +97,7 @@ impl<T: Clone + Debug + Eq + Hash> TransitiveRelation<T> {
where F: FnMut(&T) -> Option<U>, where F: FnMut(&T) -> Option<U>,
U: Clone + Debug + Eq + Hash + Clone, U: Clone + Debug + Eq + Hash + Clone,
{ {
let mut result = TransitiveRelation::new(); let mut result = TransitiveRelation::default();
for edge in &self.edges { for edge in &self.edges {
result.add(f(&self.elements[edge.source.0])?, f(&self.elements[edge.target.0])?); result.add(f(&self.elements[edge.source.0])?, f(&self.elements[edge.target.0])?);
} }

View file

@ -382,9 +382,9 @@ impl Handler {
emitter: Lock::new(e), emitter: Lock::new(e),
continue_after_error: LockCell::new(true), continue_after_error: LockCell::new(true),
delayed_span_bugs: Lock::new(Vec::new()), delayed_span_bugs: Lock::new(Vec::new()),
taught_diagnostics: Lock::new(FxHashSet::default()), taught_diagnostics: Default::default(),
emitted_diagnostic_codes: Lock::new(FxHashSet::default()), emitted_diagnostic_codes: Default::default(),
emitted_diagnostics: Lock::new(FxHashSet::default()), emitted_diagnostics: Default::default(),
} }
} }
@ -398,7 +398,7 @@ impl Handler {
/// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
/// the overall count of emitted error diagnostics. /// the overall count of emitted error diagnostics.
pub fn reset_err_count(&self) { pub fn reset_err_count(&self) {
*self.emitted_diagnostics.borrow_mut() = FxHashSet::default(); self.emitted_diagnostics.borrow_mut().clear();
self.err_count.store(0, SeqCst); self.err_count.store(0, SeqCst);
} }

View file

@ -226,7 +226,7 @@ pub fn check_dirty_clean_annotations<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
let krate = tcx.hir.krate(); let krate = tcx.hir.krate();
let mut dirty_clean_visitor = DirtyCleanVisitor { let mut dirty_clean_visitor = DirtyCleanVisitor {
tcx, tcx,
checked_attrs: FxHashSet::default(), checked_attrs: Default::default(),
}; };
krate.visit_all_item_likes(&mut dirty_clean_visitor); krate.visit_all_item_likes(&mut dirty_clean_visitor);

View file

@ -48,7 +48,7 @@ impl LoadResult<(PreviousDepGraph, WorkProductMap)> {
match self { match self {
LoadResult::Error { message } => { LoadResult::Error { message } => {
sess.warn(&message); sess.warn(&message);
(PreviousDepGraph::new(SerializedDepGraph::new()), FxHashMap::default()) Default::default()
}, },
LoadResult::DataOutOfDate => { LoadResult::DataOutOfDate => {
if let Err(err) = delete_all_session_dir_contents(sess) { if let Err(err) = delete_all_session_dir_contents(sess) {
@ -56,7 +56,7 @@ impl LoadResult<(PreviousDepGraph, WorkProductMap)> {
incremental compilation session directory contents `{}`: {}.", incremental compilation session directory contents `{}`: {}.",
dep_graph_path(sess).display(), err)); dep_graph_path(sess).display(), err));
} }
(PreviousDepGraph::new(SerializedDepGraph::new()), FxHashMap::default()) Default::default()
} }
LoadResult::Ok { data } => data LoadResult::Ok { data } => data
} }
@ -117,7 +117,7 @@ pub fn load_dep_graph(sess: &Session) ->
if sess.opts.incremental.is_none() { if sess.opts.incremental.is_none() {
// No incremental compilation. // No incremental compilation.
return MaybeAsync::Sync(LoadResult::Ok { return MaybeAsync::Sync(LoadResult::Ok {
data: (PreviousDepGraph::new(SerializedDepGraph::new()), FxHashMap::default()) data: Default::default(),
}); });
} }

View file

@ -111,7 +111,7 @@ impl CStore {
// corresponding `CrateNum`. This first entry will always remain // corresponding `CrateNum`. This first entry will always remain
// `None`. // `None`.
metas: RwLock::new(IndexVec::from_elem_n(None, 1)), metas: RwLock::new(IndexVec::from_elem_n(None, 1)),
extern_mod_crate_map: Lock::new(FxHashMap::default()), extern_mod_crate_map: Default::default(),
metadata_loader, metadata_loader,
} }
} }

View file

@ -459,7 +459,7 @@ impl<'a> Context<'a> {
let mut candidates: FxHashMap< let mut candidates: FxHashMap<
_, _,
(FxHashMap<_, _>, FxHashMap<_, _>, FxHashMap<_, _>), (FxHashMap<_, _>, FxHashMap<_, _>, FxHashMap<_, _>),
> = FxHashMap::default(); > = Default::default();
let mut staticlibs = vec![]; let mut staticlibs = vec![];
// First, find all possible candidate rlibs and dylibs purely based on // First, find all possible candidate rlibs and dylibs purely based on

View file

@ -151,11 +151,11 @@ impl<'tcx> BorrowSet<'tcx> {
tcx, tcx,
mir, mir,
idx_vec: IndexVec::new(), idx_vec: IndexVec::new(),
location_map: FxHashMap::default(), location_map: Default::default(),
activation_map: FxHashMap::default(), activation_map: Default::default(),
region_map: FxHashMap::default(), region_map: Default::default(),
local_map: FxHashMap::default(), local_map: Default::default(),
pending_activations: FxHashMap::default(), pending_activations: Default::default(),
locals_state_at_exit: locals_state_at_exit:
LocalsStateAtExit::build(locals_are_invalidated_at_exit, mir, move_data), LocalsStateAtExit::build(locals_are_invalidated_at_exit, mir, move_data),
}; };

View file

@ -252,13 +252,13 @@ fn do_mir_borrowck<'a, 'gcx, 'tcx>(
location_table, location_table,
movable_generator, movable_generator,
locals_are_invalidated_at_exit, locals_are_invalidated_at_exit,
access_place_error_reported: FxHashSet::default(), access_place_error_reported: Default::default(),
reservation_error_reported: FxHashSet::default(), reservation_error_reported: Default::default(),
move_error_reported: BTreeMap::new(), move_error_reported: BTreeMap::new(),
uninitialized_error_reported: FxHashSet::default(), uninitialized_error_reported: Default::default(),
errors_buffer, errors_buffer,
nonlexical_regioncx: regioncx, nonlexical_regioncx: regioncx,
used_mut: FxHashSet::default(), used_mut: Default::default(),
used_mut_upvars: SmallVec::new(), used_mut_upvars: SmallVec::new(),
borrow_set, borrow_set,
dominators, dominators,

View file

@ -80,8 +80,8 @@ crate fn create(
region_bound_pairs: Vec::new(), region_bound_pairs: Vec::new(),
relations: UniversalRegionRelations { relations: UniversalRegionRelations {
universal_regions: universal_regions.clone(), universal_regions: universal_regions.clone(),
outlives: TransitiveRelation::new(), outlives: Default::default(),
inverse_outlives: TransitiveRelation::new(), inverse_outlives: Default::default(),
}, },
}.create() }.create()
} }

View file

@ -128,7 +128,7 @@ pub(crate) fn type_check<'gcx, 'tcx>(
let mut constraints = MirTypeckRegionConstraints { let mut constraints = MirTypeckRegionConstraints {
liveness_constraints: LivenessValues::new(elements), liveness_constraints: LivenessValues::new(elements),
outlives_constraints: ConstraintSet::default(), outlives_constraints: ConstraintSet::default(),
closure_bounds_mapping: FxHashMap::default(), closure_bounds_mapping: Default::default(),
type_tests: Vec::default(), type_tests: Vec::default(),
}; };
let mut placeholder_indices = PlaceholderIndices::default(); let mut placeholder_indices = PlaceholderIndices::default();
@ -847,7 +847,7 @@ impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
region_bound_pairs, region_bound_pairs,
implicit_region_bound, implicit_region_bound,
borrowck_context, borrowck_context,
reported_errors: FxHashSet::default(), reported_errors: Default::default(),
universal_region_relations, universal_region_relations,
} }
} }

View file

@ -55,7 +55,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
// these maps are empty to start; cases are // these maps are empty to start; cases are
// added below in add_cases_to_switch // added below in add_cases_to_switch
options: vec![], options: vec![],
indices: FxHashMap::default(), indices: Default::default(),
} }
} }
} }

View file

@ -358,7 +358,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
needs_cleanup: false, needs_cleanup: false,
drops: vec![], drops: vec![],
cached_generator_drop: None, cached_generator_drop: None,
cached_exits: FxHashMap::default(), cached_exits: Default::default(),
cached_unwind: CachedBlock::default(), cached_unwind: CachedBlock::default(),
}); });
} }

View file

@ -11,7 +11,6 @@
use rustc::ty::{self, TyCtxt}; use rustc::ty::{self, TyCtxt};
use rustc::mir::*; use rustc::mir::*;
use rustc::mir::tcx::RvalueInitializationState; use rustc::mir::tcx::RvalueInitializationState;
use rustc::util::nodemap::FxHashMap;
use rustc_data_structures::indexed_vec::{IndexVec}; use rustc_data_structures::indexed_vec::{IndexVec};
use std::collections::hash_map::Entry; use std::collections::hash_map::Entry;
@ -53,7 +52,7 @@ impl<'a, 'gcx, 'tcx> MoveDataBuilder<'a, 'gcx, 'tcx> {
v, v,
) )
}).collect(), }).collect(),
projections: FxHashMap::default(), projections: Default::default(),
}, },
move_paths, move_paths,
path_map, path_map,

View file

@ -320,7 +320,7 @@ impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> {
f: F) -> R f: F) -> R
where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R where F: for<'b> FnOnce(MatchCheckCtxt<'b, 'tcx>) -> R
{ {
let pattern_arena = TypedArena::new(); let pattern_arena = TypedArena::default();
f(MatchCheckCtxt { f(MatchCheckCtxt {
tcx, tcx,

View file

@ -703,7 +703,7 @@ fn internalize_symbols<'a, 'tcx>(_tcx: TyCtxt<'a, 'tcx, 'tcx>,
// Build a map from every monomorphization to all the monomorphizations that // Build a map from every monomorphization to all the monomorphizations that
// reference it. // reference it.
let mut accessor_map: FxHashMap<MonoItem<'tcx>, Vec<MonoItem<'tcx>>> = FxHashMap::default(); let mut accessor_map: FxHashMap<MonoItem<'tcx>, Vec<MonoItem<'tcx>>> = Default::default();
inlining_map.iter_accesses(|accessor, accessees| { inlining_map.iter_accesses(|accessor, accessees| {
for accessee in accessees { for accessee in accessees {
accessor_map.entry(*accessee) accessor_map.entry(*accessee)

View file

@ -57,7 +57,7 @@ impl<'a, 'gcx, 'tcx> UnsafetyChecker<'a, 'tcx> {
}, },
tcx, tcx,
param_env, param_env,
used_unsafe: FxHashSet::default(), used_unsafe: Default::default(),
inherited_blocks: vec![], inherited_blocks: vec![],
} }
} }

View file

@ -41,6 +41,7 @@ use transform::{MirPass, MirSource};
pub struct CleanEndRegions; pub struct CleanEndRegions;
#[derive(Default)]
struct GatherBorrowedRegions { struct GatherBorrowedRegions {
seen_regions: FxHashSet<region::Scope>, seen_regions: FxHashSet<region::Scope>,
} }
@ -56,9 +57,7 @@ impl MirPass for CleanEndRegions {
mir: &mut Mir<'tcx>) { mir: &mut Mir<'tcx>) {
if !tcx.emit_end_regions() { return; } if !tcx.emit_end_regions() { return; }
let mut gather = GatherBorrowedRegions { let mut gather = GatherBorrowedRegions::default();
seen_regions: FxHashSet::default()
};
gather.visit_mir(mir); gather.visit_mir(mir);
let mut delete = DeleteTrivialEndRegions { seen_regions: &mut gather.seen_regions }; let mut delete = DeleteTrivialEndRegions { seen_regions: &mut gather.seen_regions };
@ -139,6 +138,7 @@ impl<'tcx> MutVisitor<'tcx> for DeleteAscribeUserType {
pub struct CleanFakeReadsAndBorrows; pub struct CleanFakeReadsAndBorrows;
#[derive(Default)]
pub struct DeleteAndRecordFakeReads { pub struct DeleteAndRecordFakeReads {
fake_borrow_temporaries: FxHashSet<Local>, fake_borrow_temporaries: FxHashSet<Local>,
} }
@ -153,9 +153,7 @@ impl MirPass for CleanFakeReadsAndBorrows {
_tcx: TyCtxt<'a, 'tcx, 'tcx>, _tcx: TyCtxt<'a, 'tcx, 'tcx>,
_source: MirSource, _source: MirSource,
mir: &mut Mir<'tcx>) { mir: &mut Mir<'tcx>) {
let mut delete_reads = DeleteAndRecordFakeReads { let mut delete_reads = DeleteAndRecordFakeReads::default();
fake_borrow_temporaries: FxHashSet::default(),
};
delete_reads.visit_mir(mir); delete_reads.visit_mir(mir);
let mut delete_borrows = DeleteFakeBorrows { let mut delete_borrows = DeleteFakeBorrows {
fake_borrow_temporaries: delete_reads.fake_borrow_temporaries, fake_borrow_temporaries: delete_reads.fake_borrow_temporaries,

View file

@ -75,7 +75,7 @@ impl MirPass for ElaborateDrops {
env: &env, env: &env,
flow_inits, flow_inits,
flow_uninits, flow_uninits,
drop_flags: FxHashMap::default(), drop_flags: Default::default(),
patch: MirPatch::new(mir), patch: MirPatch::new(mir),
}.elaborate() }.elaborate()
}; };

View file

@ -536,7 +536,7 @@ pub fn write_mir_intro<'a, 'gcx, 'tcx>(
writeln!(w, "{{")?; writeln!(w, "{{")?;
// construct a scope tree and write it out // construct a scope tree and write it out
let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = FxHashMap::default(); let mut scope_tree: FxHashMap<SourceScope, Vec<SourceScope>> = Default::default();
for (index, scope_data) in mir.source_scopes.iter().enumerate() { for (index, scope_data) in mir.source_scopes.iter().enumerate() {
if let Some(parent) = scope_data.parent_scope { if let Some(parent) = scope_data.parent_scope {
scope_tree scope_tree

View file

@ -930,7 +930,7 @@ struct Rib<'a> {
impl<'a> Rib<'a> { impl<'a> Rib<'a> {
fn new(kind: RibKind<'a>) -> Rib<'a> { fn new(kind: RibKind<'a>) -> Rib<'a> {
Rib { Rib {
bindings: FxHashMap::default(), bindings: Default::default(),
kind, kind,
} }
} }
@ -1053,11 +1053,11 @@ impl<'a> ModuleData<'a> {
parent, parent,
kind, kind,
normal_ancestor_id, normal_ancestor_id,
resolutions: RefCell::new(FxHashMap::default()), resolutions: Default::default(),
legacy_macro_resolutions: RefCell::new(Vec::new()), legacy_macro_resolutions: RefCell::new(Vec::new()),
macro_resolutions: RefCell::new(Vec::new()), macro_resolutions: RefCell::new(Vec::new()),
builtin_attrs: RefCell::new(Vec::new()), builtin_attrs: RefCell::new(Vec::new()),
unresolved_invocations: RefCell::new(FxHashSet::default()), unresolved_invocations: Default::default(),
no_implicit_prelude: false, no_implicit_prelude: false,
glob_importers: RefCell::new(Vec::new()), glob_importers: RefCell::new(Vec::new()),
globs: RefCell::new(Vec::new()), globs: RefCell::new(Vec::new()),
@ -1315,13 +1315,14 @@ impl<'a> NameBinding<'a> {
/// ///
/// All other types are defined somewhere and possibly imported, but the primitive ones need /// All other types are defined somewhere and possibly imported, but the primitive ones need
/// special handling, since they have no place of origin. /// special handling, since they have no place of origin.
#[derive(Default)]
struct PrimitiveTypeTable { struct PrimitiveTypeTable {
primitive_types: FxHashMap<Name, PrimTy>, primitive_types: FxHashMap<Name, PrimTy>,
} }
impl PrimitiveTypeTable { impl PrimitiveTypeTable {
fn new() -> PrimitiveTypeTable { fn new() -> PrimitiveTypeTable {
let mut table = PrimitiveTypeTable { primitive_types: FxHashMap::default() }; let mut table = PrimitiveTypeTable::default();
table.intern("bool", Bool); table.intern("bool", Bool);
table.intern("char", Char); table.intern("char", Char);
@ -1482,6 +1483,7 @@ pub struct Resolver<'a, 'b: 'a> {
} }
/// Nothing really interesting here, it just provides memory for the rest of the crate. /// Nothing really interesting here, it just provides memory for the rest of the crate.
#[derive(Default)]
pub struct ResolverArenas<'a> { pub struct ResolverArenas<'a> {
modules: arena::TypedArena<ModuleData<'a>>, modules: arena::TypedArena<ModuleData<'a>>,
local_modules: RefCell<Vec<Module<'a>>>, local_modules: RefCell<Vec<Module<'a>>>,
@ -1782,15 +1784,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> {
} }
pub fn arenas() -> ResolverArenas<'a> { pub fn arenas() -> ResolverArenas<'a> {
ResolverArenas { Default::default()
modules: arena::TypedArena::new(),
local_modules: RefCell::new(Vec::new()),
name_bindings: arena::TypedArena::new(),
import_directives: arena::TypedArena::new(),
name_resolutions: arena::TypedArena::new(),
invocation_data: arena::TypedArena::new(),
legacy_bindings: arena::TypedArena::new(),
}
} }
/// Runs the function on each namespace. /// Runs the function on each namespace.

View file

@ -475,6 +475,7 @@ fn check_where_clauses<'a, 'gcx, 'fcx, 'tcx>(
}); });
// Now we build the substituted predicates. // Now we build the substituted predicates.
let default_obligations = predicates.predicates.iter().flat_map(|&(pred, _)| { let default_obligations = predicates.predicates.iter().flat_map(|&(pred, _)| {
#[derive(Default)]
struct CountParams { params: FxHashSet<u32> } struct CountParams { params: FxHashSet<u32> }
impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams { impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
fn visit_ty(&mut self, t: Ty<'tcx>) -> bool { fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
@ -491,7 +492,7 @@ fn check_where_clauses<'a, 'gcx, 'fcx, 'tcx>(
true true
} }
} }
let mut param_count = CountParams { params: FxHashSet::default() }; let mut param_count = CountParams::default();
let has_region = pred.visit_with(&mut param_count); let has_region = pred.visit_with(&mut param_count);
let substituted_pred = pred.subst(fcx.tcx, substs); let substituted_pred = pred.subst(fcx.tcx, substs);
// Don't check non-defaulted params, dependent defaults (including lifetimes) // Don't check non-defaulted params, dependent defaults (including lifetimes)

View file

@ -561,7 +561,7 @@ fn convert_variant<'a, 'tcx>(
adt_kind: ty::AdtKind, adt_kind: ty::AdtKind,
attribute_def_id: DefId attribute_def_id: DefId
) -> ty::VariantDef { ) -> ty::VariantDef {
let mut seen_fields: FxHashMap<ast::Ident, Span> = FxHashMap::default(); let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
let node_id = tcx.hir.as_local_node_id(did).unwrap(); let node_id = tcx.hir.as_local_node_id(did).unwrap();
let fields = def let fields = def
.fields() .fields()

View file

@ -48,7 +48,7 @@ pub fn provide(providers: &mut Providers) {
fn crate_variances<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) fn crate_variances<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum)
-> Lrc<CrateVariancesMap> { -> Lrc<CrateVariancesMap> {
assert_eq!(crate_num, LOCAL_CRATE); assert_eq!(crate_num, LOCAL_CRATE);
let mut arena = arena::TypedArena::new(); let mut arena = arena::TypedArena::default();
let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &mut arena); let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &mut arena);
let constraints_cx = constraints::add_constraints_from_crate(terms_cx); let constraints_cx = constraints::add_constraints_from_crate(terms_cx);
Lrc::new(solve::solve_constraints(constraints_cx)) Lrc::new(solve::solve_constraints(constraints_cx))

View file

@ -178,7 +178,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> AutoTraitFinder<'a, 'tcx, 'rcx, 'cstore> {
inner: ImplItem(Impl { inner: ImplItem(Impl {
unsafety: hir::Unsafety::Normal, unsafety: hir::Unsafety::Normal,
generics: new_generics, generics: new_generics,
provided_trait_methods: FxHashSet::default(), provided_trait_methods: Default::default(),
trait_: Some(trait_.clean(self.cx)), trait_: Some(trait_.clean(self.cx)),
for_: ty.clean(self.cx), for_: ty.clean(self.cx),
items: Vec::new(), items: Vec::new(),
@ -267,9 +267,9 @@ impl<'a, 'tcx, 'rcx, 'cstore> AutoTraitFinder<'a, 'tcx, 'rcx, 'cstore> {
// all intermediate RegionVids. At the end, all constraints should // all intermediate RegionVids. At the end, all constraints should
// be between Regions (aka region variables). This gives us the information // be between Regions (aka region variables). This gives us the information
// we need to create the Generics. // we need to create the Generics.
let mut finished: FxHashMap<_, Vec<_>> = FxHashMap::default(); let mut finished: FxHashMap<_, Vec<_>> = Default::default();
let mut vid_map: FxHashMap<RegionTarget, RegionDeps> = FxHashMap::default(); let mut vid_map: FxHashMap<RegionTarget, RegionDeps> = Default::default();
// Flattening is done in two parts. First, we insert all of the constraints // Flattening is done in two parts. First, we insert all of the constraints
// into a map. Each RegionTarget (either a RegionVid or a Region) maps // into a map. Each RegionTarget (either a RegionVid or a Region) maps
@ -577,11 +577,11 @@ impl<'a, 'tcx, 'rcx, 'cstore> AutoTraitFinder<'a, 'tcx, 'rcx, 'cstore> {
} = full_generics.clean(self.cx); } = full_generics.clean(self.cx);
let mut has_sized = FxHashSet::default(); let mut has_sized = FxHashSet::default();
let mut ty_to_bounds: FxHashMap<_, FxHashSet<_>> = FxHashMap::default(); let mut ty_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
let mut lifetime_to_bounds: FxHashMap<_, FxHashSet<_>> = FxHashMap::default(); let mut lifetime_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
let mut ty_to_traits: FxHashMap<Type, FxHashSet<Type>> = FxHashMap::default(); let mut ty_to_traits: FxHashMap<Type, FxHashSet<Type>> = Default::default();
let mut ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)> = FxHashMap::default(); let mut ty_to_fn: FxHashMap<Type, (Option<PolyTrait>, Option<Type>)> = Default::default();
for (orig_p, p) in clean_where_predicates { for (orig_p, p) in clean_where_predicates {
match p { match p {

View file

@ -368,7 +368,7 @@ pub fn build_impl(cx: &DocContext, did: DefId, ret: &mut Vec<clean::Item>) {
.into_iter() .into_iter()
.map(|meth| meth.ident.to_string()) .map(|meth| meth.ident.to_string())
.collect() .collect()
}).unwrap_or(FxHashSet::default()); }).unwrap_or_default();
debug!("build_impl: impl {:?} for {:?}", trait_.def_id(), for_.def_id()); debug!("build_impl: impl {:?} for {:?}", trait_.def_id(), for_.def_id());

View file

@ -75,8 +75,7 @@ use self::cfg::Cfg;
use self::auto_trait::AutoTraitFinder; use self::auto_trait::AutoTraitFinder;
use self::blanket_impl::BlanketImplFinder; use self::blanket_impl::BlanketImplFinder;
thread_local!(pub static MAX_DEF_ID: RefCell<FxHashMap<CrateNum, DefId>> = thread_local!(pub static MAX_DEF_ID: RefCell<FxHashMap<CrateNum, DefId>> = Default::default());
RefCell::new(FxHashMap::default()));
const FN_OUTPUT_NAME: &'static str = "Output"; const FN_OUTPUT_NAME: &'static str = "Output";
@ -3388,7 +3387,7 @@ impl Clean<Vec<Item>> for doctree::Impl {
.into_iter() .into_iter()
.map(|meth| meth.ident.to_string()) .map(|meth| meth.ident.to_string())
.collect() .collect()
}).unwrap_or(FxHashSet::default()); }).unwrap_or_default();
ret.push(Item { ret.push(Item {
name: None, name: None,

View file

@ -539,9 +539,9 @@ pub fn run_core(search_paths: SearchPaths,
lt_substs: Default::default(), lt_substs: Default::default(),
impl_trait_bounds: Default::default(), impl_trait_bounds: Default::default(),
send_trait: send_trait, send_trait: send_trait,
fake_def_ids: RefCell::new(FxHashMap::default()), fake_def_ids: Default::default(),
all_fake_def_ids: RefCell::new(FxHashSet::default()), all_fake_def_ids: Default::default(),
generated_synthetics: RefCell::new(FxHashSet::default()), generated_synthetics: Default::default(),
all_traits: tcx.all_traits(LOCAL_CRATE).to_vec(), all_traits: tcx.all_traits(LOCAL_CRATE).to_vec(),
}; };
debug!("crate: {:?}", tcx.hir.krate()); debug!("crate: {:?}", tcx.hir.krate());

View file

@ -513,7 +513,7 @@ pub fn run(mut krate: clean::Crate,
src_root, src_root,
passes, passes,
include_sources: true, include_sources: true,
local_sources: FxHashMap::default(), local_sources: Default::default(),
issue_tracker_base_url: None, issue_tracker_base_url: None,
layout: layout::Layout { layout: layout::Layout {
logo: String::new(), logo: String::new(),
@ -522,7 +522,7 @@ pub fn run(mut krate: clean::Crate,
krate: krate.name.clone(), krate: krate.name.clone(),
}, },
css_file_extension: css_file_extension.clone(), css_file_extension: css_file_extension.clone(),
created_dirs: RefCell::new(FxHashSet::default()), created_dirs: Default::default(),
sort_modules_alphabetically, sort_modules_alphabetically,
themes, themes,
resource_suffix, resource_suffix,
@ -591,29 +591,29 @@ pub fn run(mut krate: clean::Crate,
.collect(); .collect();
let mut cache = Cache { let mut cache = Cache {
impls: FxHashMap::default(), impls: Default::default(),
external_paths, external_paths,
exact_paths, exact_paths,
paths: FxHashMap::default(), paths: Default::default(),
implementors: FxHashMap::default(), implementors: Default::default(),
stack: Vec::new(), stack: Vec::new(),
parent_stack: Vec::new(), parent_stack: Vec::new(),
search_index: Vec::new(), search_index: Vec::new(),
parent_is_trait_impl: false, parent_is_trait_impl: false,
extern_locations: FxHashMap::default(), extern_locations: Default::default(),
primitive_locations: FxHashMap::default(), primitive_locations: Default::default(),
stripped_mod: false, stripped_mod: false,
access_levels, access_levels,
crate_version: krate.version.take(), crate_version: krate.version.take(),
orphan_impl_items: Vec::new(), orphan_impl_items: Vec::new(),
orphan_trait_impls: Vec::new(), orphan_trait_impls: Vec::new(),
traits: krate.external_traits.lock().replace(FxHashMap::default()), traits: krate.external_traits.lock().replace(Default::default()),
deref_trait_did, deref_trait_did,
deref_mut_trait_did, deref_mut_trait_did,
owned_box_did, owned_box_did,
masked_crates: mem::replace(&mut krate.masked_crates, FxHashSet::default()), masked_crates: mem::replace(&mut krate.masked_crates, Default::default()),
typarams: external_typarams, typarams: external_typarams,
aliases: FxHashMap::default(), aliases: Default::default(),
}; };
// Cache where all our extern crates are located // Cache where all our extern crates are located

View file

@ -124,6 +124,7 @@ impl StableFilemapId {
// SourceMap // SourceMap
// //
#[derive(Default)]
pub(super) struct SourceMapFiles { pub(super) struct SourceMapFiles {
pub(super) file_maps: Vec<Lrc<SourceFile>>, pub(super) file_maps: Vec<Lrc<SourceFile>>,
stable_id_to_source_file: FxHashMap<StableFilemapId, Lrc<SourceFile>> stable_id_to_source_file: FxHashMap<StableFilemapId, Lrc<SourceFile>>
@ -143,10 +144,7 @@ pub struct SourceMap {
impl SourceMap { impl SourceMap {
pub fn new(path_mapping: FilePathMapping) -> SourceMap { pub fn new(path_mapping: FilePathMapping) -> SourceMap {
SourceMap { SourceMap {
files: Lock::new(SourceMapFiles { files: Default::default(),
file_maps: Vec::new(),
stable_id_to_source_file: FxHashMap::default(),
}),
file_loader: Box::new(RealFileLoader), file_loader: Box::new(RealFileLoader),
path_mapping, path_mapping,
doctest_offset: None, doctest_offset: None,
@ -166,10 +164,7 @@ impl SourceMap {
path_mapping: FilePathMapping) path_mapping: FilePathMapping)
-> SourceMap { -> SourceMap {
SourceMap { SourceMap {
files: Lock::new(SourceMapFiles { files: Default::default(),
file_maps: Vec::new(),
stable_id_to_source_file: FxHashMap::default(),
}),
file_loader: file_loader, file_loader: file_loader,
path_mapping, path_mapping,
doctest_offset: None, doctest_offset: None,

View file

@ -224,6 +224,7 @@ impl<T: ::std::ops::Deref<Target=str>> PartialEq<T> for Symbol {
} }
// The &'static strs in this type actually point into the arena // The &'static strs in this type actually point into the arena
#[derive(Default)]
pub struct Interner { pub struct Interner {
arena: DroplessArena, arena: DroplessArena,
names: FxHashMap<&'static str, Symbol>, names: FxHashMap<&'static str, Symbol>,
@ -232,17 +233,8 @@ pub struct Interner {
} }
impl Interner { impl Interner {
pub fn new() -> Self {
Interner {
arena: DroplessArena::new(),
names: Default::default(),
strings: Default::default(),
gensyms: Default::default(),
}
}
fn prefill(init: &[&str]) -> Self { fn prefill(init: &[&str]) -> Self {
let mut this = Interner::new(); let mut this = Interner::default();
for &string in init { for &string in init {
if string == "" { if string == "" {
// We can't allocate empty strings in the arena, so handle this here // We can't allocate empty strings in the arena, so handle this here
@ -697,7 +689,7 @@ mod tests {
#[test] #[test]
fn interner_tests() { fn interner_tests() {
let mut i: Interner = Interner::new(); let mut i: Interner = Interner::default();
// first one is zero: // first one is zero:
assert_eq!(i.intern("dog"), Symbol(0)); assert_eq!(i.intern("dog"), Symbol(0));
// re-use gets the same entry: // re-use gets the same entry: