diff --git a/src/Cargo.lock b/src/Cargo.lock index c22187ee13e8e..7756801a46c45 100644 --- a/src/Cargo.lock +++ b/src/Cargo.lock @@ -1392,6 +1392,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" name = "proc_macro" version = "0.0.0" dependencies = [ + "rustc_data_structures 0.0.0", "rustc_errors 0.0.0", "syntax 0.0.0", "syntax_pos 0.0.0", @@ -1753,6 +1754,7 @@ dependencies = [ "graphviz 0.0.0", "log 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", "rustc 0.0.0", + "rustc_data_structures 0.0.0", "rustc_errors 0.0.0", "rustc_mir 0.0.0", "syntax 0.0.0", @@ -1948,6 +1950,7 @@ dependencies = [ "rustc 0.0.0", "rustc_const_eval 0.0.0", "rustc_const_math 0.0.0", + "rustc_data_structures 0.0.0", "rustc_errors 0.0.0", "syntax 0.0.0", "syntax_pos 0.0.0", @@ -1973,6 +1976,7 @@ name = "rustc_privacy" version = "0.0.0" dependencies = [ "rustc 0.0.0", + "rustc_data_structures 0.0.0", "rustc_typeck 0.0.0", "syntax 0.0.0", "syntax_pos 0.0.0", @@ -2374,6 +2378,7 @@ version = "0.0.0" dependencies = [ "fmt_macros 0.0.0", "proc_macro 0.0.0", + "rustc_data_structures 0.0.0", "rustc_errors 0.0.0", "syntax 0.0.0", "syntax_pos 0.0.0", diff --git a/src/libproc_macro/Cargo.toml b/src/libproc_macro/Cargo.toml index cfd83e348a8e2..c1b2622520b11 100644 --- a/src/libproc_macro/Cargo.toml +++ b/src/libproc_macro/Cargo.toml @@ -11,3 +11,4 @@ crate-type = ["dylib"] syntax = { path = "../libsyntax" } syntax_pos = { path = "../libsyntax_pos" } rustc_errors = { path = "../librustc_errors" } +rustc_data_structures = { path = "../librustc_data_structures" } diff --git a/src/libproc_macro/lib.rs b/src/libproc_macro/lib.rs index 41ccd88b4a887..66fabcb73d95b 100644 --- a/src/libproc_macro/lib.rs +++ b/src/libproc_macro/lib.rs @@ -43,6 +43,7 @@ extern crate syntax; extern crate syntax_pos; extern crate rustc_errors; +extern crate rustc_data_structures; mod diagnostic; @@ -50,7 +51,7 @@ mod diagnostic; pub use diagnostic::{Diagnostic, Level}; use std::{ascii, fmt, iter}; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use std::str::FromStr; use syntax::ast; @@ -277,7 +278,7 @@ pub struct LineColumn { #[unstable(feature = "proc_macro", issue = "38356")] #[derive(Clone)] pub struct SourceFile { - filemap: Rc, + filemap: Lrc, } impl SourceFile { @@ -327,7 +328,7 @@ impl fmt::Debug for SourceFile { #[unstable(feature = "proc_macro", issue = "38356")] impl PartialEq for SourceFile { fn eq(&self, other: &Self) -> bool { - Rc::ptr_eq(&self.filemap, &other.filemap) + Lrc::ptr_eq(&self.filemap, &other.filemap) } } diff --git a/src/librustc/dep_graph/graph.rs b/src/librustc/dep_graph/graph.rs index 96d6b0f79cfff..6dd525f79580c 100644 --- a/src/librustc/dep_graph/graph.rs +++ b/src/librustc/dep_graph/graph.rs @@ -13,10 +13,9 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHashingContextProvider}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::indexed_vec::{Idx, IndexVec}; -use std::cell::{Ref, RefCell}; +use rustc_data_structures::sync::{Lrc, RwLock, ReadGuard, Lock}; use std::env; use std::hash::Hash; -use std::rc::Rc; use ty::TyCtxt; use util::common::{ProfileQueriesMsg, profq_msg}; @@ -32,7 +31,7 @@ use super::prev::PreviousDepGraph; #[derive(Clone)] pub struct DepGraph { - data: Option>, + data: Option>, // At the moment we are using DepNode as key here. In the future it might // be possible to use an IndexVec here. At the moment there @@ -41,7 +40,7 @@ pub struct DepGraph { // we need to have a dep-graph to generate DepNodeIndices. // - The architecture is still in flux and it's not clear what how to best // implement things. - fingerprints: Rc>> + fingerprints: Lrc>> } @@ -71,50 +70,50 @@ struct DepGraphData { /// tracking. The `current` field is the dependency graph of only the /// current compilation session: We don't merge the previous dep-graph into /// current one anymore. - current: RefCell, + current: Lock, /// The dep-graph from the previous compilation session. It contains all /// nodes and edges as well as all fingerprints of nodes that have them. previous: PreviousDepGraph, - colors: RefCell>, + colors: Lock>, /// When we load, there may be `.o` files, cached mir, or other such /// things available to us. If we find that they are not dirty, we /// load the path to the file storing those work-products here into /// this map. We can later look for and extract that data. - previous_work_products: RefCell>, + previous_work_products: RwLock>, /// Work-products that we generate in this run. - work_products: RefCell>, + work_products: RwLock>, - dep_node_debug: RefCell>, + dep_node_debug: Lock>, // Used for testing, only populated when -Zquery-dep-graph is specified. - loaded_from_cache: RefCell>, + loaded_from_cache: Lock>, } impl DepGraph { pub fn new(prev_graph: PreviousDepGraph) -> DepGraph { DepGraph { - data: Some(Rc::new(DepGraphData { - previous_work_products: RefCell::new(FxHashMap()), - work_products: RefCell::new(FxHashMap()), - dep_node_debug: RefCell::new(FxHashMap()), - current: RefCell::new(CurrentDepGraph::new()), + data: Some(Lrc::new(DepGraphData { + previous_work_products: RwLock::new(FxHashMap()), + work_products: RwLock::new(FxHashMap()), + dep_node_debug: Lock::new(FxHashMap()), + current: Lock::new(CurrentDepGraph::new()), previous: prev_graph, - colors: RefCell::new(FxHashMap()), - loaded_from_cache: RefCell::new(FxHashMap()), + colors: Lock::new(FxHashMap()), + loaded_from_cache: Lock::new(FxHashMap()), })), - fingerprints: Rc::new(RefCell::new(FxHashMap())), + fingerprints: Lrc::new(Lock::new(FxHashMap())), } } pub fn new_disabled() -> DepGraph { DepGraph { data: None, - fingerprints: Rc::new(RefCell::new(FxHashMap())), + fingerprints: Lrc::new(Lock::new(FxHashMap())), } } @@ -196,8 +195,8 @@ impl DepGraph { cx: C, arg: A, task: fn(C, A) -> R, - push: fn(&RefCell, DepNode), - pop: fn(&RefCell, DepNode) -> DepNodeIndex) + push: fn(&Lock, DepNode), + pop: fn(&Lock, DepNode) -> DepNodeIndex) -> (R, DepNodeIndex) where C: DepGraphSafe + StableHashingContextProvider, R: HashStable, @@ -384,13 +383,13 @@ impl DepGraph { /// Access the map of work-products created during this run. Only /// used during saving of the dep-graph. - pub fn work_products(&self) -> Ref> { + pub fn work_products(&self) -> ReadGuard> { self.data.as_ref().unwrap().work_products.borrow() } /// Access the map of work-products created during the cached run. Only /// used during saving of the dep-graph. - pub fn previous_work_products(&self) -> Ref> { + pub fn previous_work_products(&self) -> ReadGuard> { self.data.as_ref().unwrap().previous_work_products.borrow() } diff --git a/src/librustc/dep_graph/raii.rs b/src/librustc/dep_graph/raii.rs index 5728bcc7d2771..8bb8840836020 100644 --- a/src/librustc/dep_graph/raii.rs +++ b/src/librustc/dep_graph/raii.rs @@ -10,14 +10,14 @@ use super::graph::CurrentDepGraph; -use std::cell::RefCell; +use rustc_data_structures::sync::Lock; pub struct IgnoreTask<'graph> { - graph: &'graph RefCell, + graph: &'graph Lock, } impl<'graph> IgnoreTask<'graph> { - pub(super) fn new(graph: &'graph RefCell) -> IgnoreTask<'graph> { + pub(super) fn new(graph: &'graph Lock) -> IgnoreTask<'graph> { graph.borrow_mut().push_ignore(); IgnoreTask { graph, diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index 014e57716562c..84cb679303feb 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -29,9 +29,10 @@ use hir::print::Nested; use util::nodemap::{DefIdMap, FxHashMap}; use arena::TypedArena; -use std::cell::RefCell; use std::io; +use rustc_data_structures::sync::Lock; + pub mod blocks; mod collector; mod def_collector; @@ -255,7 +256,7 @@ pub struct Map<'hir> { definitions: &'hir Definitions, /// Bodies inlined from other crates are cached here. - inlined_bodies: RefCell>, + inlined_bodies: Lock>, /// The reverse mapping of `node_to_hir_id`. hir_to_node_id: FxHashMap, @@ -1090,7 +1091,7 @@ pub fn map_crate<'hir>(sess: &::session::Session, map, hir_to_node_id, definitions, - inlined_bodies: RefCell::new(DefIdMap()), + inlined_bodies: Lock::new(DefIdMap()), }; hir_id_validator::check_crate(&map); diff --git a/src/librustc/ich/caching_codemap_view.rs b/src/librustc/ich/caching_codemap_view.rs index 3caf308d65268..e5bf384d253c5 100644 --- a/src/librustc/ich/caching_codemap_view.rs +++ b/src/librustc/ich/caching_codemap_view.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use syntax::codemap::CodeMap; use syntax_pos::{BytePos, FileMap}; @@ -18,7 +18,7 @@ struct CacheEntry { line_number: usize, line_start: BytePos, line_end: BytePos, - file: Rc, + file: Lrc, file_index: usize, } @@ -51,7 +51,7 @@ impl<'cm> CachingCodemapView<'cm> { pub fn byte_pos_to_line_and_col(&mut self, pos: BytePos) - -> Option<(Rc, usize, BytePos)> { + -> Option<(Lrc, usize, BytePos)> { self.time_stamp += 1; // Check if the position is in one of the cached lines diff --git a/src/librustc/ich/hcx.rs b/src/librustc/ich/hcx.rs index 2945b1ab91245..f9b1eee4bf796 100644 --- a/src/librustc/ich/hcx.rs +++ b/src/librustc/ich/hcx.rs @@ -357,6 +357,8 @@ impl<'gcx> HashStable> for Span { // Since the same expansion context is usually referenced many // times, we cache a stable hash of it and hash that instead of // recursing every time. + use std::cell::RefCell; + // FIXME: Move this to Session or a syntax_pos global thread_local! { static CACHE: RefCell> = RefCell::new(FxHashMap()); diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index 32ab458cb91de..d60ee5f514678 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -27,6 +27,7 @@ use self::TargetLint::*; use std::slice; +use rustc_data_structures::sync::{RwLock, ReadGuard}; use lint::{EarlyLintPassObject, LateLintPassObject}; use lint::{Level, Lint, LintId, LintPass, LintBuffer}; use lint::levels::{LintLevelSets, LintLevelsBuilder}; @@ -39,7 +40,6 @@ use ty::layout::{LayoutError, LayoutOf, TyLayout}; use util::nodemap::FxHashMap; use std::default::Default as StdDefault; -use std::cell::{Ref, RefCell}; use syntax::ast; use syntax_pos::{MultiSpan, Span}; use errors::DiagnosticBuilder; @@ -77,7 +77,7 @@ pub struct LintStore { pub struct LintSession<'a, PassObject> { /// Reference to the store of registered lints. - lints: Ref<'a, LintStore>, + lints: ReadGuard<'a, LintStore>, /// Trait objects for each lint pass. passes: Option>, @@ -317,7 +317,7 @@ impl<'a, PassObject: LintPassObject> LintSession<'a, PassObject> { /// Creates a new `LintSession`, by moving out the `LintStore`'s initial /// lint levels and pass objects. These can be restored using the `restore` /// method. - fn new(store: &'a RefCell) -> LintSession<'a, PassObject> { + fn new(store: &'a RwLock) -> LintSession<'a, PassObject> { let mut s = store.borrow_mut(); let passes = PassObject::take_passes(&mut *s); drop(s); @@ -328,7 +328,7 @@ impl<'a, PassObject: LintPassObject> LintSession<'a, PassObject> { } /// Restores the levels back to the original lint store. - fn restore(self, store: &RefCell) { + fn restore(self, store: &RwLock) { drop(self.lints); let mut s = store.borrow_mut(); PassObject::restore_passes(&mut *s, self.passes); diff --git a/src/librustc/lint/mod.rs b/src/librustc/lint/mod.rs index f4abc54ad2e4e..42074d64d3c65 100644 --- a/src/librustc/lint/mod.rs +++ b/src/librustc/lint/mod.rs @@ -31,7 +31,7 @@ pub use self::Level::*; pub use self::LintSource::*; -use std::rc::Rc; +use rustc_data_structures::sync::{Send, Sync, Lrc}; use errors::{DiagnosticBuilder, DiagnosticId}; use hir::def_id::{CrateNum, LOCAL_CRATE}; @@ -257,8 +257,8 @@ pub trait EarlyLintPass: LintPass { } /// A lint pass boxed up as a trait object. -pub type EarlyLintPassObject = Box; -pub type LateLintPassObject = Box LateLintPass<'a, 'tcx> + 'static>; +pub type EarlyLintPassObject = Box; +pub type LateLintPassObject = Box LateLintPass<'a, 'tcx> + Send + Sync + 'static>; /// Identifies a lint known to the compiler. #[derive(Clone, Copy, Debug)] @@ -480,7 +480,7 @@ pub fn struct_lint_level<'a>(sess: &'a Session, } fn lint_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, cnum: CrateNum) - -> Rc + -> Lrc { assert_eq!(cnum, LOCAL_CRATE); let mut builder = LintLevelMapBuilder { @@ -493,7 +493,7 @@ fn lint_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, cnum: CrateNum) intravisit::walk_crate(builder, krate); }); - Rc::new(builder.levels.build_map()) + Lrc::new(builder.levels.build_map()) } struct LintLevelMapBuilder<'a, 'tcx: 'a> { diff --git a/src/librustc/middle/cstore.rs b/src/librustc/middle/cstore.rs index 9708afd204593..ea11930ae89d4 100644 --- a/src/librustc/middle/cstore.rs +++ b/src/librustc/middle/cstore.rs @@ -37,13 +37,12 @@ use util::nodemap::NodeSet; use std::any::Any; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; -use std::rc::Rc; -use rustc_data_structures::owning_ref::ErasedBoxRef; use syntax::ast; use syntax::ext::base::SyntaxExtension; use syntax::symbol::Symbol; use syntax_pos::Span; use rustc_back::target::Target; +use rustc_data_structures::sync::{MetadataRef, Lrc}; pub use self::NativeLibraryKind::*; @@ -139,7 +138,7 @@ pub struct NativeLibrary { pub enum LoadedMacro { MacroDef(ast::Item), - ProcMacro(Rc), + ProcMacro(Lrc), } #[derive(Copy, Clone, Debug)] @@ -187,11 +186,11 @@ pub trait MetadataLoader { fn get_rlib_metadata(&self, target: &Target, filename: &Path) - -> Result, String>; + -> Result; fn get_dylib_metadata(&self, target: &Target, filename: &Path) - -> Result, String>; + -> Result; } #[derive(Clone)] @@ -206,7 +205,7 @@ pub struct ExternConstBody<'tcx> { #[derive(Clone)] pub struct ExternBodyNestedBodies { - pub nested_bodies: Rc>, + pub nested_bodies: Lrc>, // It would require a lot of infrastructure to enable stable-hashing Bodies // from other crates, so we hash on export and just store the fingerprint @@ -225,7 +224,7 @@ pub struct ExternBodyNestedBodies { /// (it'd break incremental compilation) and should only be called pre-HIR (e.g. /// during resolve) pub trait CrateStore { - fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc; + fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc; // access to the metadata loader fn metadata_loader(&self) -> &MetadataLoader; @@ -234,7 +233,7 @@ pub trait CrateStore { fn def_key(&self, def: DefId) -> DefKey; fn def_path(&self, def: DefId) -> hir_map::DefPath; fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash; - fn def_path_table(&self, cnum: CrateNum) -> Rc; + fn def_path_table(&self, cnum: CrateNum) -> Lrc; // "queries" used in resolve that aren't tracked for incremental compilation fn visibility_untracked(&self, def: DefId) -> ty::Visibility; @@ -297,7 +296,7 @@ pub struct DummyCrateStore; #[allow(unused_variables)] impl CrateStore for DummyCrateStore { - fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc + fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc { bug!("crate_data_as_rc_any") } // item info fn visibility_untracked(&self, def: DefId) -> ty::Visibility { bug!("visibility") } @@ -325,7 +324,7 @@ impl CrateStore for DummyCrateStore { fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash { bug!("def_path_hash") } - fn def_path_table(&self, cnum: CrateNum) -> Rc { + fn def_path_table(&self, cnum: CrateNum) -> Lrc { bug!("def_path_table") } fn struct_field_names_untracked(&self, def: DefId) -> Vec { @@ -398,7 +397,7 @@ pub fn used_crates(tcx: TyCtxt, prefer: LinkagePreference) }) .collect::>(); let mut ordering = tcx.postorder_cnums(LOCAL_CRATE); - Rc::make_mut(&mut ordering).reverse(); + Lrc::make_mut(&mut ordering).reverse(); libs.sort_by_key(|&(a, _)| { ordering.iter().position(|x| *x == a) }); diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index 3bcde93fde502..02100514a5f6e 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -27,7 +27,7 @@ use middle::region; use ty::{self, TyCtxt, adjustment}; use hir::{self, PatKind}; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use syntax::ast; use syntax::ptr::P; use syntax_pos::Span; @@ -279,7 +279,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx, 'tcx> { param_env: ty::ParamEnv<'tcx>, region_scope_tree: &'a region::ScopeTree, tables: &'a ty::TypeckTables<'tcx>, - rvalue_promotable_map: Option>) + rvalue_promotable_map: Option>) -> Self { ExprUseVisitor { diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 0d4429de22a84..ce396276c98e2 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -85,6 +85,7 @@ use syntax::ast; use syntax_pos::Span; use std::fmt; +use rustc_data_structures::sync::Lrc; use std::rc::Rc; use util::nodemap::ItemLocalSet; @@ -286,7 +287,7 @@ pub struct MemCategorizationContext<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { pub tcx: TyCtxt<'a, 'gcx, 'tcx>, pub region_scope_tree: &'a region::ScopeTree, pub tables: &'a ty::TypeckTables<'tcx>, - rvalue_promotable_map: Option>, + rvalue_promotable_map: Option>, infcx: Option<&'a InferCtxt<'a, 'gcx, 'tcx>>, } @@ -395,7 +396,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx, 'tcx> { pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, region_scope_tree: &'a region::ScopeTree, tables: &'a ty::TypeckTables<'tcx>, - rvalue_promotable_map: Option>) + rvalue_promotable_map: Option>) -> MemCategorizationContext<'a, 'tcx, 'tcx> { MemCategorizationContext { tcx, diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index 6f457c9d1e1b2..5d61544f3c6b9 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -18,7 +18,7 @@ use hir::map as hir_map; use hir::def::Def; use hir::def_id::{DefId, CrateNum}; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use ty::{self, TyCtxt}; use ty::maps::Providers; use middle::privacy; @@ -378,7 +378,7 @@ impl<'a, 'tcx: 'a> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, // We introduce a new-type here, so we can have a specialized HashStable // implementation for it. #[derive(Clone)] -pub struct ReachableSet(pub Rc); +pub struct ReachableSet(pub Lrc); fn reachable_set<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> ReachableSet { @@ -426,7 +426,7 @@ fn reachable_set<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> reachable_context.propagate(); // Return the set of reachable symbols. - ReachableSet(Rc::new(reachable_context.reachable_symbols)) + ReachableSet(Lrc::new(reachable_context.reachable_symbols)) } pub fn provide(providers: &mut Providers) { diff --git a/src/librustc/middle/recursion_limit.rs b/src/librustc/middle/recursion_limit.rs index 6c87f750376fa..85592353c8977 100644 --- a/src/librustc/middle/recursion_limit.rs +++ b/src/librustc/middle/recursion_limit.rs @@ -18,7 +18,7 @@ use session::Session; use syntax::ast; -use std::cell::Cell; +use rustc_data_structures::sync::LockCell; pub fn update_limits(sess: &Session, krate: &ast::Crate) { update_limit(sess, krate, &sess.recursion_limit, "recursion_limit", @@ -27,7 +27,7 @@ pub fn update_limits(sess: &Session, krate: &ast::Crate) { "type length limit"); } -fn update_limit(sess: &Session, krate: &ast::Crate, limit: &Cell, +fn update_limit(sess: &Session, krate: &ast::Crate, limit: &LockCell, name: &str, description: &str) { for attr in &krate.attrs { if !attr.check_name(name) { diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index d3aa80e5585e2..d1feb8e9a07de 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -20,7 +20,7 @@ use ty; use std::fmt; use std::mem; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use syntax::codemap; use syntax::ast; use syntax_pos::{Span, DUMMY_SP}; @@ -1350,7 +1350,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> { } fn region_scope_tree<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) - -> Rc + -> Lrc { let closure_base_def_id = tcx.closure_base_def_id(def_id); if closure_base_def_id != def_id { @@ -1392,7 +1392,7 @@ fn region_scope_tree<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) ScopeTree::default() }; - Rc::new(scope_tree) + Lrc::new(scope_tree) } pub fn provide(providers: &mut Providers) { diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 8b302dbe67a42..b3096703f8c2f 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -23,7 +23,7 @@ use ty::{self, TyCtxt}; use std::cell::Cell; use std::mem::replace; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use syntax::ast; use syntax::attr; use syntax::ptr::P; @@ -212,10 +212,10 @@ struct NamedRegionMap { /// See `NamedRegionMap`. pub struct ResolveLifetimes { - defs: FxHashMap>>, - late_bound: FxHashMap>>, + defs: FxHashMap>>, + late_bound: FxHashMap>>, object_lifetime_defaults: - FxHashMap>>>>, + FxHashMap>>>>, } impl_stable_hash_for!(struct ::middle::resolve_lifetime::ResolveLifetimes { @@ -363,7 +363,7 @@ pub fn provide(providers: &mut ty::maps::Providers) { fn resolve_lifetimes<'tcx>( tcx: TyCtxt<'_, 'tcx, 'tcx>, for_krate: CrateNum, -) -> Rc { +) -> Lrc { assert_eq!(for_krate, LOCAL_CRATE); let named_region_map = krate(tcx); @@ -372,29 +372,29 @@ fn resolve_lifetimes<'tcx>( for (k, v) in named_region_map.defs { let hir_id = tcx.hir.node_to_hir_id(k); let map = defs.entry(hir_id.owner_local_def_id()) - .or_insert_with(|| Rc::new(FxHashMap())); - Rc::get_mut(map).unwrap().insert(hir_id.local_id, v); + .or_insert_with(|| Lrc::new(FxHashMap())); + Lrc::get_mut(map).unwrap().insert(hir_id.local_id, v); } let mut late_bound = FxHashMap(); for k in named_region_map.late_bound { let hir_id = tcx.hir.node_to_hir_id(k); let map = late_bound .entry(hir_id.owner_local_def_id()) - .or_insert_with(|| Rc::new(FxHashSet())); - Rc::get_mut(map).unwrap().insert(hir_id.local_id); + .or_insert_with(|| Lrc::new(FxHashSet())); + Lrc::get_mut(map).unwrap().insert(hir_id.local_id); } let mut object_lifetime_defaults = FxHashMap(); for (k, v) in named_region_map.object_lifetime_defaults { let hir_id = tcx.hir.node_to_hir_id(k); let map = object_lifetime_defaults .entry(hir_id.owner_local_def_id()) - .or_insert_with(|| Rc::new(FxHashMap())); - Rc::get_mut(map) + .or_insert_with(|| Lrc::new(FxHashMap())); + Lrc::get_mut(map) .unwrap() - .insert(hir_id.local_id, Rc::new(v)); + .insert(hir_id.local_id, Lrc::new(v)); } - Rc::new(ResolveLifetimes { + Lrc::new(ResolveLifetimes { defs, late_bound, object_lifetime_defaults, diff --git a/src/librustc/mir/cache.rs b/src/librustc/mir/cache.rs index efc2f647cfdf5..8fed58a178862 100644 --- a/src/librustc/mir/cache.rs +++ b/src/librustc/mir/cache.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::cell::{Ref, RefCell}; use rustc_data_structures::indexed_vec::IndexVec; +use rustc_data_structures::sync::{RwLock, ReadGuard}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult}; use ich::StableHashingContext; @@ -19,7 +19,7 @@ use rustc_serialize as serialize; #[derive(Clone, Debug)] pub struct Cache { - predecessors: RefCell>>> + predecessors: RwLock>>> } @@ -46,7 +46,7 @@ impl<'gcx> HashStable> for Cache { impl Cache { pub fn new() -> Self { Cache { - predecessors: RefCell::new(None) + predecessors: RwLock::new(None) } } @@ -55,12 +55,12 @@ impl Cache { *self.predecessors.borrow_mut() = None; } - pub fn predecessors(&self, mir: &Mir) -> Ref>> { + pub fn predecessors(&self, mir: &Mir) -> ReadGuard>> { if self.predecessors.borrow().is_none() { *self.predecessors.borrow_mut() = Some(calculate_predecessors(mir)); } - Ref::map(self.predecessors.borrow(), |p| p.as_ref().unwrap()) + ReadGuard::map(self.predecessors.borrow(), |p| p.as_ref().unwrap()) } } diff --git a/src/librustc/mir/mod.rs b/src/librustc/mir/mod.rs index f410865a6cd7f..ba0b19f7df274 100644 --- a/src/librustc/mir/mod.rs +++ b/src/librustc/mir/mod.rs @@ -14,6 +14,7 @@ use graphviz::IntoCow; use middle::const_val::ConstVal; use middle::region; use rustc_const_math::{ConstUsize, ConstInt, ConstMathErr}; +use rustc_data_structures::sync::{Lrc}; use rustc_data_structures::indexed_vec::{IndexVec, Idx}; use rustc_data_structures::control_flow_graph::dominators::{Dominators, dominators}; use rustc_data_structures::control_flow_graph::{GraphPredecessors, GraphSuccessors}; @@ -30,11 +31,10 @@ use std::slice; use hir::{self, InlineAsm}; use std::ascii; use std::borrow::{Cow}; -use std::cell::Ref; +use rustc_data_structures::sync::ReadGuard; use std::fmt::{self, Debug, Formatter, Write}; use std::{iter, u32}; use std::ops::{Index, IndexMut}; -use std::rc::Rc; use std::vec::IntoIter; use syntax::ast::{self, Name}; use syntax::symbol::InternedString; @@ -184,13 +184,13 @@ impl<'tcx> Mir<'tcx> { } #[inline] - pub fn predecessors(&self) -> Ref>> { + pub fn predecessors(&self) -> ReadGuard>> { self.cache.predecessors(self) } #[inline] - pub fn predecessors_for(&self, bb: BasicBlock) -> Ref> { - Ref::map(self.predecessors(), |p| &p[bb]) + pub fn predecessors_for(&self, bb: BasicBlock) -> ReadGuard> { + ReadGuard::map(self.predecessors(), |p| &p[bb]) } #[inline] @@ -1788,10 +1788,10 @@ pub struct UnsafetyViolation { #[derive(Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)] pub struct UnsafetyCheckResult { /// Violations that are propagated *upwards* from this function - pub violations: Rc<[UnsafetyViolation]>, + pub violations: Lrc<[UnsafetyViolation]>, /// unsafe blocks in this function, along with whether they are used. This is /// used for the "unused_unsafe" lint. - pub unsafe_blocks: Rc<[(ast::NodeId, bool)]>, + pub unsafe_blocks: Lrc<[(ast::NodeId, bool)]>, } /// The layout of generator state diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index 0de1c20dbde1e..c7f1e0da91e73 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -23,6 +23,8 @@ use ty::tls; use util::nodemap::{FxHashMap, FxHashSet}; use util::common::{duration_to_secs_str, ErrorReported}; +use rustc_data_structures::sync::{self, Lrc, RwLock, Lock, LockCell, ReadGuard}; + use syntax::ast::NodeId; use errors::{self, DiagnosticBuilder, DiagnosticId}; use errors::emitter::{Emitter, EmitterWriter}; @@ -39,13 +41,11 @@ use rustc_back::target::Target; use rustc_data_structures::flock; use jobserver::Client; -use std::cell::{self, Cell, RefCell}; use std::collections::HashMap; use std::env; use std::fmt; use std::io::Write; use std::path::{Path, PathBuf}; -use std::rc::Rc; use std::sync::{Once, ONCE_INIT}; use std::time::Duration; @@ -62,10 +62,10 @@ pub struct Session { pub opts: config::Options, pub parse_sess: ParseSess, /// For a library crate, this is always none - pub entry_fn: RefCell>, - pub entry_type: Cell>, - pub plugin_registrar_fn: Cell>, - pub derive_registrar_fn: Cell>, + pub entry_fn: Lock>, + pub entry_type: LockCell>, + pub plugin_registrar_fn: LockCell>, + pub derive_registrar_fn: LockCell>, pub default_sysroot: Option, /// The name of the root source file of the crate, in the local file system. /// `None` means that there is no source file. @@ -73,88 +73,88 @@ pub struct Session { /// The directory the compiler has been executed in plus a flag indicating /// if the value stored here has been affected by path remapping. pub working_dir: (PathBuf, bool), - pub lint_store: RefCell, - pub buffered_lints: RefCell>, + pub lint_store: RwLock, + pub buffered_lints: Lock>, /// Set of (DiagnosticId, Option, message) tuples tracking /// (sub)diagnostics that have been set once, but should not be set again, /// in order to avoid redundantly verbose output (Issue #24690, #44953). - pub one_time_diagnostics: RefCell, String)>>, - pub plugin_llvm_passes: RefCell>, - pub plugin_attributes: RefCell>, - pub crate_types: RefCell>, - pub dependency_formats: RefCell, + pub one_time_diagnostics: Lock, String)>>, + pub plugin_llvm_passes: Lock>, + pub plugin_attributes: Lock>, + pub crate_types: RwLock>, + pub dependency_formats: Lock, /// The crate_disambiguator is constructed out of all the `-C metadata` /// arguments passed to the compiler. Its value together with the crate-name /// forms a unique global identifier for the crate. It is used to allow /// multiple crates with the same name to coexist. See the /// trans::back::symbol_names module for more information. - pub crate_disambiguator: RefCell>, - pub features: RefCell, + pub crate_disambiguator: Lock>, + pub features: RwLock, /// The maximum recursion limit for potentially infinitely recursive /// operations such as auto-dereference and monomorphization. - pub recursion_limit: Cell, + pub recursion_limit: LockCell, /// The maximum length of types during monomorphization. - pub type_length_limit: Cell, + pub type_length_limit: LockCell, /// The metadata::creader module may inject an allocator/panic_runtime /// dependency if it didn't already find one, and this tracks what was /// injected. - pub injected_allocator: Cell>, - pub allocator_kind: Cell>, - pub injected_panic_runtime: Cell>, + pub injected_allocator: LockCell>, + pub allocator_kind: LockCell>, + pub injected_panic_runtime: LockCell>, /// Map from imported macro spans (which consist of /// the localized span for the macro body) to the /// macro name and definition span in the source crate. - pub imported_macro_spans: RefCell>, + pub imported_macro_spans: Lock>, - incr_comp_session: RefCell, + incr_comp_session: RwLock, /// Some measurements that are being gathered during compilation. pub perf_stats: PerfStats, /// Data about code being compiled, gathered during compilation. - pub code_stats: RefCell, + pub code_stats: Lock, - next_node_id: Cell, + next_node_id: LockCell, /// If -zfuel=crate=n is specified, Some(crate). optimization_fuel_crate: Option, /// If -zfuel=crate=n is specified, initially set to n. Otherwise 0. - optimization_fuel_limit: Cell, + optimization_fuel_limit: LockCell, /// We're rejecting all further optimizations. - out_of_fuel: Cell, + out_of_fuel: LockCell, // The next two are public because the driver needs to read them. /// If -zprint-fuel=crate, Some(crate). pub print_fuel_crate: Option, /// Always set to zero and incremented so that we can print fuel expended by a crate. - pub print_fuel: Cell, + pub print_fuel: LockCell, /// Loaded up early on in the initialization of this `Session` to avoid /// false positives about a job server in our environment. pub jobserver_from_env: Option, /// Metadata about the allocators for the current crate being compiled - pub has_global_allocator: Cell, + pub has_global_allocator: LockCell, } pub struct PerfStats { /// The accumulated time needed for computing the SVH of the crate - pub svh_time: Cell, + pub svh_time: LockCell, /// The accumulated time spent on computing incr. comp. hashes - pub incr_comp_hashes_time: Cell, + pub incr_comp_hashes_time: LockCell, /// The number of incr. comp. hash computations performed - pub incr_comp_hashes_count: Cell, + pub incr_comp_hashes_count: LockCell, /// The number of bytes hashed when computing ICH values - pub incr_comp_bytes_hashed: Cell, + pub incr_comp_bytes_hashed: LockCell, /// The accumulated time spent on computing symbol hashes - pub symbol_hash_time: Cell, + pub symbol_hash_time: LockCell, /// The accumulated time spent decoding def path tables from metadata - pub decode_def_path_tables_time: Cell, + pub decode_def_path_tables_time: LockCell, } /// Enum to support dispatch of one-time diagnostics (in Session.diag_once) @@ -652,9 +652,9 @@ impl Session { }; } - pub fn incr_comp_session_dir(&self) -> cell::Ref { + pub fn incr_comp_session_dir(&self) -> ReadGuard { let incr_comp_session = self.incr_comp_session.borrow(); - cell::Ref::map(incr_comp_session, |incr_comp_session| { + ReadGuard::map(incr_comp_session, |incr_comp_session| { match *incr_comp_session { IncrCompSession::NotInitialized => { bug!("Trying to get session directory from IncrCompSession `{:?}`", @@ -669,7 +669,7 @@ impl Session { }) } - pub fn incr_comp_session_dir_opt(&self) -> Option> { + pub fn incr_comp_session_dir_opt(&self) -> Option> { if self.opts.incremental.is_some() { Some(self.incr_comp_session_dir()) } else { @@ -839,14 +839,14 @@ pub fn build_session(sopts: config::Options, build_session_with_codemap(sopts, local_crate_source_file, registry, - Rc::new(codemap::CodeMap::new(file_path_mapping)), + Lrc::new(codemap::CodeMap::new(file_path_mapping)), None) } pub fn build_session_with_codemap(sopts: config::Options, local_crate_source_file: Option, registry: errors::registry::Registry, - codemap: Rc, + codemap: Lrc, emitter_dest: Option>) -> Session { // FIXME: This is not general enough to make the warning lint completely override @@ -866,7 +866,7 @@ pub fn build_session_with_codemap(sopts: config::Options, let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace; - let emitter: Box = match (sopts.error_format, emitter_dest) { + let emitter: Box = match (sopts.error_format, emitter_dest) { (config::ErrorOutputType::HumanReadable(color_config), None) => { Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()), false)) } @@ -906,7 +906,7 @@ pub fn build_session_with_codemap(sopts: config::Options, pub fn build_session_(sopts: config::Options, local_crate_source_file: Option, span_diagnostic: errors::Handler, - codemap: Rc) + codemap: Lrc) -> Session { let host = match Target::search(config::host_triple()) { Ok(t) => t, @@ -929,10 +929,10 @@ pub fn build_session_(sopts: config::Options, }); let optimization_fuel_crate = sopts.debugging_opts.fuel.as_ref().map(|i| i.0.clone()); - let optimization_fuel_limit = Cell::new(sopts.debugging_opts.fuel.as_ref() + let optimization_fuel_limit = LockCell::new(sopts.debugging_opts.fuel.as_ref() .map(|i| i.1).unwrap_or(0)); let print_fuel_crate = sopts.debugging_opts.print_fuel.clone(); - let print_fuel = Cell::new(0); + let print_fuel = LockCell::new(0); let working_dir = match env::current_dir() { Ok(dir) => dir, @@ -948,44 +948,44 @@ pub fn build_session_(sopts: config::Options, opts: sopts, parse_sess: p_s, // For a library crate, this is always none - entry_fn: RefCell::new(None), - entry_type: Cell::new(None), - plugin_registrar_fn: Cell::new(None), - derive_registrar_fn: Cell::new(None), + entry_fn: Lock::new(None), + entry_type: LockCell::new(None), + plugin_registrar_fn: LockCell::new(None), + derive_registrar_fn: LockCell::new(None), default_sysroot, local_crate_source_file, working_dir, - lint_store: RefCell::new(lint::LintStore::new()), - buffered_lints: RefCell::new(Some(lint::LintBuffer::new())), - one_time_diagnostics: RefCell::new(FxHashSet()), - plugin_llvm_passes: RefCell::new(Vec::new()), - plugin_attributes: RefCell::new(Vec::new()), - crate_types: RefCell::new(Vec::new()), - dependency_formats: RefCell::new(FxHashMap()), - crate_disambiguator: RefCell::new(None), - features: RefCell::new(feature_gate::Features::new()), - recursion_limit: Cell::new(64), - type_length_limit: Cell::new(1048576), - next_node_id: Cell::new(NodeId::new(1)), - injected_allocator: Cell::new(None), - allocator_kind: Cell::new(None), - injected_panic_runtime: Cell::new(None), - imported_macro_spans: RefCell::new(HashMap::new()), - incr_comp_session: RefCell::new(IncrCompSession::NotInitialized), + lint_store: RwLock::new(lint::LintStore::new()), + buffered_lints: Lock::new(Some(lint::LintBuffer::new())), + one_time_diagnostics: Lock::new(FxHashSet()), + plugin_llvm_passes: Lock::new(Vec::new()), + plugin_attributes: Lock::new(Vec::new()), + crate_types: RwLock::new(Vec::new()), + dependency_formats: Lock::new(FxHashMap()), + crate_disambiguator: Lock::new(None), + features: RwLock::new(feature_gate::Features::new()), + recursion_limit: LockCell::new(64), + type_length_limit: LockCell::new(1048576), + next_node_id: LockCell::new(NodeId::new(1)), + injected_allocator: LockCell::new(None), + allocator_kind: LockCell::new(None), + injected_panic_runtime: LockCell::new(None), + imported_macro_spans: Lock::new(HashMap::new()), + incr_comp_session: RwLock::new(IncrCompSession::NotInitialized), perf_stats: PerfStats { - svh_time: Cell::new(Duration::from_secs(0)), - incr_comp_hashes_time: Cell::new(Duration::from_secs(0)), - incr_comp_hashes_count: Cell::new(0), - incr_comp_bytes_hashed: Cell::new(0), - symbol_hash_time: Cell::new(Duration::from_secs(0)), - decode_def_path_tables_time: Cell::new(Duration::from_secs(0)), + svh_time: LockCell::new(Duration::from_secs(0)), + incr_comp_hashes_time: LockCell::new(Duration::from_secs(0)), + incr_comp_hashes_count: LockCell::new(0), + incr_comp_bytes_hashed: LockCell::new(0), + symbol_hash_time: LockCell::new(Duration::from_secs(0)), + decode_def_path_tables_time: LockCell::new(Duration::from_secs(0)), }, - code_stats: RefCell::new(CodeStats::new()), + code_stats: Lock::new(CodeStats::new()), optimization_fuel_crate, optimization_fuel_limit, print_fuel_crate, print_fuel, - out_of_fuel: Cell::new(false), + out_of_fuel: LockCell::new(false), // Note that this is unsafe because it may misinterpret file descriptors // on Unix as jobserver file descriptors. We hopefully execute this near // the beginning of the process though to ensure we don't get false @@ -1003,7 +1003,7 @@ pub fn build_session_(sopts: config::Options, }); (*GLOBAL_JOBSERVER).clone() }, - has_global_allocator: Cell::new(false), + has_global_allocator: LockCell::new(false), }; sess @@ -1056,7 +1056,7 @@ pub enum IncrCompSession { } pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! { - let emitter: Box = match output { + let emitter: Box = match output { config::ErrorOutputType::HumanReadable(color_config) => { Box::new(EmitterWriter::stderr(color_config, None, false)) } @@ -1071,7 +1071,7 @@ pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! { } pub fn early_warn(output: config::ErrorOutputType, msg: &str) { - let emitter: Box = match output { + let emitter: Box = match output { config::ErrorOutputType::HumanReadable(color_config) => { Box::new(EmitterWriter::stderr(color_config, None, false)) } diff --git a/src/librustc/traits/mod.rs b/src/librustc/traits/mod.rs index 94605d895a554..c7bef6c6e2c6b 100644 --- a/src/librustc/traits/mod.rs +++ b/src/librustc/traits/mod.rs @@ -25,6 +25,7 @@ use ty::{self, AdtKind, Ty, TyCtxt, TypeFoldable, ToPredicate}; use ty::error::{ExpectedFound, TypeError}; use infer::{InferCtxt}; +use rustc_data_structures::sync::Lrc; use std::rc::Rc; use syntax::ast; use syntax_pos::{Span, DUMMY_SP}; @@ -693,11 +694,11 @@ pub fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, fn vtable_methods<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_ref: ty::PolyTraitRef<'tcx>) - -> Rc)>>> + -> Lrc)>>> { debug!("vtable_methods({:?})", trait_ref); - Rc::new( + Lrc::new( supertraits(tcx, trait_ref).flat_map(move |trait_ref| { let trait_methods = tcx.associated_items(trait_ref.def_id()) .filter(|item| item.kind == ty::AssociatedKind::Method); diff --git a/src/librustc/traits/select.rs b/src/librustc/traits/select.rs index e70de0e566e41..c724db448a8eb 100644 --- a/src/librustc/traits/select.rs +++ b/src/librustc/traits/select.rs @@ -41,10 +41,10 @@ use ty::fast_reject; use ty::relate::TypeRelation; use middle::lang_items; +use rustc_data_structures::sync::Lock; use rustc_data_structures::bitvec::BitVector; use rustc_data_structures::snapshot_vec::{SnapshotVecDelegate, SnapshotVec}; use std::iter; -use std::cell::RefCell; use std::cmp; use std::fmt; use std::marker::PhantomData; @@ -148,7 +148,7 @@ struct TraitObligationStack<'prev, 'tcx: 'prev> { #[derive(Clone)] pub struct SelectionCache<'tcx> { - hashmap: RefCell, + hashmap: Lock, WithDepNode>>>>, } @@ -413,7 +413,7 @@ impl EvaluationResult { #[derive(Clone)] pub struct EvaluationCache<'tcx> { - hashmap: RefCell, WithDepNode>> + hashmap: Lock, WithDepNode>> } impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { @@ -3303,7 +3303,7 @@ impl<'tcx> TraitObligation<'tcx> { impl<'tcx> SelectionCache<'tcx> { pub fn new() -> SelectionCache<'tcx> { SelectionCache { - hashmap: RefCell::new(FxHashMap()) + hashmap: Lock::new(FxHashMap()) } } } @@ -3311,7 +3311,7 @@ impl<'tcx> SelectionCache<'tcx> { impl<'tcx> EvaluationCache<'tcx> { pub fn new() -> EvaluationCache<'tcx> { EvaluationCache { - hashmap: RefCell::new(FxHashMap()) + hashmap: Lock::new(FxHashMap()) } } } diff --git a/src/librustc/traits/specialize/mod.rs b/src/librustc/traits/specialize/mod.rs index afe29cc0e7baf..7973aae979b8b 100644 --- a/src/librustc/traits/specialize/mod.rs +++ b/src/librustc/traits/specialize/mod.rs @@ -28,7 +28,7 @@ use traits::{self, Reveal, ObligationCause}; use traits::select::IntercrateAmbiguityCause; use ty::{self, TyCtxt, TypeFoldable}; use syntax_pos::DUMMY_SP; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use lint; @@ -306,7 +306,7 @@ impl SpecializesCache { // Query provider for `specialization_graph_of`. pub(super) fn specialization_graph_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_id: DefId) - -> Rc { + -> Lrc { let mut sg = specialization_graph::Graph::new(); let mut trait_impls = Vec::new(); @@ -390,7 +390,7 @@ pub(super) fn specialization_graph_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx } } - Rc::new(sg) + Lrc::new(sg) } /// Recovers the "impl X for Y" signature from `impl_def_id` and returns it as a diff --git a/src/librustc/traits/specialize/specialization_graph.rs b/src/librustc/traits/specialize/specialization_graph.rs index 834389e5d009c..e55d4614a2ee3 100644 --- a/src/librustc/traits/specialize/specialization_graph.rs +++ b/src/librustc/traits/specialize/specialization_graph.rs @@ -17,7 +17,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher, use traits; use ty::{self, TyCtxt, TypeFoldable}; use ty::fast_reject::{self, SimplifiedType}; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use syntax::ast::Name; use util::nodemap::{DefIdMap, FxHashMap}; @@ -330,7 +330,7 @@ impl<'a, 'gcx, 'tcx> Node { pub struct Ancestors { trait_def_id: DefId, - specialization_graph: Rc, + specialization_graph: Lrc, current_source: Option, } diff --git a/src/librustc/ty/context.rs b/src/librustc/ty/context.rs index b233156cf7fc6..9475e45f52e74 100644 --- a/src/librustc/ty/context.rs +++ b/src/librustc/ty/context.rs @@ -55,16 +55,15 @@ use rustc_data_structures::stable_hasher::{HashStable, hash_stable_hashmap, use arena::{TypedArena, DroplessArena}; use rustc_const_math::{ConstInt, ConstUsize}; use rustc_data_structures::indexed_vec::IndexVec; +use rustc_data_structures::sync::{Sync, Lrc, Lock, LockCell}; use std::any::Any; use std::borrow::Borrow; -use std::cell::{Cell, RefCell}; use std::cmp::Ordering; use std::collections::hash_map::{self, Entry}; use std::hash::{Hash, Hasher}; use std::mem; use std::ops::Deref; use std::iter; -use std::rc::Rc; use std::sync::mpsc; use std::sync::Arc; use syntax::abi; @@ -127,26 +126,26 @@ pub struct CtxtInterners<'tcx> { /// Specifically use a speedy hash algorithm for these hash sets, /// they're accessed quite often. - type_: RefCell>>>, - type_list: RefCell>>>>, - substs: RefCell>>>, - region: RefCell>>, - existential_predicates: RefCell>>>>, - predicates: RefCell>>>>, - const_: RefCell>>>, + type_: Lock>>>, + type_list: Lock>>>>, + substs: Lock>>>, + region: Lock>>, + existential_predicates: Lock>>>>, + predicates: Lock>>>>, + const_: Lock>>>, } impl<'gcx: 'tcx, 'tcx> CtxtInterners<'tcx> { fn new(arena: &'tcx DroplessArena) -> CtxtInterners<'tcx> { CtxtInterners { - arena, - type_: RefCell::new(FxHashSet()), - type_list: RefCell::new(FxHashSet()), - substs: RefCell::new(FxHashSet()), - region: RefCell::new(FxHashSet()), - existential_predicates: RefCell::new(FxHashSet()), - predicates: RefCell::new(FxHashSet()), - const_: RefCell::new(FxHashSet()), + arena: arena, + type_: Lock::new(FxHashSet()), + type_list: Lock::new(FxHashSet()), + substs: Lock::new(FxHashSet()), + region: Lock::new(FxHashSet()), + existential_predicates: Lock::new(FxHashSet()), + predicates: Lock::new(FxHashSet()), + const_: Lock::new(FxHashSet()), } } @@ -397,9 +396,9 @@ pub struct TypeckTables<'tcx> { /// Set of trait imports actually used in the method resolution. /// This is used for warning unused imports. During type - /// checking, this `Rc` should not be cloned: it must have a ref-count + /// checking, this `Lrc` should not be cloned: it must have a ref-count /// of 1 so that we can insert things into the set mutably. - pub used_trait_imports: Rc, + pub used_trait_imports: Lrc, /// If any errors occurred while type-checking this body, /// this field will be set to `true`. @@ -426,7 +425,7 @@ impl<'tcx> TypeckTables<'tcx> { liberated_fn_sigs: ItemLocalMap(), fru_field_types: ItemLocalMap(), cast_kinds: ItemLocalMap(), - used_trait_imports: Rc::new(DefIdSet()), + used_trait_imports: Lrc::new(DefIdSet()), tainted_by_errors: false, free_region_map: FreeRegionMap::new(), } @@ -797,7 +796,7 @@ pub struct GlobalCtxt<'tcx> { global_arenas: &'tcx GlobalArenas<'tcx>, global_interners: CtxtInterners<'tcx>, - cstore: &'tcx CrateStore, + cstore: &'tcx (CrateStore + Sync), pub sess: &'tcx Session, @@ -814,11 +813,11 @@ pub struct GlobalCtxt<'tcx> { /// Map indicating what traits are in scope for places where this /// is relevant; generated by resolve. trait_map: FxHashMap>>>>, + Lrc>>>>, /// Export map produced by name resolution. - export_map: FxHashMap>>, + export_map: FxHashMap>>, pub hir: hir_map::Map<'tcx>, @@ -831,14 +830,14 @@ pub struct GlobalCtxt<'tcx> { // Records the free variables refrenced by every closure // expression. Do not track deps for this, just recompute it from // scratch every time. - freevars: FxHashMap>>, + freevars: FxHashMap>>, maybe_unused_trait_imports: FxHashSet, maybe_unused_extern_crates: Vec<(DefId, Span)>, // Internal cache for metadata decoding. No need to track deps on this. - pub rcache: RefCell>>, + pub rcache: Lock>>, /// Caches the results of trait selection. This cache is used /// for things that do not have to do with the parameters in scope. @@ -857,23 +856,23 @@ pub struct GlobalCtxt<'tcx> { pub data_layout: TargetDataLayout, /// Used to prevent layout from recursing too deeply. - pub layout_depth: Cell, + pub layout_depth: LockCell, /// Map from function to the `#[derive]` mode that it's defining. Only used /// by `proc-macro` crates. - pub derive_macros: RefCell>, + pub derive_macros: Lock>, - stability_interner: RefCell>, + stability_interner: Lock>, - pub interpret_interner: RefCell>, + pub interpret_interner: Lock>, - layout_interner: RefCell>, + layout_interner: Lock>, /// A vector of every trait accessible in the whole crate /// (i.e. including those from subcrates). This is used only for /// error reporting, and so is lazily initialized and generally - /// shouldn't taint the common path (hence the RefCell). - pub all_traits: RefCell>>, + /// shouldn't taint the common path (hence the Lock). + pub all_traits: Lock>>, /// A general purpose channel to throw data out the back towards LLVM worker /// threads. @@ -881,7 +880,7 @@ pub struct GlobalCtxt<'tcx> { /// This is intended to only get used during the trans phase of the compiler /// 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: mpsc::Sender>, + pub tx_to_llvm_workers: Lock>>, output_filenames: Arc, } @@ -1131,7 +1130,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { /// value (types, substs, etc.) can only be used while `ty::tls` has a valid /// reference to the context, to allow formatting values that need it. pub fn create_and_enter(s: &'tcx Session, - cstore: &'tcx CrateStore, + cstore: &'tcx (CrateStore + Sync), local_providers: ty::maps::Providers<'tcx>, extern_providers: ty::maps::Providers<'tcx>, arenas: &'tcx AllArenas<'tcx>, @@ -1153,7 +1152,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { 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, Rc<_>)> = cstore + let upstream_def_path_tables: Vec<(CrateNum, Lrc<_>)> = cstore .crates_untracked() .iter() .map(|&cnum| (cnum, cstore.def_path_table(cnum))) @@ -1188,10 +1187,10 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { 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_insert_with(|| Rc::new(FxHashMap())); - Rc::get_mut(map).unwrap() + .or_insert_with(|| Lrc::new(FxHashMap())); + Lrc::get_mut(map).unwrap() .insert(hir_id.local_id, - Rc::new(StableVec::new(v))); + Lrc::new(StableVec::new(v))); } tls::enter_global(GlobalCtxt { @@ -1204,10 +1203,10 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { types: common_types, trait_map, export_map: resolutions.export_map.into_iter().map(|(k, v)| { - (k, Rc::new(v)) + (k, Lrc::new(v)) }).collect(), freevars: resolutions.freevars.into_iter().map(|(k, v)| { - (hir.local_def_id(k), Rc::new(v)) + (hir.local_def_id(k), Lrc::new(v)) }).collect(), maybe_unused_trait_imports: resolutions.maybe_unused_trait_imports @@ -1222,18 +1221,18 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { hir, def_path_hash_to_def_id, maps: maps::Maps::new(providers), - rcache: RefCell::new(FxHashMap()), + rcache: Lock::new(FxHashMap()), selection_cache: traits::SelectionCache::new(), evaluation_cache: traits::EvaluationCache::new(), crate_name: Symbol::intern(crate_name), data_layout, - layout_interner: RefCell::new(FxHashSet()), - layout_depth: Cell::new(0), - derive_macros: RefCell::new(NodeMap()), - stability_interner: RefCell::new(FxHashSet()), - interpret_interner: Default::default(), - all_traits: RefCell::new(None), - tx_to_llvm_workers: tx, + layout_interner: Lock::new(FxHashSet()), + layout_depth: LockCell::new(0), + derive_macros: Lock::new(NodeMap()), + stability_interner: Lock::new(FxHashSet()), + interpret_interner: Lock::new(Default::default()), + all_traits: Lock::new(None), + tx_to_llvm_workers: Lock::new(tx), output_filenames: Arc::new(output_filenames.clone()), }, f) } @@ -1243,15 +1242,15 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { self.sess.consider_optimizing(&cname, msg) } - pub fn lang_items(self) -> Rc { + pub fn lang_items(self) -> Lrc { self.get_lang_items(LOCAL_CRATE) } - pub fn stability(self) -> Rc> { + pub fn stability(self) -> Lrc> { self.stability_index(LOCAL_CRATE) } - pub fn crates(self) -> Rc> { + pub fn crates(self) -> Lrc> { self.all_crate_nums(LOCAL_CRATE) } @@ -1312,7 +1311,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { // Note that this is *untracked* and should only be used within the query // system if the result is otherwise tracked through queries - pub fn crate_data_as_rc_any(self, cnum: CrateNum) -> Rc { + pub fn crate_data_as_rc_any(self, cnum: CrateNum) -> Lrc { self.cstore.crate_data_as_rc_any(cnum) } @@ -2259,7 +2258,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { lint::struct_lint_level(self.sess, lint, level, src, None, msg) } - pub fn in_scope_traits(self, id: HirId) -> Option>> { + pub fn in_scope_traits(self, id: HirId) -> Option>> { self.in_scope_traits_map(id.owner) .and_then(|map| map.get(&id.local_id).cloned()) } @@ -2276,7 +2275,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { } pub fn object_lifetime_defaults(self, id: HirId) - -> Option>> + -> Option>> { self.object_lifetime_defaults_map(id.owner) .and_then(|map| map.get(&id.local_id).cloned()) @@ -2347,7 +2346,7 @@ pub fn provide(providers: &mut ty::maps::Providers) { // Once red/green incremental compilation lands we should be able to // remove this because while the crate changes often the lint level map // will change rarely. - tcx.dep_graph.with_ignore(|| Rc::new(middle::lang_items::collect(tcx))) + tcx.dep_graph.with_ignore(|| Lrc::new(middle::lang_items::collect(tcx))) }; providers.freevars = |tcx, id| tcx.gcx.freevars.get(&id).cloned(); providers.maybe_unused_trait_import = |tcx, id| { @@ -2355,12 +2354,12 @@ pub fn provide(providers: &mut ty::maps::Providers) { }; providers.maybe_unused_extern_crates = |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); - Rc::new(tcx.maybe_unused_extern_crates.clone()) + Lrc::new(tcx.maybe_unused_extern_crates.clone()) }; providers.stability_index = |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); - Rc::new(stability::Index::new(tcx)) + Lrc::new(stability::Index::new(tcx)) }; providers.lookup_stability = |tcx, id| { assert_eq!(id.krate, LOCAL_CRATE); @@ -2378,11 +2377,11 @@ pub fn provide(providers: &mut ty::maps::Providers) { }; providers.all_crate_nums = |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); - Rc::new(tcx.cstore.crates_untracked()) + Lrc::new(tcx.cstore.crates_untracked()) }; providers.postorder_cnums = |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); - Rc::new(tcx.cstore.postorder_cnums_untracked()) + Lrc::new(tcx.cstore.postorder_cnums_untracked()) }; providers.output_filenames = |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); diff --git a/src/librustc/ty/maps/mod.rs b/src/librustc/ty/maps/mod.rs index 23531b7b942f5..27c8fadc3adb8 100644 --- a/src/librustc/ty/maps/mod.rs +++ b/src/librustc/ty/maps/mod.rs @@ -46,7 +46,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::stable_hasher::StableVec; use std::ops::Deref; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use std::sync::Arc; use syntax_pos::{Span, DUMMY_SP}; use syntax_pos::symbol::InternedString; @@ -117,17 +117,17 @@ define_maps! { <'tcx> /// Get a map with the variance of every item; use `item_variance` /// instead. - [] fn crate_variances: crate_variances(CrateNum) -> Rc, + [] fn crate_variances: crate_variances(CrateNum) -> Lrc, /// Maps from def-id of a type or region parameter to its /// (inferred) variance. - [] fn variances_of: ItemVariances(DefId) -> Rc>, + [] fn variances_of: ItemVariances(DefId) -> Lrc>, /// Maps from def-id of a type to its (inferred) outlives. [] fn inferred_outlives_of: InferredOutlivesOf(DefId) -> Vec>, /// Maps from an impl/trait def-id to a list of the def-ids of its items - [] fn associated_item_def_ids: AssociatedItemDefIds(DefId) -> Rc>, + [] fn associated_item_def_ids: AssociatedItemDefIds(DefId) -> Lrc>, /// Maps from a trait item to the trait item "descriptor" [] fn associated_item: AssociatedItems(DefId) -> ty::AssociatedItem, @@ -138,17 +138,17 @@ define_maps! { <'tcx> /// Maps a DefId of a type to a list of its inherent impls. /// Contains implementations of methods that are inherent to a type. /// Methods in these implementations don't need to be exported. - [] fn inherent_impls: InherentImpls(DefId) -> Rc>, + [] fn inherent_impls: InherentImpls(DefId) -> Lrc>, /// Set of all the def-ids in this crate that have MIR associated with /// them. This includes all the body owners, but also things like struct /// constructors. - [] fn mir_keys: mir_keys(CrateNum) -> Rc, + [] fn mir_keys: mir_keys(CrateNum) -> Lrc, /// Maps DefId's that have an associated Mir to the result /// of the MIR qualify_consts pass. The actual meaning of /// the value isn't known except to the pass itself. - [] fn mir_const_qualif: MirConstQualif(DefId) -> (u8, Rc>), + [] fn mir_const_qualif: MirConstQualif(DefId) -> (u8, Lrc>), /// Fetch the MIR for a given def-id right after it's built - this includes /// unreachable code. @@ -183,13 +183,13 @@ define_maps! { <'tcx> [] fn typeck_tables_of: TypeckTables(DefId) -> &'tcx ty::TypeckTables<'tcx>, - [] fn used_trait_imports: UsedTraitImports(DefId) -> Rc, + [] fn used_trait_imports: UsedTraitImports(DefId) -> Lrc, [] fn has_typeck_tables: HasTypeckTables(DefId) -> bool, [] fn coherent_trait: coherent_trait_dep_node((CrateNum, DefId)) -> (), - [] fn borrowck: BorrowCheck(DefId) -> Rc, + [] fn borrowck: BorrowCheck(DefId) -> Lrc, /// Borrow checks the function body. If this is a closure, returns /// additional requirements that the closure's creator must verify. @@ -214,13 +214,13 @@ define_maps! { <'tcx> -> Result<(), ErrorReported>, /// Performs the privacy check and computes "access levels". - [] fn privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Rc, + [] fn privacy_access_levels: PrivacyAccessLevels(CrateNum) -> Lrc, [] fn reachable_set: reachability_dep_node(CrateNum) -> ReachableSet, /// Per-body `region::ScopeTree`. The `DefId` should be the owner-def-id for the body; /// in the case of closures, this will be redirected to the enclosing function. - [] fn region_scope_tree: RegionScopeTree(DefId) -> Rc, + [] fn region_scope_tree: RegionScopeTree(DefId) -> Lrc, [] fn mir_shims: mir_shim_dep_node(ty::InstanceDef<'tcx>) -> &'tcx mir::Mir<'tcx>, @@ -231,22 +231,22 @@ define_maps! { <'tcx> [] fn def_span: DefSpan(DefId) -> Span, [] fn lookup_stability: LookupStability(DefId) -> Option<&'tcx attr::Stability>, [] fn lookup_deprecation_entry: LookupDeprecationEntry(DefId) -> Option, - [] fn item_attrs: ItemAttrs(DefId) -> Rc<[ast::Attribute]>, + [] fn item_attrs: ItemAttrs(DefId) -> Lrc<[ast::Attribute]>, [] fn fn_arg_names: FnArgNames(DefId) -> Vec, [] fn impl_parent: ImplParent(DefId) -> Option, [] fn trait_of_item: TraitOfItem(DefId) -> Option, [] fn is_exported_symbol: IsExportedSymbol(DefId) -> bool, [] fn item_body_nested_bodies: ItemBodyNestedBodies(DefId) -> ExternBodyNestedBodies, [] fn const_is_rvalue_promotable_to_static: ConstIsRvaluePromotableToStatic(DefId) -> bool, - [] fn rvalue_promotable_map: RvaluePromotableMap(DefId) -> Rc, + [] fn rvalue_promotable_map: RvaluePromotableMap(DefId) -> Lrc, [] fn is_mir_available: IsMirAvailable(DefId) -> bool, [] fn vtable_methods: vtable_methods_node(ty::PolyTraitRef<'tcx>) - -> Rc)>>>, + -> Lrc)>>>, [] fn trans_fulfill_obligation: fulfill_obligation_dep_node( (ty::ParamEnv<'tcx>, ty::PolyTraitRef<'tcx>)) -> Vtable<'tcx, ()>, - [] fn trait_impls_of: TraitImpls(DefId) -> Rc, - [] fn specialization_graph_of: SpecializationGraph(DefId) -> Rc, + [] fn trait_impls_of: TraitImpls(DefId) -> Lrc, + [] fn specialization_graph_of: SpecializationGraph(DefId) -> Lrc, [] fn is_object_safe: ObjectSafety(DefId) -> bool, // Get the ParameterEnvironment for a given item; this environment @@ -268,7 +268,7 @@ define_maps! { <'tcx> ty::layout::LayoutError<'tcx>>, [] fn dylib_dependency_formats: DylibDepFormats(CrateNum) - -> Rc>, + -> Lrc>, [] fn is_panic_runtime: IsPanicRuntime(CrateNum) -> bool, [] fn is_compiler_builtins: IsCompilerBuiltins(CrateNum) -> bool, @@ -278,17 +278,17 @@ define_maps! { <'tcx> [] fn panic_strategy: GetPanicStrategy(CrateNum) -> PanicStrategy, [] fn is_no_builtins: IsNoBuiltins(CrateNum) -> bool, - [] fn extern_crate: ExternCrate(DefId) -> Rc>, + [] fn extern_crate: ExternCrate(DefId) -> Lrc>, [] fn specializes: specializes_node((DefId, DefId)) -> bool, [] fn in_scope_traits_map: InScopeTraits(DefIndex) - -> Option>>>>, - [] fn module_exports: ModuleExports(DefId) -> Option>>, - [] fn lint_levels: lint_levels_node(CrateNum) -> Rc, + -> Option>>>>, + [] fn module_exports: ModuleExports(DefId) -> Option>>, + [] fn lint_levels: lint_levels_node(CrateNum) -> Lrc, [] fn impl_defaultness: ImplDefaultness(DefId) -> hir::Defaultness, - [] fn exported_symbol_ids: ExportedSymbolIds(CrateNum) -> Rc, - [] fn native_libraries: NativeLibraries(CrateNum) -> Rc>, + [] fn exported_symbol_ids: ExportedSymbolIds(CrateNum) -> Lrc, + [] fn native_libraries: NativeLibraries(CrateNum) -> Lrc>, [] fn plugin_registrar_fn: PluginRegistrarFn(CrateNum) -> Option, [] fn derive_registrar_fn: DeriveRegistrarFn(CrateNum) -> Option, [] fn crate_disambiguator: CrateDisambiguator(CrateNum) -> CrateDisambiguator, @@ -296,48 +296,48 @@ define_maps! { <'tcx> [] fn original_crate_name: OriginalCrateName(CrateNum) -> Symbol, [] fn implementations_of_trait: implementations_of_trait_node((CrateNum, DefId)) - -> Rc>, + -> Lrc>, [] fn all_trait_implementations: AllTraitImplementations(CrateNum) - -> Rc>, + -> Lrc>, [] fn is_dllimport_foreign_item: IsDllimportForeignItem(DefId) -> bool, [] fn is_statically_included_foreign_item: IsStaticallyIncludedForeignItem(DefId) -> bool, [] fn native_library_kind: NativeLibraryKind(DefId) -> Option, - [] fn link_args: link_args_node(CrateNum) -> Rc>, + [] fn link_args: link_args_node(CrateNum) -> Lrc>, // Lifetime resolution. See `middle::resolve_lifetimes`. - [] fn resolve_lifetimes: ResolveLifetimes(CrateNum) -> Rc, + [] fn resolve_lifetimes: ResolveLifetimes(CrateNum) -> Lrc, [] fn named_region_map: NamedRegion(DefIndex) -> - Option>>, + Option>>, [] fn is_late_bound_map: IsLateBound(DefIndex) -> - Option>>, + Option>>, [] fn object_lifetime_defaults_map: ObjectLifetimeDefaults(DefIndex) - -> Option>>>>, + -> Option>>>>, [] fn visibility: Visibility(DefId) -> ty::Visibility, [] fn dep_kind: DepKind(CrateNum) -> DepKind, [] fn crate_name: CrateName(CrateNum) -> Symbol, - [] fn item_children: ItemChildren(DefId) -> Rc>, + [] fn item_children: ItemChildren(DefId) -> Lrc>, [] fn extern_mod_stmt_cnum: ExternModStmtCnum(DefId) -> Option, - [] fn get_lang_items: get_lang_items_node(CrateNum) -> Rc, - [] fn defined_lang_items: DefinedLangItems(CrateNum) -> Rc>, - [] fn missing_lang_items: MissingLangItems(CrateNum) -> Rc>, + [] fn get_lang_items: get_lang_items_node(CrateNum) -> Lrc, + [] fn defined_lang_items: DefinedLangItems(CrateNum) -> Lrc>, + [] fn missing_lang_items: MissingLangItems(CrateNum) -> Lrc>, [] fn extern_const_body: ExternConstBody(DefId) -> ExternConstBody<'tcx>, [] fn visible_parent_map: visible_parent_map_node(CrateNum) - -> Rc>, + -> Lrc>, [] fn missing_extern_crate_item: MissingExternCrateItem(CrateNum) -> bool, - [] fn used_crate_source: UsedCrateSource(CrateNum) -> Rc, - [] fn postorder_cnums: postorder_cnums_node(CrateNum) -> Rc>, + [] fn used_crate_source: UsedCrateSource(CrateNum) -> Lrc, + [] fn postorder_cnums: postorder_cnums_node(CrateNum) -> Lrc>, - [] fn freevars: Freevars(DefId) -> Option>>, + [] fn freevars: Freevars(DefId) -> Option>>, [] fn maybe_unused_trait_import: MaybeUnusedTraitImport(DefId) -> bool, [] fn maybe_unused_extern_crates: maybe_unused_extern_crates_node(CrateNum) - -> Rc>, + -> Lrc>, - [] fn stability_index: stability_index_node(CrateNum) -> Rc>, - [] fn all_crate_nums: all_crate_nums_node(CrateNum) -> Rc>, + [] fn stability_index: stability_index_node(CrateNum) -> Lrc>, + [] fn all_crate_nums: all_crate_nums_node(CrateNum) -> Lrc>, [] fn exported_symbols: ExportedSymbols(CrateNum) -> Arc, SymbolExportLevel)>>, diff --git a/src/librustc/ty/maps/on_disk_cache.rs b/src/librustc/ty/maps/on_disk_cache.rs index 079b518efd898..105b1703fa213 100644 --- a/src/librustc/ty/maps/on_disk_cache.rs +++ b/src/librustc/ty/maps/on_disk_cache.rs @@ -17,14 +17,13 @@ use hir::map::definitions::DefPathHash; use ich::CachingCodemapView; use mir; use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::sync::{Lrc, Lock}; use rustc_data_structures::indexed_vec::{IndexVec, Idx}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder, opaque, SpecializedDecoder, SpecializedEncoder, UseSpecializedDecodable, UseSpecializedEncodable}; use session::{CrateDisambiguator, Session}; -use std::cell::RefCell; use std::mem; -use std::rc::Rc; use syntax::ast::NodeId; use syntax::codemap::{CodeMap, StableFilemapId}; use syntax_pos::{BytePos, Span, DUMMY_SP, FileMap}; @@ -56,17 +55,17 @@ pub struct OnDiskCache<'sess> { // This field collects all Diagnostics emitted during the current // compilation session. - current_diagnostics: RefCell>>, + current_diagnostics: Lock>>, prev_cnums: Vec<(u32, String, CrateDisambiguator)>, - cnum_map: RefCell>>>, + cnum_map: Lock>>>, codemap: &'sess CodeMap, file_index_to_stable_id: FxHashMap, // These two fields caches that are populated lazily during decoding. - file_index_to_file: RefCell>>, - synthetic_expansion_infos: RefCell>, + file_index_to_file: Lock>>, + synthetic_expansion_infos: Lock>, // A map from dep-node to the position of the cached query result in // `serialized_data`. @@ -132,14 +131,14 @@ impl<'sess> OnDiskCache<'sess> { OnDiskCache { serialized_data: data, file_index_to_stable_id: footer.file_index_to_stable_id, - file_index_to_file: RefCell::new(FxHashMap()), + file_index_to_file: Lock::new(FxHashMap()), prev_cnums: footer.prev_cnums, - cnum_map: RefCell::new(None), + cnum_map: Lock::new(None), codemap: sess.codemap(), - current_diagnostics: RefCell::new(FxHashMap()), + current_diagnostics: Lock::new(FxHashMap()), query_result_index: footer.query_result_index.into_iter().collect(), prev_diagnostics_index: footer.diagnostics_index.into_iter().collect(), - synthetic_expansion_infos: RefCell::new(FxHashMap()), + synthetic_expansion_infos: Lock::new(FxHashMap()), } } @@ -147,14 +146,14 @@ impl<'sess> OnDiskCache<'sess> { OnDiskCache { serialized_data: Vec::new(), file_index_to_stable_id: FxHashMap(), - file_index_to_file: RefCell::new(FxHashMap()), + file_index_to_file: Lock::new(FxHashMap()), prev_cnums: vec![], - cnum_map: RefCell::new(None), + cnum_map: Lock::new(None), codemap, - current_diagnostics: RefCell::new(FxHashMap()), + current_diagnostics: Lock::new(FxHashMap()), query_result_index: FxHashMap(), prev_diagnostics_index: FxHashMap(), - synthetic_expansion_infos: RefCell::new(FxHashMap()), + synthetic_expansion_infos: Lock::new(FxHashMap()), } } @@ -356,9 +355,9 @@ impl<'sess> OnDiskCache<'sess> { opaque: opaque::Decoder::new(&self.serialized_data[..], pos.to_usize()), codemap: self.codemap, cnum_map: cnum_map.as_ref().unwrap(), - file_index_to_file: &mut file_index_to_file, + file_index_to_file: &mut *file_index_to_file, file_index_to_stable_id: &self.file_index_to_stable_id, - synthetic_expansion_infos: &mut synthetic_expansion_infos, + synthetic_expansion_infos: &mut *synthetic_expansion_infos, }; match decode_tagged(&mut decoder, dep_node_index) { @@ -418,12 +417,12 @@ struct CacheDecoder<'a, 'tcx: 'a, 'x> { codemap: &'x CodeMap, cnum_map: &'x IndexVec>, synthetic_expansion_infos: &'x mut FxHashMap, - file_index_to_file: &'x mut FxHashMap>, + file_index_to_file: &'x mut FxHashMap>, file_index_to_stable_id: &'x FxHashMap, } impl<'a, 'tcx, 'x> CacheDecoder<'a, 'tcx, 'x> { - fn file_index_to_file(&mut self, index: FileMapIndex) -> Rc { + fn file_index_to_file(&mut self, index: FileMapIndex) -> Lrc { let CacheDecoder { ref mut file_index_to_file, ref file_index_to_stable_id, @@ -696,7 +695,7 @@ struct CacheEncoder<'enc, 'a, 'tcx, E> impl<'enc, 'a, 'tcx, E> CacheEncoder<'enc, 'a, 'tcx, E> where E: 'enc + ty_codec::TyEncoder { - fn filemap_index(&mut self, filemap: Rc) -> FileMapIndex { + fn filemap_index(&mut self, filemap: Lrc) -> FileMapIndex { self.file_to_file_index[&(&*filemap as *const FileMap)] } diff --git a/src/librustc/ty/maps/plumbing.rs b/src/librustc/ty/maps/plumbing.rs index 8875439be6b3d..254c71636e535 100644 --- a/src/librustc/ty/maps/plumbing.rs +++ b/src/librustc/ty/maps/plumbing.rs @@ -20,7 +20,7 @@ use ty::maps::config::QueryDescription; use ty::item_path; use rustc_data_structures::fx::{FxHashMap}; -use std::cell::{Ref, RefMut}; +use rustc_data_structures::sync::LockGuard; use std::marker::PhantomData; use std::mem; use syntax_pos::Span; @@ -57,12 +57,12 @@ impl<'tcx, M: QueryDescription<'tcx>> QueryMap<'tcx, M> { pub(super) trait GetCacheInternal<'tcx>: QueryDescription<'tcx> + Sized { fn get_cache_internal<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>) - -> Ref<'a, QueryMap<'tcx, Self>>; + -> LockGuard<'a, QueryMap<'tcx, Self>>; } pub(super) struct CycleError<'a, 'tcx: 'a> { span: Span, - cycle: RefMut<'a, [(Span, Query<'tcx>)]>, + cycle: LockGuard<'a, [(Span, Query<'tcx>)]>, } impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { @@ -112,7 +112,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { .find(|&(_, &(_, ref q))| *q == query) { return Err(CycleError { span, - cycle: RefMut::map(stack, |stack| &mut stack[i..]) + cycle: LockGuard::map(stack, |stack| &mut stack[i..]) }); } stack.push((span, query)); @@ -189,7 +189,7 @@ macro_rules! define_maps { [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*) => { use dep_graph::DepNodeIndex; - use std::cell::RefCell; + use rustc_data_structures::sync::{Lock, LockGuard}; define_map_struct! { tcx: $tcx, @@ -201,8 +201,8 @@ macro_rules! define_maps { -> Self { Maps { providers, - query_stack: RefCell::new(vec![]), - $($name: RefCell::new(QueryMap::new())),* + query_stack: Lock::new(vec![]), + $($name: Lock::new(QueryMap::new())),* } } } @@ -250,7 +250,7 @@ macro_rules! define_maps { impl<$tcx> GetCacheInternal<$tcx> for queries::$name<$tcx> { fn get_cache_internal<'a>(tcx: TyCtxt<'a, $tcx, $tcx>) - -> ::std::cell::Ref<'a, QueryMap<$tcx, Self>> { + -> LockGuard<'a, QueryMap<$tcx, Self>> { tcx.maps.$name.borrow() } } @@ -586,8 +586,8 @@ macro_rules! define_map_struct { input: ($(([$(modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => { pub struct Maps<$tcx> { providers: IndexVec>, - query_stack: RefCell)>>, - $($(#[$attr])* $name: RefCell>>,)* + query_stack: Lock)>>, + $($(#[$attr])* $name: Lock>>,)* } }; } diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs index e03e1237466e6..e6ad5084b5022 100644 --- a/src/librustc/ty/mod.rs +++ b/src/librustc/ty/mod.rs @@ -42,7 +42,7 @@ use std::fmt; use std::hash::{Hash, Hasher}; use std::iter::FromIterator; use std::ops::Deref; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use std::slice; use std::vec::IntoIter; use std::mem; @@ -124,7 +124,7 @@ mod sty; /// *on-demand* infrastructure. #[derive(Clone)] pub struct CrateAnalysis { - pub access_levels: Rc, + pub access_levels: Lrc, pub name: String, pub glob_map: Option, } @@ -336,10 +336,10 @@ pub struct CrateVariancesMap { /// For each item with generics, maps to a vector of the variance /// of its generics. If an item has no generics, it will have no /// entry. - pub variances: FxHashMap>>, + pub variances: FxHashMap>>, /// An empty vector, useful for cloning. - pub empty_variance: Rc>, + pub empty_variance: Lrc>, } impl Variance { @@ -2102,7 +2102,7 @@ impl BorrowKind { #[derive(Debug, Clone)] pub enum Attributes<'gcx> { - Owned(Rc<[ast::Attribute]>), + Owned(Lrc<[ast::Attribute]>), Borrowed(&'gcx [ast::Attribute]) } @@ -2587,7 +2587,7 @@ fn adt_dtorck_constraint<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) - -> Rc> { + -> Lrc> { let id = tcx.hir.as_local_node_id(def_id).unwrap(); let item = tcx.hir.expect_item(id); let vec: Vec<_> = match item.node { @@ -2606,7 +2606,7 @@ fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, hir::ItemTraitAlias(..) => vec![], _ => span_bug!(item.span, "associated_item_def_ids: not impl or trait") }; - Rc::new(vec) + Lrc::new(vec) } fn def_span<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Span { @@ -2696,7 +2696,7 @@ pub fn provide(providers: &mut ty::maps::Providers) { /// (constructing this map requires touching the entire crate). #[derive(Clone, Debug)] pub struct CrateInherentImpls { - pub inherent_impls: DefIdMap>>, + pub inherent_impls: DefIdMap>>, } /// A set of constraints that need to be satisfied in order for diff --git a/src/librustc/ty/steal.rs b/src/librustc/ty/steal.rs index 0b0818888812f..08f48dfb6d924 100644 --- a/src/librustc/ty/steal.rs +++ b/src/librustc/ty/steal.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::cell::{Ref, RefCell}; +use rustc_data_structures::sync::{RwLock, ReadGuard}; use std::mem; /// The `Steal` struct is intended to used as the value for a query. @@ -32,18 +32,18 @@ use std::mem; /// /// FIXME(#41710) -- what is the best way to model linear queries? pub struct Steal { - value: RefCell> + value: RwLock> } impl Steal { pub fn new(value: T) -> Self { Steal { - value: RefCell::new(Some(value)) + value: RwLock::new(Some(value)) } } - pub fn borrow(&self) -> Ref { - Ref::map(self.value.borrow(), |opt| match *opt { + pub fn borrow(&self) -> ReadGuard { + ReadGuard::map(self.value.borrow(), |opt| match *opt { None => bug!("attempted to read from stolen value"), Some(ref v) => v }) diff --git a/src/librustc/ty/trait_def.rs b/src/librustc/ty/trait_def.rs index 0fbf9f1bd587b..62d3c8dc87da3 100644 --- a/src/librustc/ty/trait_def.rs +++ b/src/librustc/ty/trait_def.rs @@ -20,7 +20,7 @@ use ty::{Ty, TyCtxt}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult}; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; /// A trait's definition with type information. pub struct TraitDef { @@ -142,7 +142,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { // Query provider for `trait_impls_of`. pub(super) fn trait_impls_of_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_id: DefId) - -> Rc { + -> Lrc { let mut remote_impls = Vec::new(); // Traits defined in the current crate can't have impls in upstream @@ -180,7 +180,7 @@ pub(super) fn trait_impls_of_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } } - Rc::new(TraitImpls { + Lrc::new(TraitImpls { blanket_impls: blanket_impls, non_blanket_impls: non_blanket_impls, }) diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index 76d3494dbf082..51a9034ec3f8c 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -10,6 +10,8 @@ #![allow(non_camel_case_types)] +use rustc_data_structures::sync::LockCell; + use std::cell::{RefCell, Cell}; use std::collections::HashMap; use std::ffi::CString; @@ -205,7 +207,7 @@ pub fn to_readable_str(mut val: usize) -> String { groups.join("_") } -pub fn record_time(accu: &Cell, f: F) -> T where +pub fn record_time(accu: &LockCell, f: F) -> T where F: FnOnce() -> T, { let start = Instant::now(); diff --git a/src/librustc_borrowck/Cargo.toml b/src/librustc_borrowck/Cargo.toml index 25f02537490fa..abc1fc759f696 100644 --- a/src/librustc_borrowck/Cargo.toml +++ b/src/librustc_borrowck/Cargo.toml @@ -17,3 +17,4 @@ graphviz = { path = "../libgraphviz" } rustc = { path = "../librustc" } rustc_mir = { path = "../librustc_mir" } rustc_errors = { path = "../librustc_errors" } +rustc_data_structures = { path = "../librustc_data_structures" } \ No newline at end of file diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs index b124872ba12ca..f206cf0e3155d 100644 --- a/src/librustc_borrowck/borrowck/mod.rs +++ b/src/librustc_borrowck/borrowck/mod.rs @@ -44,6 +44,7 @@ use rustc::util::nodemap::FxHashSet; use std::cell::RefCell; use std::fmt; use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use std::hash::{Hash, Hasher}; use syntax::ast; use syntax_pos::{MultiSpan, Span}; @@ -86,7 +87,7 @@ pub struct AnalysisData<'a, 'tcx: 'a> { } fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId) - -> Rc + -> Lrc { debug!("borrowck(body_owner_def_id={:?})", owner_def_id); @@ -99,7 +100,7 @@ fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId) // those things (notably the synthesized constructors from // tuple structs/variants) do not have an associated body // and do not need borrowchecking. - return Rc::new(BorrowCheckResult { + return Lrc::new(BorrowCheckResult { used_mut_nodes: FxHashSet(), }) } @@ -127,7 +128,7 @@ fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId) // Note that `mir_validated` is a "stealable" result; the // thief, `optimized_mir()`, forces borrowck, so we know that // is not yet stolen. - tcx.mir_validated(owner_def_id).borrow(); + let _guard = tcx.mir_validated(owner_def_id).borrow(); // option dance because you can't capture an uninitialized variable // by mut-ref. @@ -145,7 +146,7 @@ fn borrowck<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, owner_def_id: DefId) } unused::check(&mut bccx, body); - Rc::new(BorrowCheckResult { + Lrc::new(BorrowCheckResult { used_mut_nodes: bccx.used_mut_nodes.into_inner(), }) } @@ -243,7 +244,7 @@ pub struct BorrowckCtxt<'a, 'tcx: 'a> { // Some in `borrowck_fn` and cleared later tables: &'a ty::TypeckTables<'tcx>, - region_scope_tree: Rc, + region_scope_tree: Lrc, owner_def_id: DefId, diff --git a/src/librustc_borrowck/lib.rs b/src/librustc_borrowck/lib.rs index be173db23a52a..2bdee3198f22a 100644 --- a/src/librustc_borrowck/lib.rs +++ b/src/librustc_borrowck/lib.rs @@ -23,6 +23,7 @@ extern crate syntax; extern crate syntax_pos; extern crate rustc_errors as errors; +extern crate rustc_data_structures; // for "clarity", rename the graphviz crate to dot; graphviz within `borrowck` // refers to the borrowck-specific graphviz adapter traits. diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index c0bbab35e1e95..18fd4062c825e 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -51,7 +51,7 @@ use std::fs; use std::io::{self, Write}; use std::iter; use std::path::{Path, PathBuf}; -use std::rc::Rc; +use rustc_data_structures::sync::{Sync, Lrc}; use std::sync::mpsc; use syntax::{ast, diagnostics, visit}; use syntax::attr; @@ -919,7 +919,7 @@ pub fn phase_2_configure_and_expand(sess: &Session, expanded_crate: krate, defs: resolver.definitions, analysis: ty::CrateAnalysis { - access_levels: Rc::new(AccessLevels::default()), + access_levels: Lrc::new(AccessLevels::default()), name: crate_name.to_string(), glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None }, }, @@ -962,7 +962,7 @@ pub fn default_provide_extern(providers: &mut ty::maps::Providers) { /// structures carrying the results of the analysis. pub fn phase_3_run_analysis_passes<'tcx, F, R>(control: &CompileController, sess: &'tcx Session, - cstore: &'tcx CrateStore, + cstore: &'tcx (CrateStore + Sync), hir_map: hir_map::Map<'tcx>, mut analysis: ty::CrateAnalysis, resolutions: Resolutions, diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 5fa823659287a..e5b4d47c49c4d 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -25,6 +25,8 @@ #![feature(rustc_diagnostic_macros)] #![feature(set_stdio)] +#![recursion_limit="256"] + extern crate arena; extern crate getopts; extern crate graphviz; @@ -89,9 +91,9 @@ use std::io::{self, Read, Write}; use std::iter::repeat; use std::path::PathBuf; use std::process::{self, Command, Stdio}; -use std::rc::Rc; use std::str; use std::sync::{Arc, Mutex}; +use rustc_data_structures::sync::Lrc; use std::thread; use syntax::ast; @@ -187,7 +189,7 @@ mod rustc_trans { // The FileLoader provides a way to load files from sources other than the file system. pub fn run_compiler<'a>(args: &[String], callbacks: &mut CompilerCalls<'a>, - file_loader: Option>, + file_loader: Option>, emitter_dest: Option>) -> (CompileResult, Option) { @@ -230,7 +232,7 @@ pub fn run_compiler<'a>(args: &[String], let cstore = CStore::new(DefaultTransCrate::metadata_loader()); let loader = file_loader.unwrap_or(box RealFileLoader); - let codemap = Rc::new(CodeMap::with_file_loader(loader, sopts.file_path_mapping())); + let codemap = Lrc::new(CodeMap::with_file_loader(loader, sopts.file_path_mapping())); let mut sess = session::build_session_with_codemap( sopts, input_file_path.clone(), descriptions, codemap, emitter_dest, ); diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 76923be65cfd7..fd25add0e98b0 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -17,6 +17,7 @@ use self::NodesMatchingUII::*; use {abort_on_err, driver}; +use rustc_data_structures::sync::Sync; use rustc::ty::{self, TyCtxt, Resolutions, AllArenas}; use rustc::cfg; use rustc::cfg::graphviz::LabelledCFG; @@ -199,7 +200,7 @@ impl PpSourceMode { } fn call_with_pp_support_hir<'tcx, A, F>(&self, sess: &'tcx Session, - cstore: &'tcx CrateStore, + cstore: &'tcx (CrateStore + Sync), hir_map: &hir_map::Map<'tcx>, analysis: &ty::CrateAnalysis, resolutions: &Resolutions, @@ -902,7 +903,7 @@ pub fn print_after_parsing(sess: &Session, } pub fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session, - cstore: &'tcx CrateStore, + cstore: &'tcx (CrateStore + Sync), hir_map: &hir_map::Map<'tcx>, analysis: &ty::CrateAnalysis, resolutions: &Resolutions, @@ -1058,7 +1059,7 @@ pub fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session, // with a different callback than the standard driver, so that isn't easy. // Instead, we call that function ourselves. fn print_with_analysis<'tcx, 'a: 'tcx>(sess: &'a Session, - cstore: &'a CrateStore, + cstore: &'a (CrateStore + Sync), hir_map: &hir_map::Map<'tcx>, analysis: &ty::CrateAnalysis, resolutions: &Resolutions, diff --git a/src/librustc_driver/test.rs b/src/librustc_driver/test.rs index 6765ea5e67a60..1421270395750 100644 --- a/src/librustc_driver/test.rs +++ b/src/librustc_driver/test.rs @@ -31,6 +31,7 @@ use rustc::session::{self, config}; use rustc::session::config::{OutputFilenames, OutputTypes}; use rustc_trans_utils::trans_crate::TransCrate; use std::rc::Rc; +use rustc_data_structures::sync::{Send, Lrc}; use syntax::ast; use syntax::abi::Abi; use syntax::codemap::{CodeMap, FilePathMapping, FileName}; @@ -108,7 +109,7 @@ fn test_env(source_string: &str, let sess = session::build_session_(options, None, diagnostic_handler, - Rc::new(CodeMap::new(FilePathMapping::empty()))); + Lrc::new(CodeMap::new(FilePathMapping::empty()))); rustc_trans::init(&sess); rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess)); let input = config::Input::Str { diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs index af556c576c035..59143651865b0 100644 --- a/src/librustc_errors/emitter.rs +++ b/src/librustc_errors/emitter.rs @@ -12,14 +12,14 @@ use self::Destination::*; use syntax_pos::{DUMMY_SP, FileMap, Span, MultiSpan}; -use {Level, CodeSuggestion, DiagnosticBuilder, SubDiagnostic, CodeMapper, DiagnosticId}; +use {Level, CodeSuggestion, DiagnosticBuilder, SubDiagnostic, CodeMapperDyn, DiagnosticId}; use snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, StyledString, Style}; use styled_buffer::StyledBuffer; +use rustc_data_structures::sync::Lrc; use std::borrow::Cow; use std::io::prelude::*; use std::io; -use std::rc::Rc; use term; use std::collections::HashMap; use std::cmp::min; @@ -104,19 +104,19 @@ impl ColorConfig { pub struct EmitterWriter { dst: Destination, - cm: Option>, + cm: Option>, short_message: bool, } struct FileWithAnnotatedLines { - file: Rc, + file: Lrc, lines: Vec, multiline_depth: usize, } impl EmitterWriter { pub fn stderr(color_config: ColorConfig, - code_map: Option>, + code_map: Option>, short_message: bool) -> EmitterWriter { if color_config.use_color() { @@ -136,7 +136,7 @@ impl EmitterWriter { } pub fn new(dst: Box, - code_map: Option>, + code_map: Option>, short_message: bool) -> EmitterWriter { EmitterWriter { @@ -148,7 +148,7 @@ impl EmitterWriter { fn preprocess_annotations(&mut self, msp: &MultiSpan) -> Vec { fn add_annotation_to_file(file_vec: &mut Vec, - file: Rc, + file: Lrc, line_index: usize, ann: Annotation) { @@ -280,7 +280,7 @@ impl EmitterWriter { fn render_source_line(&self, buffer: &mut StyledBuffer, - file: Rc, + file: Lrc, line: &Line, width_offset: usize, code_offset: usize) -> Vec<(usize, Style)> { @@ -1133,8 +1133,6 @@ impl EmitterWriter { level: &Level, max_line_num_len: usize) -> io::Result<()> { - use std::borrow::Borrow; - if let Some(ref cm) = self.cm { let mut buffer = StyledBuffer::new(); @@ -1148,7 +1146,7 @@ impl EmitterWriter { Some(Style::HeaderMsg)); // Render the replacements for each suggestion - let suggestions = suggestion.splice_lines(cm.borrow()); + let suggestions = suggestion.splice_lines(&**cm); let mut row_num = 2; for &(ref complete, ref parts) in suggestions.iter().take(MAX_SUGGESTIONS) { diff --git a/src/librustc_errors/lib.rs b/src/librustc_errors/lib.rs index 2ac49958d3c53..ffe9a237ec1d0 100644 --- a/src/librustc_errors/lib.rs +++ b/src/librustc_errors/lib.rs @@ -34,13 +34,12 @@ use self::Level::*; use emitter::{Emitter, EmitterWriter}; +use rustc_data_structures::sync::{Lrc, Lock, LockCell, Send, Sync}; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::stable_hasher::StableHasher; use std::borrow::Cow; -use std::cell::{RefCell, Cell}; use std::mem; -use std::rc::Rc; use std::{error, fmt}; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; @@ -95,6 +94,8 @@ pub struct SubstitutionPart { pub snippet: String, } +pub type CodeMapperDyn = CodeMapper + Send + Sync; + pub trait CodeMapper { fn lookup_char_pos(&self, pos: BytePos) -> Loc; fn span_to_lines(&self, sp: Span) -> FileLinesResult; @@ -102,12 +103,13 @@ pub trait CodeMapper { fn span_to_filename(&self, sp: Span) -> FileName; fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option; fn call_span_if_macro(&self, sp: Span) -> Span; - fn ensure_filemap_source_present(&self, file_map: Rc) -> bool; + fn ensure_filemap_source_present(&self, file_map: Lrc) -> bool; } impl CodeSuggestion { /// Returns the assembled code suggestions and whether they should be shown with an underline. - pub fn splice_lines(&self, cm: &CodeMapper) -> Vec<(String, Vec)> { + pub fn splice_lines(&self, cm: &CodeMapperDyn) + -> Vec<(String, Vec)> { use syntax_pos::{CharPos, Loc, Pos}; fn push_trailing(buf: &mut String, @@ -239,15 +241,15 @@ pub struct Handler { pub flags: HandlerFlags, err_count: AtomicUsize, - emitter: RefCell>, - continue_after_error: Cell, - delayed_span_bug: RefCell>, - tracked_diagnostics: RefCell>>, + emitter: Lock>, + continue_after_error: LockCell, + delayed_span_bug: Lock>, + tracked_diagnostics: Lock>>, // This set contains a hash of every diagnostic that has been emitted by // this handler. These hashes is used to avoid emitting the same error // twice. - emitted_diagnostics: RefCell>, + emitted_diagnostics: Lock>, } #[derive(Default)] @@ -261,7 +263,7 @@ impl Handler { pub fn with_tty_emitter(color_config: ColorConfig, can_emit_warnings: bool, treat_err_as_bug: bool, - cm: Option>) + cm: Option>) -> Handler { Handler::with_tty_emitter_and_flags( color_config, @@ -274,7 +276,7 @@ impl Handler { } pub fn with_tty_emitter_and_flags(color_config: ColorConfig, - cm: Option>, + cm: Option>, flags: HandlerFlags) -> Handler { let emitter = Box::new(EmitterWriter::stderr(color_config, cm, false)); @@ -283,7 +285,7 @@ impl Handler { pub fn with_emitter(can_emit_warnings: bool, treat_err_as_bug: bool, - e: Box) + e: Box) -> Handler { Handler::with_emitter_and_flags( e, @@ -294,15 +296,15 @@ impl Handler { }) } - pub fn with_emitter_and_flags(e: Box, flags: HandlerFlags) -> Handler { + pub fn with_emitter_and_flags(e: Box, flags: HandlerFlags) -> Handler { Handler { flags, err_count: AtomicUsize::new(0), - emitter: RefCell::new(e), - continue_after_error: Cell::new(true), - delayed_span_bug: RefCell::new(None), - tracked_diagnostics: RefCell::new(None), - emitted_diagnostics: RefCell::new(FxHashSet()), + emitter: Lock::new(e), + continue_after_error: LockCell::new(true), + delayed_span_bug: Lock::new(None), + tracked_diagnostics: Lock::new(None), + emitted_diagnostics: Lock::new(FxHashSet()), } } diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs index 58453066cf34b..0265bb8962be0 100644 --- a/src/librustc_metadata/creader.rs +++ b/src/librustc_metadata/creader.rs @@ -14,6 +14,7 @@ use cstore::{self, CStore, CrateSource, MetadataBlob}; use locator::{self, CratePaths}; use native_libs::relevant_lib; use schema::CrateRoot; +use rustc_data_structures::sync::{Lrc, RwLock, Lock, LockCell}; use rustc::hir::def_id::{CrateNum, DefIndex, CRATE_DEF_INDEX}; use rustc::hir::svh::Svh; @@ -29,10 +30,8 @@ use rustc::util::common::record_time; use rustc::util::nodemap::FxHashSet; use rustc::hir::map::Definitions; -use std::cell::{RefCell, Cell}; use std::ops::Deref; use std::path::PathBuf; -use std::rc::Rc; use std::{cmp, fs}; use syntax::ast; @@ -79,7 +78,7 @@ struct ExtensionCrate { } enum PMDSource { - Registered(Rc), + Registered(Lrc), Owned(Library), } @@ -194,7 +193,7 @@ impl<'a> CrateLoader<'a> { span: Span, lib: Library, dep_kind: DepKind) - -> (CrateNum, Rc) { + -> (CrateNum, Lrc) { info!("register crate `extern crate {} as {}`", name, ident); let crate_root = lib.metadata.get_root(); self.verify_no_symbol_conflicts(span, &crate_root); @@ -236,8 +235,8 @@ impl<'a> CrateLoader<'a> { let mut cmeta = cstore::CrateMetadata { name, - extern_crate: Cell::new(None), - def_path_table: Rc::new(def_path_table), + extern_crate: LockCell::new(None), + def_path_table: Lrc::new(def_path_table), exported_symbols, trait_impls, proc_macros: crate_root.macro_derive_registrar.map(|_| { @@ -245,11 +244,11 @@ impl<'a> CrateLoader<'a> { }), root: crate_root, blob: metadata, - cnum_map: RefCell::new(cnum_map), + cnum_map: Lock::new(cnum_map), cnum, - codemap_import_info: RefCell::new(vec![]), - attribute_cache: RefCell::new([Vec::new(), Vec::new()]), - dep_kind: Cell::new(dep_kind), + codemap_import_info: RwLock::new(vec![]), + attribute_cache: Lock::new([Vec::new(), Vec::new()]), + dep_kind: LockCell::new(dep_kind), source: cstore::CrateSource { dylib, rlib, @@ -274,7 +273,7 @@ impl<'a> CrateLoader<'a> { cmeta.dllimport_foreign_items = dllimports; - let cmeta = Rc::new(cmeta); + let cmeta = Lrc::new(cmeta); self.cstore.set_crate_data(cnum, cmeta.clone()); (cnum, cmeta) } @@ -287,7 +286,7 @@ impl<'a> CrateLoader<'a> { span: Span, path_kind: PathKind, mut dep_kind: DepKind) - -> (CrateNum, Rc) { + -> (CrateNum, Lrc) { info!("resolving crate `extern crate {} as {}`", name, ident); let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) { LoadResult::Previous(cnum) @@ -513,7 +512,7 @@ impl<'a> CrateLoader<'a> { /// custom derive (and other macro-1.1 style features) are implemented via /// executables and custom IPC. fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option, span: Span) - -> Vec<(ast::Name, Rc)> { + -> Vec<(ast::Name, Lrc)> { use std::{env, mem}; use proc_macro::TokenStream; use proc_macro::__internal::Registry; @@ -542,7 +541,7 @@ impl<'a> CrateLoader<'a> { mem::transmute::<*mut u8, fn(&mut Registry)>(sym) }; - struct MyRegistrar(Vec<(ast::Name, Rc)>); + struct MyRegistrar(Vec<(ast::Name, Lrc)>); impl Registry for MyRegistrar { fn register_custom_derive(&mut self, @@ -552,7 +551,7 @@ impl<'a> CrateLoader<'a> { let attrs = attributes.iter().cloned().map(Symbol::intern).collect::>(); let derive = ProcMacroDerive::new(expand, attrs.clone()); let derive = SyntaxExtension::ProcMacroDerive(Box::new(derive), attrs); - self.0.push((Symbol::intern(trait_name), Rc::new(derive))); + self.0.push((Symbol::intern(trait_name), Lrc::new(derive))); } fn register_attr_proc_macro(&mut self, @@ -561,7 +560,7 @@ impl<'a> CrateLoader<'a> { let expand = SyntaxExtension::AttrProcMacro( Box::new(AttrProcMacro { inner: expand }) ); - self.0.push((Symbol::intern(name), Rc::new(expand))); + self.0.push((Symbol::intern(name), Lrc::new(expand))); } fn register_bang_proc_macro(&mut self, @@ -570,7 +569,7 @@ impl<'a> CrateLoader<'a> { let expand = SyntaxExtension::ProcMacro( Box::new(BangProcMacro { inner: expand }) ); - self.0.push((Symbol::intern(name), Rc::new(expand))); + self.0.push((Symbol::intern(name), Lrc::new(expand))); } } diff --git a/src/librustc_metadata/cstore.rs b/src/librustc_metadata/cstore.rs index 87e41cae60d66..8132f8cf6212c 100644 --- a/src/librustc_metadata/cstore.rs +++ b/src/librustc_metadata/cstore.rs @@ -22,9 +22,7 @@ use rustc_back::PanicStrategy; use rustc_data_structures::indexed_vec::IndexVec; use rustc::util::nodemap::{FxHashMap, FxHashSet, NodeMap}; -use std::cell::{RefCell, Cell}; -use std::rc::Rc; -use rustc_data_structures::owning_ref::ErasedBoxRef; +use rustc_data_structures::sync::{Sync, Lrc, RwLock, Lock, LockCell}; use syntax::{ast, attr}; use syntax::ext::base::SyntaxExtension; use syntax::symbol::Symbol; @@ -42,7 +40,9 @@ pub use cstore_impl::{provide, provide_extern}; // own crate numbers. pub type CrateNumMap = IndexVec; -pub struct MetadataBlob(pub ErasedBoxRef<[u8]>); +pub use rustc_data_structures::sync::MetadataRef; + +pub struct MetadataBlob(pub MetadataRef); /// Holds information about a syntax_pos::FileMap imported from another crate. /// See `imported_filemaps()` for more information. @@ -52,7 +52,7 @@ pub struct ImportedFileMap { /// The end of this FileMap within the codemap of its original crate pub original_end_pos: syntax_pos::BytePos, /// The imported FileMap's representation within the local codemap - pub translated_filemap: Rc, + pub translated_filemap: Lrc, } pub struct CrateMetadata { @@ -61,13 +61,13 @@ pub struct CrateMetadata { /// Information about the extern crate that caused this crate to /// be loaded. If this is `None`, then the crate was injected /// (e.g., by the allocator) - pub extern_crate: Cell>, + pub extern_crate: LockCell>, pub blob: MetadataBlob, - pub cnum_map: RefCell, + pub cnum_map: Lock, pub cnum: CrateNum, - pub codemap_import_info: RefCell>, - pub attribute_cache: RefCell<[Vec>>; 2]>, + pub codemap_import_info: RwLock>, + pub attribute_cache: Lock<[Vec>>; 2]>, pub root: schema::CrateRoot, @@ -76,32 +76,32 @@ pub struct CrateMetadata { /// hashmap, which gives the reverse mapping. This allows us to /// quickly retrace a `DefPath`, which is needed for incremental /// compilation support. - pub def_path_table: Rc, + pub def_path_table: Lrc, pub exported_symbols: FxHashSet, pub trait_impls: FxHashMap<(u32, DefIndex), schema::LazySeq>, - pub dep_kind: Cell, + pub dep_kind: LockCell, pub source: CrateSource, - pub proc_macros: Option)>>, + pub proc_macros: Option)>>, // Foreign items imported from a dylib (Windows only) pub dllimport_foreign_items: FxHashSet, } pub struct CStore { - metas: RefCell>>, + metas: RwLock>>, /// Map from NodeId's of local extern crate statements to crate numbers - extern_mod_crate_map: RefCell>, - pub metadata_loader: Box, + extern_mod_crate_map: Lock>, + pub metadata_loader: Box, } impl CStore { - pub fn new(metadata_loader: Box) -> CStore { + pub fn new(metadata_loader: Box) -> CStore { CStore { - metas: RefCell::new(FxHashMap()), - extern_mod_crate_map: RefCell::new(FxHashMap()), + metas: RwLock::new(FxHashMap()), + extern_mod_crate_map: Lock::new(FxHashMap()), metadata_loader, } } @@ -110,16 +110,16 @@ impl CStore { CrateNum::new(self.metas.borrow().len() + 1) } - pub fn get_crate_data(&self, cnum: CrateNum) -> Rc { + pub fn get_crate_data(&self, cnum: CrateNum) -> Lrc { self.metas.borrow().get(&cnum).unwrap().clone() } - pub fn set_crate_data(&self, cnum: CrateNum, data: Rc) { + pub fn set_crate_data(&self, cnum: CrateNum, data: Lrc) { self.metas.borrow_mut().insert(cnum, data); } pub fn iter_crate_data(&self, mut i: I) - where I: FnMut(CrateNum, &Rc) + where I: FnMut(CrateNum, &Lrc) { for (&k, v) in self.metas.borrow().iter() { i(k, v); diff --git a/src/librustc_metadata/cstore_impl.rs b/src/librustc_metadata/cstore_impl.rs index 955648208cd8b..7e6339b0939d5 100644 --- a/src/librustc_metadata/cstore_impl.rs +++ b/src/librustc_metadata/cstore_impl.rs @@ -30,7 +30,7 @@ use rustc::hir::map::definitions::DefPathTable; use rustc::util::nodemap::{NodeSet, DefIdMap}; use std::any::Any; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use syntax::ast; use syntax::attr; @@ -111,12 +111,12 @@ provide! { <'tcx> tcx, def_id, other, cdata, let _ = cdata; tcx.calculate_dtor(def_id, &mut |_,_| Ok(())) } - variances_of => { Rc::new(cdata.get_item_variances(def_id.index)) } + variances_of => { Lrc::new(cdata.get_item_variances(def_id.index)) } associated_item_def_ids => { let mut result = vec![]; cdata.each_child_of_item(def_id.index, |child| result.push(child.def.def_id()), tcx.sess); - Rc::new(result) + Lrc::new(result) } associated_item => { cdata.get_associated_item(def_id.index) } impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) } @@ -136,11 +136,11 @@ provide! { <'tcx> tcx, def_id, other, cdata, mir } mir_const_qualif => { - (cdata.mir_const_qualif(def_id.index), Rc::new(IdxSetBuf::new_empty(0))) + (cdata.mir_const_qualif(def_id.index), Lrc::new(IdxSetBuf::new_empty(0))) } typeck_tables_of => { cdata.item_body_tables(def_id.index, tcx) } fn_sig => { cdata.fn_sig(def_id.index, tcx) } - inherent_impls => { Rc::new(cdata.get_inherent_implementations_for_type(def_id.index)) } + inherent_impls => { Lrc::new(cdata.get_inherent_implementations_for_type(def_id.index)) } is_const_fn => { cdata.is_const_fn(def_id.index) } is_foreign_item => { cdata.is_foreign_item(def_id.index) } is_auto_impl => { cdata.is_auto_impl(def_id.index) } @@ -169,18 +169,18 @@ provide! { <'tcx> tcx, def_id, other, cdata, } is_mir_available => { cdata.is_item_mir_available(def_id.index) } - dylib_dependency_formats => { Rc::new(cdata.get_dylib_dependency_formats()) } + dylib_dependency_formats => { Lrc::new(cdata.get_dylib_dependency_formats()) } is_panic_runtime => { cdata.is_panic_runtime(tcx.sess) } is_compiler_builtins => { cdata.is_compiler_builtins(tcx.sess) } has_global_allocator => { cdata.has_global_allocator() } is_sanitizer_runtime => { cdata.is_sanitizer_runtime(tcx.sess) } is_profiler_runtime => { cdata.is_profiler_runtime(tcx.sess) } panic_strategy => { cdata.panic_strategy() } - extern_crate => { Rc::new(cdata.extern_crate.get()) } + extern_crate => { Lrc::new(cdata.extern_crate.get()) } is_no_builtins => { cdata.is_no_builtins(tcx.sess) } impl_defaultness => { cdata.get_impl_defaultness(def_id.index) } - exported_symbol_ids => { Rc::new(cdata.get_exported_symbols()) } - native_libraries => { Rc::new(cdata.get_native_libraries(tcx.sess)) } + exported_symbol_ids => { Lrc::new(cdata.get_exported_symbols()) } + native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) } plugin_registrar_fn => { cdata.root.plugin_registrar_fn.map(|index| { DefId { krate: def_id.krate, index } @@ -199,13 +199,13 @@ provide! { <'tcx> tcx, def_id, other, cdata, let mut result = vec![]; let filter = Some(other); cdata.get_implementations_for_trait(filter, &mut result); - Rc::new(result) + Lrc::new(result) } all_trait_implementations => { let mut result = vec![]; cdata.get_implementations_for_trait(None, &mut result); - Rc::new(result) + Lrc::new(result) } is_dllimport_foreign_item => { @@ -217,10 +217,10 @@ provide! { <'tcx> tcx, def_id, other, cdata, item_children => { let mut result = vec![]; cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess); - Rc::new(result) + Lrc::new(result) } - defined_lang_items => { Rc::new(cdata.get_lang_items()) } - missing_lang_items => { Rc::new(cdata.get_missing_lang_items()) } + defined_lang_items => { Lrc::new(cdata.get_lang_items()) } + missing_lang_items => { Lrc::new(cdata.get_missing_lang_items()) } extern_const_body => { debug!("item_body({:?}): inlining item", def_id); @@ -234,7 +234,7 @@ provide! { <'tcx> tcx, def_id, other, cdata, } } - used_crate_source => { Rc::new(cdata.source.clone()) } + used_crate_source => { Lrc::new(cdata.source.clone()) } has_copy_closures => { cdata.has_copy_closures(tcx.sess) } has_clone_closures => { cdata.has_clone_closures(tcx.sess) } @@ -276,11 +276,11 @@ pub fn provide<'tcx>(providers: &mut Providers<'tcx>) { }, native_libraries: |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); - Rc::new(native_libs::collect(tcx)) + Lrc::new(native_libs::collect(tcx)) }, link_args: |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); - Rc::new(link_args::collect(tcx)) + Lrc::new(link_args::collect(tcx)) }, // Returns a map from a sufficiently visible external item (i.e. an @@ -362,7 +362,7 @@ pub fn provide<'tcx>(providers: &mut Providers<'tcx>) { } } - Rc::new(visible_parent_map) + Lrc::new(visible_parent_map) }, ..*providers @@ -370,7 +370,7 @@ pub fn provide<'tcx>(providers: &mut Providers<'tcx>) { } impl CrateStore for cstore::CStore { - fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc { + fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc { self.get_crate_data(krate) } @@ -443,7 +443,7 @@ impl CrateStore for cstore::CStore { self.get_crate_data(def.krate).def_path_hash(def.index) } - fn def_path_table(&self, cnum: CrateNum) -> Rc { + fn def_path_table(&self, cnum: CrateNum) -> Lrc { self.get_crate_data(cnum).def_path_table.clone() } @@ -467,7 +467,7 @@ impl CrateStore for cstore::CStore { } else if data.name == "proc_macro" && self.get_crate_data(id.krate).item_name(id.index) == "quote" { let ext = SyntaxExtension::ProcMacro(Box::new(::proc_macro::__internal::Quoter)); - return LoadedMacro::ProcMacro(Rc::new(ext)); + return LoadedMacro::ProcMacro(Lrc::new(ext)); } let (name, def) = data.get_macro(id.index); diff --git a/src/librustc_metadata/decoder.rs b/src/librustc_metadata/decoder.rs index 0e9f4a8f1784b..09a8e1c785ab1 100644 --- a/src/librustc_metadata/decoder.rs +++ b/src/librustc_metadata/decoder.rs @@ -13,6 +13,7 @@ use cstore::{self, CrateMetadata, MetadataBlob, NativeLibrary}; use schema::*; +use rustc_data_structures::sync::{Lrc, ReadGuard}; use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash}; use rustc::hir; use rustc::middle::cstore::{LinkagePreference, ExternConstBody, @@ -28,11 +29,9 @@ use rustc::ty::codec::TyDecoder; use rustc::util::nodemap::DefIdSet; use rustc::mir::Mir; -use std::cell::Ref; use std::collections::BTreeMap; use std::io; use std::mem; -use std::rc::Rc; use std::u32; use rustc_serialize::{Decodable, Decoder, SpecializedDecoder, opaque}; @@ -775,12 +774,12 @@ impl<'a, 'tcx> CrateMetadata { .map(|body| (body.id(), body)) .collect(); ExternBodyNestedBodies { - nested_bodies: Rc::new(nested_bodies), + nested_bodies: Lrc::new(nested_bodies), fingerprint: ast.stable_bodies_hash, } } else { ExternBodyNestedBodies { - nested_bodies: Rc::new(BTreeMap::new()), + nested_bodies: Lrc::new(BTreeMap::new()), fingerprint: Fingerprint::zero(), } } @@ -870,11 +869,11 @@ impl<'a, 'tcx> CrateMetadata { } } - pub fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Rc<[ast::Attribute]> { + pub fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> { let (node_as, node_index) = (node_id.address_space().index(), node_id.as_array_index()); if self.is_proc_macro(node_id) { - return Rc::new([]); + return Lrc::new([]); } if let Some(&Some(ref val)) = @@ -890,7 +889,7 @@ impl<'a, 'tcx> CrateMetadata { if def_key.disambiguated_data.data == DefPathData::StructCtor { item = self.entry(def_key.parent.unwrap()); } - let result: Rc<[ast::Attribute]> = Rc::from(self.get_attributes(&item, sess)); + let result: Lrc<[ast::Attribute]> = Lrc::from(self.get_attributes(&item, sess)); let vec_ = &mut self.attribute_cache.borrow_mut()[node_as]; if vec_.len() < node_index + 1 { vec_.resize(node_index + 1, None); @@ -1108,7 +1107,7 @@ impl<'a, 'tcx> CrateMetadata { /// for items inlined from other crates. pub fn imported_filemaps(&'a self, local_codemap: &codemap::CodeMap) - -> Ref<'a, Vec> { + -> ReadGuard<'a, Vec> { { let filemaps = self.codemap_import_info.borrow(); if !filemaps.is_empty() { diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index 5ddbb18450e2e..411de16e9b49b 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -35,7 +35,7 @@ use std::hash::Hash; use std::io::prelude::*; use std::io::Cursor; use std::path::Path; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use std::u32; use syntax::ast::{self, CRATE_NODE_ID}; use syntax::codemap::Spanned; @@ -297,7 +297,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { adapted.name.hash(&mut hasher); hasher.finish() }; - Rc::new(adapted) + Lrc::new(adapted) } }, // expanded code, not from a file diff --git a/src/librustc_metadata/lib.rs b/src/librustc_metadata/lib.rs index a65ddcecf8874..169a2f3a10f02 100644 --- a/src/librustc_metadata/lib.rs +++ b/src/librustc_metadata/lib.rs @@ -23,7 +23,10 @@ #![feature(specialization)] #![feature(rustc_private)] +#![recursion_limit="256"] + extern crate libc; + #[macro_use] extern crate log; #[macro_use] diff --git a/src/librustc_metadata/locator.rs b/src/librustc_metadata/locator.rs index 90c469eea843d..dee8af9a8be50 100644 --- a/src/librustc_metadata/locator.rs +++ b/src/librustc_metadata/locator.rs @@ -219,7 +219,7 @@ //! no means all of the necessary details. Take a look at the rest of //! metadata::locator or metadata::creader for all the juicy details! -use cstore::MetadataBlob; +use cstore::{MetadataRef, MetadataBlob}; use creader::Library; use schema::{METADATA_HEADER, rustc_version}; @@ -243,8 +243,8 @@ use std::path::{Path, PathBuf}; use std::time::Instant; use flate2::read::DeflateDecoder; -use rustc_data_structures::owning_ref::{ErasedBoxRef, OwningRef}; +use rustc_data_structures::owning_ref::OwningRef; pub struct CrateMismatch { path: PathBuf, got: String, @@ -842,7 +842,7 @@ fn get_metadata_section_imp(target: &Target, if !filename.exists() { return Err(format!("no such file: '{}'", filename.display())); } - let raw_bytes: ErasedBoxRef<[u8]> = match flavor { + let raw_bytes: MetadataRef = match flavor { CrateFlavor::Rlib => loader.get_rlib_metadata(target, filename)?, CrateFlavor::Dylib => { let buf = loader.get_dylib_metadata(target, filename)?; diff --git a/src/librustc_mir/borrow_check/error_reporting.rs b/src/librustc_mir/borrow_check/error_reporting.rs index bc1b3edbb6ad9..c2b0299dca034 100644 --- a/src/librustc_mir/borrow_check/error_reporting.rs +++ b/src/librustc_mir/borrow_check/error_reporting.rs @@ -14,8 +14,7 @@ use rustc::mir::{BorrowKind, Field, Local, Location, Operand}; use rustc::mir::{Place, ProjectionElem, Rvalue, Statement, StatementKind}; use rustc::ty::{self, RegionKind}; use rustc_data_structures::indexed_vec::Idx; - -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use super::{MirBorrowckCtxt, Context}; use super::{InitializationRequiringAction, PrefixSet}; @@ -426,7 +425,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { &mut self, context: Context, name: &String, - _scope_tree: &Rc, + _scope_tree: &Lrc, borrow: &BorrowData<'tcx>, drop_span: Span, borrow_span: Span, @@ -448,7 +447,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { fn report_scoped_temporary_value_does_not_live_long_enough( &mut self, context: Context, - _scope_tree: &Rc, + _scope_tree: &Lrc, borrow: &BorrowData<'tcx>, drop_span: Span, _borrow_span: Span, @@ -472,7 +471,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { &mut self, context: Context, name: &String, - scope_tree: &Rc, + scope_tree: &Lrc, borrow: &BorrowData<'tcx>, drop_span: Span, borrow_span: Span, @@ -494,7 +493,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { fn report_unscoped_temporary_value_does_not_live_long_enough( &mut self, context: Context, - scope_tree: &Rc, + scope_tree: &Lrc, borrow: &BorrowData<'tcx>, drop_span: Span, _borrow_span: Span, diff --git a/src/librustc_mir/dataflow/impls/borrows.rs b/src/librustc_mir/dataflow/impls/borrows.rs index c39ae10371cdd..d1125f541de44 100644 --- a/src/librustc_mir/dataflow/impls/borrows.rs +++ b/src/librustc_mir/dataflow/impls/borrows.rs @@ -22,6 +22,7 @@ use rustc::util::nodemap::{FxHashMap, FxHashSet}; use rustc_data_structures::bitslice::{BitwiseOperator}; use rustc_data_structures::indexed_set::{IdxSet}; use rustc_data_structures::indexed_vec::{Idx, IndexVec}; +use rustc_data_structures::sync::Lrc; use dataflow::{BitDenotation, BlockSets, InitialFlow}; pub use dataflow::indexes::{BorrowIndex, ReserveOrActivateIndex}; @@ -44,7 +45,7 @@ use std::rc::Rc; pub struct Borrows<'a, 'gcx: 'tcx, 'tcx: 'a> { tcx: TyCtxt<'a, 'gcx, 'tcx>, mir: &'a Mir<'tcx>, - scope_tree: Rc, + scope_tree: Lrc, root_scope: Option, /// The fundamental map relating bitvector indexes to the borrows @@ -273,7 +274,7 @@ impl<'a, 'gcx, 'tcx> Borrows<'a, 'gcx, 'tcx> { pub fn borrows(&self) -> &IndexVec> { &self.borrows } - pub fn scope_tree(&self) -> &Rc { &self.scope_tree } + pub fn scope_tree(&self) -> &Lrc { &self.scope_tree } pub fn location(&self, idx: BorrowIndex) -> &Location { &self.borrows[idx].location diff --git a/src/librustc_mir/hair/cx/mod.rs b/src/librustc_mir/hair/cx/mod.rs index 306b41714a553..c331eef6f49ec 100644 --- a/src/librustc_mir/hair/cx/mod.rs +++ b/src/librustc_mir/hair/cx/mod.rs @@ -30,7 +30,7 @@ use syntax::ast; use syntax::symbol::Symbol; use rustc::hir; use rustc_const_math::{ConstInt, ConstUsize}; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; #[derive(Clone)] pub struct Cx<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { @@ -43,7 +43,7 @@ pub struct Cx<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { /// Identity `Substs` for use with const-evaluation. pub identity_substs: &'gcx Substs<'gcx>, - pub region_scope_tree: Rc, + pub region_scope_tree: Lrc, pub tables: &'a ty::TypeckTables<'gcx>, /// This is `Constness::Const` if we are compiling a `static`, diff --git a/src/librustc_mir/transform/check_unsafety.rs b/src/librustc_mir/transform/check_unsafety.rs index e7ce528507180..d3b867685d610 100644 --- a/src/librustc_mir/transform/check_unsafety.rs +++ b/src/librustc_mir/transform/check_unsafety.rs @@ -10,6 +10,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::indexed_vec::IndexVec; +use rustc_data_structures::sync::Lrc; use rustc::ty::maps::Providers; use rustc::ty::{self, TyCtxt}; @@ -22,7 +23,6 @@ use rustc::mir::visit::{PlaceContext, Visitor}; use syntax::ast; use syntax::symbol::Symbol; -use std::rc::Rc; use util; pub struct UnsafetyChecker<'a, 'tcx: 'a> { @@ -328,8 +328,8 @@ fn unsafety_check_result<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) ClearCrossCrate::Clear => { debug!("unsafety_violations: {:?} - remote, skipping", def_id); return UnsafetyCheckResult { - violations: Rc::new([]), - unsafe_blocks: Rc::new([]) + violations: Lrc::new([]), + unsafe_blocks: Lrc::new([]) } } }; diff --git a/src/librustc_mir/transform/mod.rs b/src/librustc_mir/transform/mod.rs index 563405fccc970..daa93dc744568 100644 --- a/src/librustc_mir/transform/mod.rs +++ b/src/librustc_mir/transform/mod.rs @@ -18,8 +18,8 @@ use rustc::ty::steal::Steal; use rustc::hir; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; use rustc::util::nodemap::DefIdSet; +use rustc_data_structures::sync::Lrc; use std::borrow::Cow; -use std::rc::Rc; use syntax::ast; use syntax_pos::Span; @@ -66,7 +66,7 @@ fn is_mir_available<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> boo /// Finds the full set of def-ids within the current crate that have /// MIR associated with them. fn mir_keys<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, krate: CrateNum) - -> Rc { + -> Lrc { assert_eq!(krate, LOCAL_CRATE); let mut set = DefIdSet(); @@ -101,7 +101,7 @@ fn mir_keys<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, krate: CrateNum) set: &mut set, }.as_deep_visitor()); - Rc::new(set) + Lrc::new(set) } fn mir_built<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Steal> { diff --git a/src/librustc_mir/transform/qualify_consts.rs b/src/librustc_mir/transform/qualify_consts.rs index 2b2323928efba..cfd7cf0313da6 100644 --- a/src/librustc_mir/transform/qualify_consts.rs +++ b/src/librustc_mir/transform/qualify_consts.rs @@ -34,7 +34,7 @@ use syntax::feature_gate::UnstableFeatures; use syntax_pos::{Span, DUMMY_SP}; use std::fmt; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use std::usize; use transform::{MirPass, MirSource}; @@ -296,7 +296,7 @@ impl<'a, 'tcx> Qualifier<'a, 'tcx, 'tcx> { } /// Qualify a whole const, static initializer or const fn. - fn qualify_const(&mut self) -> (Qualif, Rc>) { + fn qualify_const(&mut self) -> (Qualif, Lrc>) { debug!("qualifying {} {:?}", self.mode, self.def_id); let mir = self.mir; @@ -411,7 +411,7 @@ impl<'a, 'tcx> Qualifier<'a, 'tcx, 'tcx> { } } - (self.qualif, Rc::new(promoted_temps)) + (self.qualif, Lrc::new(promoted_temps)) } } @@ -945,7 +945,7 @@ pub fn provide(providers: &mut Providers) { fn mir_const_qualif<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) - -> (u8, Rc>) { + -> (u8, Lrc>) { // NB: This `borrow()` is guaranteed to be valid (i.e., the value // cannot yet be stolen), because `mir_validated()`, which steals // from `mir_const(), forces this query to execute before @@ -954,7 +954,7 @@ fn mir_const_qualif<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, if mir.return_ty().references_error() { tcx.sess.delay_span_bug(mir.span, "mir_const_qualif: Mir had errors"); - return (Qualif::NOT_CONST.bits(), Rc::new(IdxSetBuf::new_empty(0))); + return (Qualif::NOT_CONST.bits(), Lrc::new(IdxSetBuf::new_empty(0))); } let mut qualifier = Qualifier::new(tcx, def_id, mir, Mode::Const); diff --git a/src/librustc_passes/Cargo.toml b/src/librustc_passes/Cargo.toml index d2560c2f8203f..c2e5e369a8fcb 100644 --- a/src/librustc_passes/Cargo.toml +++ b/src/librustc_passes/Cargo.toml @@ -13,6 +13,7 @@ log = "0.3" rustc = { path = "../librustc" } rustc_const_eval = { path = "../librustc_const_eval" } rustc_const_math = { path = "../librustc_const_math" } +rustc_data_structures = { path = "../librustc_data_structures" } syntax = { path = "../libsyntax" } syntax_pos = { path = "../libsyntax_pos" } rustc_errors = { path = "../librustc_errors" } diff --git a/src/librustc_passes/consts.rs b/src/librustc_passes/consts.rs index 6df860492f05a..74d548c1fbb95 100644 --- a/src/librustc_passes/consts.rs +++ b/src/librustc_passes/consts.rs @@ -45,7 +45,7 @@ use rustc::util::common::ErrorReported; use rustc::util::nodemap::{ItemLocalSet, NodeSet}; use rustc::lint::builtin::CONST_ERR; use rustc::hir::{self, PatKind, RangeEnd}; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use syntax::ast; use syntax_pos::{Span, DUMMY_SP}; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; @@ -83,7 +83,7 @@ fn const_is_rvalue_promotable_to_static<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, fn rvalue_promotable_map<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) - -> Rc + -> Lrc { let outer_def_id = tcx.closure_base_def_id(def_id); if outer_def_id != def_id { @@ -108,7 +108,7 @@ fn rvalue_promotable_map<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let body_id = tcx.hir.body_owned_by(node_id); visitor.visit_nested_body(body_id); - Rc::new(visitor.result) + Lrc::new(visitor.result) } struct CheckCrateVisitor<'a, 'tcx: 'a> { diff --git a/src/librustc_passes/lib.rs b/src/librustc_passes/lib.rs index 9a150abea6691..9e7f2e142a360 100644 --- a/src/librustc_passes/lib.rs +++ b/src/librustc_passes/lib.rs @@ -25,6 +25,7 @@ extern crate rustc; extern crate rustc_const_eval; extern crate rustc_const_math; +extern crate rustc_data_structures; #[macro_use] extern crate log; diff --git a/src/librustc_privacy/Cargo.toml b/src/librustc_privacy/Cargo.toml index c65312e9a8337..62eab40f3ec9a 100644 --- a/src/librustc_privacy/Cargo.toml +++ b/src/librustc_privacy/Cargo.toml @@ -13,3 +13,4 @@ rustc = { path = "../librustc" } rustc_typeck = { path = "../librustc_typeck" } syntax = { path = "../libsyntax" } syntax_pos = { path = "../libsyntax_pos" } +rustc_data_structures = { path = "../librustc_data_structures" } \ No newline at end of file diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index bb0a4be49c2a8..b36b140a881d5 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -19,6 +19,7 @@ #[macro_use] extern crate syntax; extern crate rustc_typeck; extern crate syntax_pos; +extern crate rustc_data_structures; use rustc::hir::{self, PatKind}; use rustc::hir::def::Def; @@ -37,7 +38,7 @@ use syntax_pos::Span; use std::cmp; use std::mem::replace; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; mod diagnostics; @@ -1642,13 +1643,13 @@ pub fn provide(providers: &mut Providers) { }; } -pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Rc { +pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Lrc { tcx.privacy_access_levels(LOCAL_CRATE) } fn privacy_access_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, krate: CrateNum) - -> Rc { + -> Lrc { assert_eq!(krate, LOCAL_CRATE); let krate = tcx.hir.krate(); @@ -1722,7 +1723,7 @@ fn privacy_access_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor)); } - Rc::new(visitor.access_levels) + Lrc::new(visitor.access_levels) } __build_diagnostic_array! { librustc_privacy, DIAGNOSTICS } diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index 3b20c1e74cd39..efd28326a22a1 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -27,7 +27,7 @@ use rustc::hir::def_id::{BUILTIN_MACROS_CRATE, CRATE_DEF_INDEX, LOCAL_CRATE, Def use rustc::ty; use std::cell::Cell; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use syntax::ast::{Name, Ident}; use syntax::attr; @@ -576,7 +576,7 @@ impl<'a> Resolver<'a> { } } - pub fn get_macro(&mut self, def: Def) -> Rc { + pub fn get_macro(&mut self, def: Def) -> Lrc { let def_id = match def { Def::Macro(def_id, ..) => def_id, _ => panic!("Expected Def::Macro(..)"), @@ -590,7 +590,7 @@ impl<'a> Resolver<'a> { LoadedMacro::ProcMacro(ext) => return ext, }; - let ext = Rc::new(macro_rules::compile(&self.session.parse_sess, + let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess, &self.session.features, ¯o_def)); self.macro_map.insert(def_id, ext.clone()); diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index b57a8bc7e77f1..3391861665915 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -68,7 +68,7 @@ use std::cmp; use std::collections::BTreeSet; use std::fmt; use std::mem::replace; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver}; use macros::{InvocationData, LegacyBinding, LegacyScope, MacroBinding}; @@ -1118,7 +1118,7 @@ impl<'a> NameBinding<'a> { } } - fn get_macro(&self, resolver: &mut Resolver<'a>) -> Rc { + fn get_macro(&self, resolver: &mut Resolver<'a>) -> Lrc { resolver.get_macro(self.def_ignoring_ambiguity()) } @@ -1323,7 +1323,7 @@ pub struct Resolver<'a> { macro_names: FxHashSet, global_macros: FxHashMap>, lexical_macro_resolutions: Vec<(Ident, &'a Cell>)>, - macro_map: FxHashMap>, + macro_map: FxHashMap>, macro_defs: FxHashMap, local_macro_def_scopes: FxHashMap>, macro_exports: Vec, diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index 260a0cd7cd733..a3f5fa3db2f5c 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -40,7 +40,7 @@ use syntax_pos::{Span, DUMMY_SP}; use std::cell::Cell; use std::mem; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; #[derive(Clone)] pub struct InvocationData<'a> { @@ -185,7 +185,7 @@ impl<'a> base::Resolver for Resolver<'a> { invocation.expansion.set(visitor.legacy_scope); } - fn add_builtin(&mut self, ident: ast::Ident, ext: Rc) { + fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc) { let def_id = DefId { krate: BUILTIN_MACROS_CRATE, index: DefIndex::new(self.macro_map.len()), @@ -292,7 +292,7 @@ impl<'a> base::Resolver for Resolver<'a> { } fn resolve_invoc(&mut self, invoc: &mut Invocation, scope: Mark, force: bool) - -> Result>, Determinacy> { + -> Result>, Determinacy> { let def = match invoc.kind { InvocationKind::Attr { attr: None, .. } => return Ok(None), _ => self.resolve_invoc_to_def(invoc, scope, force)?, @@ -315,7 +315,7 @@ impl<'a> base::Resolver for Resolver<'a> { } fn resolve_macro(&mut self, scope: Mark, path: &ast::Path, kind: MacroKind, force: bool) - -> Result, Determinacy> { + -> Result, Determinacy> { self.resolve_macro_to_def(scope, path, kind, force).map(|def| { self.unused_macros.remove(&def.def_id()); self.get_macro(def) @@ -735,7 +735,7 @@ impl<'a> Resolver<'a> { } let def_id = self.definitions.local_def_id(item.id); - let ext = Rc::new(macro_rules::compile(&self.session.parse_sess, + let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess, &self.session.features, item)); self.macro_map.insert(def_id, ext); diff --git a/src/librustc_trans/back/symbol_export.rs b/src/librustc_trans/back/symbol_export.rs index fa6fe2e9e93ef..121361a9ef48e 100644 --- a/src/librustc_trans/back/symbol_export.rs +++ b/src/librustc_trans/back/symbol_export.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use std::sync::Arc; use base; @@ -64,7 +64,7 @@ pub fn crates_export_threshold(crate_types: &[config::CrateType]) pub fn provide(providers: &mut Providers) { providers.exported_symbol_ids = |tcx, cnum| { let export_threshold = threshold(tcx); - Rc::new(tcx.exported_symbols(cnum) + Lrc::new(tcx.exported_symbols(cnum) .iter() .filter_map(|&(_, id, level)| { id.and_then(|id| { diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index d8e95cd2cf2e0..147a79ef4cb88 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -982,7 +982,7 @@ pub fn start_async_translation(tcx: TyCtxt, crate_info, time_graph, - coordinator_send: tcx.tx_to_llvm_workers.clone(), + coordinator_send: tcx.tx_to_llvm_workers.lock().clone(), trans_worker_receive, shared_emitter_main, future: coordinator_thread, @@ -1352,7 +1352,7 @@ fn start_executing_work(tcx: TyCtxt, metadata_config: Arc, allocator_config: Arc) -> thread::JoinHandle> { - let coordinator_send = tcx.tx_to_llvm_workers.clone(); + let coordinator_send = tcx.tx_to_llvm_workers.lock().clone(); let mut exported_symbols = FxHashMap(); exported_symbols.insert(LOCAL_CRATE, tcx.exported_symbols(LOCAL_CRATE)); for &cnum in tcx.crates().iter() { @@ -2257,7 +2257,7 @@ pub fn submit_translated_module_to_llvm(tcx: TyCtxt, mtrans: ModuleTranslation, cost: u64) { let llvm_work_item = WorkItem::Optimize(mtrans); - drop(tcx.tx_to_llvm_workers.send(Box::new(Message::TranslationDone { + drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::TranslationDone { llvm_work_item, cost, }))); diff --git a/src/librustc_trans/lib.rs b/src/librustc_trans/lib.rs index c4849c621e8d5..380b56b50ef90 100644 --- a/src/librustc_trans/lib.rs +++ b/src/librustc_trans/lib.rs @@ -73,8 +73,8 @@ pub use llvm_util::{init, target_features, print_version, print_passes, print, e use std::any::Any; use std::path::PathBuf; -use std::rc::Rc; use std::sync::mpsc; +use rustc_data_structures::sync::{self, Lrc}; use rustc::dep_graph::DepGraph; use rustc::hir::def_id::CrateNum; @@ -158,7 +158,7 @@ impl rustc_trans_utils::trans_crate::TransCrate for LlvmTransCrate { type OngoingCrateTranslation = back::write::OngoingCrateTranslation; type TranslatedCrate = CrateTranslation; - fn metadata_loader() -> Box { + fn metadata_loader() -> Box { box metadata::LlvmMetadataLoader } @@ -319,11 +319,11 @@ pub struct CrateInfo { profiler_runtime: Option, sanitizer_runtime: Option, is_no_builtins: FxHashSet, - native_libraries: FxHashMap>>, + native_libraries: FxHashMap>>, crate_name: FxHashMap, - used_libraries: Rc>, - link_args: Rc>, - used_crate_source: FxHashMap>, + used_libraries: Lrc>, + link_args: Lrc>, + used_crate_source: FxHashMap>, used_crates_static: Vec<(CrateNum, LibSource)>, used_crates_dynamic: Vec<(CrateNum, LibSource)>, } diff --git a/src/librustc_trans_utils/trans_crate.rs b/src/librustc_trans_utils/trans_crate.rs index 800c3063c025c..5ac9f2c7f146f 100644 --- a/src/librustc_trans_utils/trans_crate.rs +++ b/src/librustc_trans_utils/trans_crate.rs @@ -28,7 +28,7 @@ use std::fs::File; use std::path::Path; use std::sync::mpsc; -use rustc_data_structures::owning_ref::{ErasedBoxRef, OwningRef}; +use rustc_data_structures::owning_ref::OwningRef; use ar::{Archive, Builder, Header}; use flate2::Compression; use flate2::write::DeflateEncoder; @@ -39,18 +39,21 @@ use rustc::session::Session; use rustc::session::config::{CrateType, OutputFilenames}; use rustc::ty::TyCtxt; use rustc::ty::maps::Providers; -use rustc::middle::cstore::EncodedMetadata; +use rustc::middle::cstore::{MetadataLoader, EncodedMetadata}; use rustc::middle::cstore::MetadataLoader as MetadataLoaderTrait; use rustc::dep_graph::{DepGraph, DepNode, DepKind}; use rustc_back::target::Target; use link::{build_link_meta, out_filename}; +use rustc_data_structures::sync::Sync; + +pub use rustc_data_structures::sync::MetadataRef; pub trait TransCrate { type MetadataLoader: MetadataLoaderTrait; type OngoingCrateTranslation; type TranslatedCrate; - fn metadata_loader() -> Box; + fn metadata_loader() -> Box; fn provide(_providers: &mut Providers); fn provide_extern(_providers: &mut Providers); fn trans_crate<'a, 'tcx>( @@ -73,7 +76,7 @@ impl TransCrate for DummyTransCrate { type OngoingCrateTranslation = (); type TranslatedCrate = (); - fn metadata_loader() -> Box { + fn metadata_loader() -> Box { box DummyMetadataLoader(()) } @@ -116,7 +119,7 @@ impl MetadataLoaderTrait for DummyMetadataLoader { &self, _target: &Target, _filename: &Path - ) -> Result, String> { + ) -> Result { bug!("DummyMetadataLoader::get_rlib_metadata"); } @@ -124,7 +127,7 @@ impl MetadataLoaderTrait for DummyMetadataLoader { &self, _target: &Target, _filename: &Path - ) -> Result, String> { + ) -> Result { bug!("DummyMetadataLoader::get_dylib_metadata"); } } @@ -132,7 +135,7 @@ impl MetadataLoaderTrait for DummyMetadataLoader { pub struct NoLlvmMetadataLoader; impl MetadataLoaderTrait for NoLlvmMetadataLoader { - fn get_rlib_metadata(&self, _: &Target, filename: &Path) -> Result, String> { + fn get_rlib_metadata(&self, _: &Target, filename: &Path) -> Result { let file = File::open(filename) .map_err(|e| format!("metadata file open err: {:?}", e))?; let mut archive = Archive::new(file); @@ -155,7 +158,7 @@ impl MetadataLoaderTrait for NoLlvmMetadataLoader { &self, _target: &Target, _filename: &Path, - ) -> Result, String> { + ) -> Result { // FIXME: Support reading dylibs from llvm enabled rustc self.get_rlib_metadata(_target, _filename) } @@ -181,7 +184,7 @@ impl TransCrate for MetadataOnlyTransCrate { type OngoingCrateTranslation = OngoingCrateTranslation; type TranslatedCrate = TranslatedCrate; - fn metadata_loader() -> Box { + fn metadata_loader() -> Box { box NoLlvmMetadataLoader } diff --git a/src/librustc_typeck/check/generator_interior.rs b/src/librustc_typeck/check/generator_interior.rs index af1297697c241..268930c05b141 100644 --- a/src/librustc_typeck/check/generator_interior.rs +++ b/src/librustc_typeck/check/generator_interior.rs @@ -18,14 +18,14 @@ use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; use rustc::hir::{self, Pat, PatKind, Expr}; use rustc::middle::region; use rustc::ty::Ty; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use super::FnCtxt; use util::nodemap::FxHashMap; struct InteriorVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, types: FxHashMap, usize>, - region_scope_tree: Rc, + region_scope_tree: Lrc, expr_count: usize, } diff --git a/src/librustc_typeck/check/method/mod.rs b/src/librustc_typeck/check/method/mod.rs index 58d72e37d51cf..b87b61bbaf688 100644 --- a/src/librustc_typeck/check/method/mod.rs +++ b/src/librustc_typeck/check/method/mod.rs @@ -25,7 +25,7 @@ use syntax_pos::Span; use rustc::hir; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; pub use self::MethodError::*; pub use self::CandidateSource::*; @@ -165,7 +165,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { if let Some(import_id) = pick.import_id { let import_def_id = self.tcx.hir.local_def_id(import_id); debug!("used_trait_import: {:?}", import_def_id); - Rc::get_mut(&mut self.tables.borrow_mut().used_trait_imports) + Lrc::get_mut(&mut self.tables.borrow_mut().used_trait_imports) .unwrap().insert(import_def_id); } @@ -364,7 +364,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { if let Some(import_id) = pick.import_id { let import_def_id = self.tcx.hir.local_def_id(import_id); debug!("used_trait_import: {:?}", import_def_id); - Rc::get_mut(&mut self.tables.borrow_mut().used_trait_imports) + Lrc::get_mut(&mut self.tables.borrow_mut().used_trait_imports) .unwrap().insert(import_def_id); } diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs index f29009c1973a2..860f7df863f71 100644 --- a/src/librustc_typeck/check/method/suggest.rs +++ b/src/librustc_typeck/check/method/suggest.rs @@ -21,6 +21,7 @@ use namespace::Namespace; use rustc::traits::{Obligation, SelectionContext}; use util::nodemap::FxHashSet; +use rustc_data_structures::sync::LockGuard; use syntax::ast; use errors::DiagnosticBuilder; use syntax_pos::Span; @@ -29,7 +30,6 @@ use rustc::hir; use rustc::hir::print; use rustc::infer::type_variable::TypeVariableOrigin; -use std::cell; use std::cmp::Ordering; use super::{MethodError, NoMatchData, CandidateSource}; @@ -632,7 +632,7 @@ pub fn all_traits<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> AllTraits<'a> } pub struct AllTraits<'a> { - borrow: cell::Ref<'a, Option>, + borrow: LockGuard<'a, Option>, idx: usize, } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index ab81d26e77175..eb85fe7c05c09 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -110,7 +110,7 @@ use util::common::{ErrorReported, indenter}; use util::nodemap::{DefIdMap, DefIdSet, FxHashMap, NodeMap}; use std::cell::{Cell, RefCell, Ref, RefMut}; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use std::collections::hash_map::Entry; use std::cmp; use std::fmt::Display; @@ -797,7 +797,7 @@ fn has_typeck_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, fn used_trait_imports<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) - -> Rc { + -> Lrc { tcx.typeck_tables_of(def_id).used_trait_imports.clone() } diff --git a/src/librustc_typeck/check/regionck.rs b/src/librustc_typeck/check/regionck.rs index 64063ec5beda9..815ad74b19bfa 100644 --- a/src/librustc_typeck/check/regionck.rs +++ b/src/librustc_typeck/check/regionck.rs @@ -96,7 +96,7 @@ use rustc::ty::adjustment; use std::mem; use std::ops::Deref; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use syntax::ast; use syntax_pos::Span; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; @@ -189,7 +189,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { pub struct RegionCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { pub fcx: &'a FnCtxt<'a, 'gcx, 'tcx>, - pub region_scope_tree: Rc, + pub region_scope_tree: Lrc, outlives_environment: OutlivesEnvironment<'tcx>, diff --git a/src/librustc_typeck/check/writeback.rs b/src/librustc_typeck/check/writeback.rs index 29dc983ab560b..4817dfabc2d77 100644 --- a/src/librustc_typeck/check/writeback.rs +++ b/src/librustc_typeck/check/writeback.rs @@ -23,7 +23,7 @@ use rustc::util::nodemap::DefIdSet; use syntax::ast; use syntax_pos::Span; use std::mem; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; /////////////////////////////////////////////////////////////////////////// // Entry point @@ -48,7 +48,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let used_trait_imports = mem::replace( &mut self.tables.borrow_mut().used_trait_imports, - Rc::new(DefIdSet()), + Lrc::new(DefIdSet()), ); debug!( "used_trait_imports({:?}) = {:?}", diff --git a/src/librustc_typeck/coherence/inherent_impls.rs b/src/librustc_typeck/coherence/inherent_impls.rs index 569b6a2febb45..89f1b8fe4316e 100644 --- a/src/librustc_typeck/coherence/inherent_impls.rs +++ b/src/librustc_typeck/coherence/inherent_impls.rs @@ -24,7 +24,7 @@ use rustc::hir::itemlikevisit::ItemLikeVisitor; use rustc::ty::{self, CrateInherentImpls, TyCtxt}; use rustc::util::nodemap::DefIdMap; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use syntax::ast; use syntax_pos::Span; @@ -48,7 +48,7 @@ pub fn crate_inherent_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, /// On-demand query: yields a vector of the inherent impls for a specific type. pub fn inherent_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty_def_id: DefId) - -> Rc> { + -> Lrc> { assert!(ty_def_id.is_local()); // NB. Until we adopt the red-green dep-tracking algorithm (see @@ -67,7 +67,7 @@ pub fn inherent_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, // [the plan]: https://github.com/rust-lang/rust-roadmap/issues/4 thread_local! { - static EMPTY_DEF_ID_VEC: Rc> = Rc::new(vec![]) + static EMPTY_DEF_ID_VEC: Lrc> = Lrc::new(vec![]) } let result = tcx.dep_graph.with_ignore(|| { @@ -296,11 +296,11 @@ impl<'a, 'tcx> InherentCollect<'a, 'tcx> { let impl_def_id = self.tcx.hir.local_def_id(item.id); let mut rc_vec = self.impls_map.inherent_impls .entry(def_id) - .or_insert_with(|| Rc::new(vec![])); + .or_insert_with(|| Lrc::new(vec![])); // At this point, there should not be any clones of the - // `Rc`, so we can still safely push into it in place: - Rc::get_mut(&mut rc_vec).unwrap().push(impl_def_id); + // `Lrc`, so we can still safely push into it in place: + Lrc::get_mut(&mut rc_vec).unwrap().push(impl_def_id); } else { struct_span_err!(self.tcx.sess, item.span, diff --git a/src/librustc_typeck/variance/mod.rs b/src/librustc_typeck/variance/mod.rs index 418d2b9467096..2392104424355 100644 --- a/src/librustc_typeck/variance/mod.rs +++ b/src/librustc_typeck/variance/mod.rs @@ -17,7 +17,7 @@ use rustc::hir; use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc::ty::{self, CrateVariancesMap, TyCtxt}; use rustc::ty::maps::Providers; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; /// Defines the `TermsContext` basically houses an arena where we can /// allocate terms. @@ -44,16 +44,16 @@ pub fn provide(providers: &mut Providers) { } fn crate_variances<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) - -> Rc { + -> Lrc { assert_eq!(crate_num, LOCAL_CRATE); let mut arena = arena::TypedArena::new(); let terms_cx = terms::determine_parameters_to_be_inferred(tcx, &mut arena); let constraints_cx = constraints::add_constraints_from_crate(terms_cx); - Rc::new(solve::solve_constraints(constraints_cx)) + Lrc::new(solve::solve_constraints(constraints_cx)) } fn variances_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId) - -> Rc> { + -> Lrc> { let id = tcx.hir.as_local_node_id(item_def_id).expect("expected local def-id"); let unsupported = || { // Variance not relevant. diff --git a/src/librustc_typeck/variance/solve.rs b/src/librustc_typeck/variance/solve.rs index 434e8ce148f3b..340a7b1d08ede 100644 --- a/src/librustc_typeck/variance/solve.rs +++ b/src/librustc_typeck/variance/solve.rs @@ -18,7 +18,7 @@ use rustc::hir::def_id::DefId; use rustc::ty; use rustc_data_structures::fx::FxHashMap; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use super::constraints::*; use super::terms::*; @@ -51,7 +51,7 @@ pub fn solve_constraints(constraints_cx: ConstraintContext) -> ty::CrateVariance }; solutions_cx.solve(); let variances = solutions_cx.create_map(); - let empty_variance = Rc::new(Vec::new()); + let empty_variance = Lrc::new(Vec::new()); ty::CrateVariancesMap { variances, empty_variance } } @@ -88,7 +88,7 @@ impl<'a, 'tcx> SolveContext<'a, 'tcx> { } } - fn create_map(&self) -> FxHashMap>> { + fn create_map(&self) -> FxHashMap>> { let tcx = self.terms_cx.tcx; let solutions = &self.solutions; @@ -109,7 +109,7 @@ impl<'a, 'tcx> SolveContext<'a, 'tcx> { } } - (def_id, Rc::new(variances)) + (def_id, Lrc::new(variances)) }).collect() } diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 914365b003e18..10c30d823d395 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -13,7 +13,7 @@ use std::collections::BTreeMap; use std::io; use std::iter::once; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use syntax::ast; use rustc::hir; @@ -403,7 +403,7 @@ fn build_module(cx: &DocContext, did: DefId) -> clean::Module { } struct InlinedConst { - nested_bodies: Rc> + nested_bodies: Lrc> } impl hir::print::PpAnn for InlinedConst { diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index b353c0da865c8..6e48469dc2ecb 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -31,6 +31,7 @@ use errors::emitter::ColorConfig; use std::cell::{RefCell, Cell}; use std::mem; use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use std::path::PathBuf; use visit_ast::RustdocVisitor; @@ -134,7 +135,7 @@ pub fn run_core(search_paths: SearchPaths, ..config::basic_options().clone() }; - let codemap = Rc::new(codemap::CodeMap::new(sessopts.file_path_mapping())); + let codemap = Lrc::new(codemap::CodeMap::new(sessopts.file_path_mapping())); let diagnostic_handler = errors::Handler::with_tty_emitter(ColorConfig::Auto, true, false, diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 7ebacdec1f0b2..7aad2b414c925 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -25,6 +25,8 @@ #![feature(unicode)] #![feature(vec_remove_item)] +#![recursion_limit="256"] + extern crate arena; extern crate getopts; extern crate env_logger; diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 8e861f10dd8d4..a9548ee9d8faa 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -18,6 +18,7 @@ use std::panic::{self, AssertUnwindSafe}; use std::process::Command; use std::rc::Rc; use std::str; +use rustc_data_structures::sync::Lrc; use std::sync::{Arc, Mutex}; use testing; @@ -76,7 +77,7 @@ pub fn run(input_path: &Path, ..config::basic_options().clone() }; - let codemap = Rc::new(CodeMap::new(sessopts.file_path_mapping())); + let codemap = Lrc::new(CodeMap::new(sessopts.file_path_mapping())); let handler = errors::Handler::with_tty_emitter(ColorConfig::Auto, true, false, @@ -234,7 +235,7 @@ fn run_test(test: &str, cratename: &str, filename: &FileName, cfgs: Vec, } } let data = Arc::new(Mutex::new(Vec::new())); - let codemap = Rc::new(CodeMap::new(sessopts.file_path_mapping())); + let codemap = Lrc::new(CodeMap::new(sessopts.file_path_mapping())); let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()), Some(codemap.clone()), false); @@ -449,7 +450,7 @@ pub struct Collector { opts: TestOptions, maybe_sysroot: Option, position: Span, - codemap: Option>, + codemap: Option>, filename: Option, // to be removed when hoedown will be removed as well pub render_type: RenderType, @@ -459,7 +460,7 @@ pub struct Collector { impl Collector { pub fn new(cratename: String, cfgs: Vec, libs: SearchPaths, externs: Externs, use_headers: bool, opts: TestOptions, maybe_sysroot: Option, - codemap: Option>, filename: Option, + codemap: Option>, filename: Option, render_type: RenderType, linker: Option) -> Collector { Collector { tests: Vec::new(), diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index e0f14c04c6cc9..af8ea29a781cb 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -29,7 +29,7 @@ use tokenstream::{ThinTokenStream, TokenStream}; use serialize::{self, Encoder, Decoder}; use std::collections::HashSet; use std::fmt; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use std::u32; #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy)] @@ -1208,7 +1208,7 @@ pub enum LitKind { /// A string literal (`"foo"`) Str(Symbol, StrStyle), /// A byte string (`b"foo"`) - ByteStr(Rc>), + ByteStr(Lrc>), /// A byte char (`b'f'`) Byte(u8), /// A character literal (`'a'`) diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index e49a7117192d3..4181f2a6d4a2c 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -24,10 +24,9 @@ pub use self::ExpnFormat::*; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::stable_hasher::StableHasher; -use std::cell::{RefCell, Ref}; +use rustc_data_structures::sync::{Lrc, Lock, LockGuard}; use std::hash::Hash; use std::path::{Path, PathBuf}; -use std::rc::Rc; use std::env; use std::fs; @@ -125,32 +124,32 @@ impl StableFilemapId { // pub struct CodeMap { - pub(super) files: RefCell>>, - file_loader: Box, + pub(super) files: Lock>>, + file_loader: Box, // This is used to apply the file path remapping as specified via // -Zremap-path-prefix to all FileMaps allocated within this CodeMap. path_mapping: FilePathMapping, - stable_id_to_filemap: RefCell>>, + stable_id_to_filemap: Lock>>, } impl CodeMap { pub fn new(path_mapping: FilePathMapping) -> CodeMap { CodeMap { - files: RefCell::new(Vec::new()), + files: Lock::new(Vec::new()), file_loader: Box::new(RealFileLoader), path_mapping, - stable_id_to_filemap: RefCell::new(FxHashMap()), + stable_id_to_filemap: Lock::new(FxHashMap()), } } - pub fn with_file_loader(file_loader: Box, + pub fn with_file_loader(file_loader: Box, path_mapping: FilePathMapping) -> CodeMap { CodeMap { - files: RefCell::new(Vec::new()), - file_loader, + files: Lock::new(Vec::new()), + file_loader: file_loader, path_mapping, - stable_id_to_filemap: RefCell::new(FxHashMap()), + stable_id_to_filemap: Lock::new(FxHashMap()), } } @@ -162,16 +161,16 @@ impl CodeMap { self.file_loader.file_exists(path) } - pub fn load_file(&self, path: &Path) -> io::Result> { + pub fn load_file(&self, path: &Path) -> io::Result> { let src = self.file_loader.read_file(path)?; Ok(self.new_filemap(path.to_owned().into(), src)) } - pub fn files(&self) -> Ref>> { + pub fn files(&self) -> LockGuard>> { self.files.borrow() } - pub fn filemap_by_stable_id(&self, stable_id: StableFilemapId) -> Option> { + pub fn filemap_by_stable_id(&self, stable_id: StableFilemapId) -> Option> { self.stable_id_to_filemap.borrow().get(&stable_id).map(|fm| fm.clone()) } @@ -187,7 +186,7 @@ impl CodeMap { /// Creates a new filemap without setting its line information. If you don't /// intend to set the line information yourself, you should use new_filemap_and_lines. - pub fn new_filemap(&self, filename: FileName, src: String) -> Rc { + pub fn new_filemap(&self, filename: FileName, src: String) -> Lrc { let start_pos = self.next_start_pos(); let mut files = self.files.borrow_mut(); @@ -205,7 +204,7 @@ impl CodeMap { }, other => (other, false), }; - let filemap = Rc::new(FileMap::new( + let filemap = Lrc::new(FileMap::new( filename, was_remapped, unmapped_path, @@ -223,7 +222,7 @@ impl CodeMap { } /// Creates a new filemap and sets its line information. - pub fn new_filemap_and_lines(&self, filename: &Path, src: &str) -> Rc { + pub fn new_filemap_and_lines(&self, filename: &Path, src: &str) -> Lrc { let fm = self.new_filemap(filename.to_owned().into(), src.to_owned()); let mut byte_pos: u32 = fm.start_pos.0; for line in src.lines() { @@ -251,7 +250,7 @@ impl CodeMap { mut file_local_lines: Vec, mut file_local_multibyte_chars: Vec, mut file_local_non_narrow_chars: Vec) - -> Rc { + -> Lrc { let start_pos = self.next_start_pos(); let mut files = self.files.borrow_mut(); @@ -270,19 +269,19 @@ impl CodeMap { *swc = *swc + start_pos; } - let filemap = Rc::new(FileMap { + let filemap = Lrc::new(FileMap { name: filename, name_was_remapped, unmapped_path: None, crate_of_origin, src: None, src_hash, - external_src: RefCell::new(ExternalSource::AbsentOk), + external_src: Lock::new(ExternalSource::AbsentOk), start_pos, end_pos, - lines: RefCell::new(file_local_lines), - multibyte_chars: RefCell::new(file_local_multibyte_chars), - non_narrow_chars: RefCell::new(file_local_non_narrow_chars), + lines: Lock::new(file_local_lines), + multibyte_chars: Lock::new(file_local_multibyte_chars), + non_narrow_chars: Lock::new(file_local_non_narrow_chars), name_hash, }); @@ -366,7 +365,7 @@ impl CodeMap { } // If the relevant filemap is empty, we don't return a line number. - pub fn lookup_line(&self, pos: BytePos) -> Result> { + pub fn lookup_line(&self, pos: BytePos) -> Result> { let idx = self.lookup_filemap_idx(pos); let files = self.files.borrow(); @@ -569,7 +568,7 @@ impl CodeMap { self.span_until_char(sp, '{') } - pub fn get_filemap(&self, filename: &FileName) -> Option> { + pub fn get_filemap(&self, filename: &FileName) -> Option> { for fm in self.files.borrow().iter() { if *filename == fm.name { return Some(fm.clone()); @@ -666,7 +665,7 @@ impl CodeMapper for CodeMap { } sp } - fn ensure_filemap_source_present(&self, file_map: Rc) -> bool { + fn ensure_filemap_source_present(&self, file_map: Lrc) -> bool { file_map.add_external_src( || match file_map.name { FileName::Real(ref name) => self.file_loader.read_file(name).ok(), @@ -719,7 +718,7 @@ impl FilePathMapping { mod tests { use super::*; use std::borrow::Cow; - use std::rc::Rc; + use rustc_data_structures::sync::Lrc; #[test] fn t1 () { @@ -940,7 +939,7 @@ mod tests { /// `substring` in `source_text`. trait CodeMapExtension { fn span_substr(&self, - file: &Rc, + file: &Lrc, source_text: &str, substring: &str, n: usize) @@ -949,7 +948,7 @@ mod tests { impl CodeMapExtension for CodeMap { fn span_substr(&self, - file: &Rc, + file: &Lrc, source_text: &str, substring: &str, n: usize) diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index d53335f5be7fb..bb61f24026b62 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -28,6 +28,7 @@ use std::collections::HashMap; use std::iter; use std::path::PathBuf; use std::rc::Rc; +use rustc_data_structures::sync::{Send, Sync, Lrc}; use std::default::Default; use tokenstream::{self, TokenStream}; @@ -507,7 +508,6 @@ pub enum MacroKind { Derive, } -/// An enum representing the different kinds of syntax extensions. pub enum SyntaxExtension { /// A syntax extension that is attached to an item and creates new items /// based upon it. @@ -515,26 +515,26 @@ pub enum SyntaxExtension { /// `#[derive(...)]` is a `MultiItemDecorator`. /// /// Prefer ProcMacro or MultiModifier since they are more flexible. - MultiDecorator(Box), + MultiDecorator(Box), /// A syntax extension that is attached to an item and modifies it /// in-place. Also allows decoration, i.e., creating new items. - MultiModifier(Box), + MultiModifier(Box), /// A function-like procedural macro. TokenStream -> TokenStream. - ProcMacro(Box), + ProcMacro(Box), /// An attribute-like procedural macro. TokenStream, TokenStream -> TokenStream. /// The first TokenSteam is the attribute, the second is the annotated item. /// Allows modification of the input items and adding new items, similar to /// MultiModifier, but uses TokenStreams, rather than AST nodes. - AttrProcMacro(Box), + AttrProcMacro(Box), /// A normal, function-like syntax extension. /// /// `bytes!` is a `NormalTT`. NormalTT { - expander: Box, + expander: Box, def_info: Option<(ast::NodeId, Span)>, /// Whether the contents of the macro can /// directly use `#[unstable]` things (true == yes). @@ -547,13 +547,13 @@ pub enum SyntaxExtension { /// A function-like syntax extension that has an extra ident before /// the block. /// - IdentTT(Box, Option, bool), + IdentTT(Box, Option, bool), /// An attribute-like procedural macro. TokenStream -> TokenStream. /// The input is the annotated item. /// Allows generating code to implement a Trait for a given struct /// or enum item. - ProcMacroDerive(Box, Vec /* inert attribute names */), + ProcMacroDerive(Box, Vec /* inert attribute names */), /// An attribute-like procedural macro that derives a builtin trait. BuiltinDerive(BuiltinDeriveFn), @@ -561,7 +561,7 @@ pub enum SyntaxExtension { /// A declarative macro, e.g. `macro m() {}`. /// /// The second element is the definition site span. - DeclMacro(Box, Option<(ast::NodeId, Span)>), + DeclMacro(Box, Option<(ast::NodeId, Span)>), } impl SyntaxExtension { @@ -603,15 +603,15 @@ pub trait Resolver { fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool; fn visit_expansion(&mut self, mark: Mark, expansion: &Expansion, derives: &[Mark]); - fn add_builtin(&mut self, ident: ast::Ident, ext: Rc); + fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc); fn resolve_imports(&mut self); // Resolves attribute and derive legacy macros from `#![plugin(..)]`. fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec) -> Option; fn resolve_invoc(&mut self, invoc: &mut Invocation, scope: Mark, force: bool) - -> Result>, Determinacy>; + -> Result>, Determinacy>; fn resolve_macro(&mut self, scope: Mark, path: &ast::Path, kind: MacroKind, force: bool) - -> Result, Determinacy>; + -> Result, Determinacy>; fn check_unused_macros(&self); } @@ -630,16 +630,16 @@ impl Resolver for DummyResolver { fn is_whitelisted_legacy_custom_derive(&self, _name: Name) -> bool { false } fn visit_expansion(&mut self, _invoc: Mark, _expansion: &Expansion, _derives: &[Mark]) {} - fn add_builtin(&mut self, _ident: ast::Ident, _ext: Rc) {} + fn add_builtin(&mut self, _ident: ast::Ident, _ext: Lrc) {} fn resolve_imports(&mut self) {} fn find_legacy_attr_invoc(&mut self, _attrs: &mut Vec) -> Option { None } fn resolve_invoc(&mut self, _invoc: &mut Invocation, _scope: Mark, _force: bool) - -> Result>, Determinacy> { + -> Result>, Determinacy> { Err(Determinacy::Determined) } fn resolve_macro(&mut self, _scope: Mark, _path: &ast::Path, _kind: MacroKind, - _force: bool) -> Result, Determinacy> { + _force: bool) -> Result, Determinacy> { Err(Determinacy::Determined) } fn check_unused_macros(&self) {} diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 81baa0c3954ca..fc4624ba3bb0b 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -39,6 +39,7 @@ use std::io::Read; use std::mem; use std::rc::Rc; use std::path::PathBuf; +use rustc_data_structures::sync::Lrc; macro_rules! expansions { ($($kind:ident: $ty:ty [$($vec:ident, $ty_elt:ty)*], $kind_name:expr, .$make:ident, @@ -446,7 +447,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { } } - fn expand_invoc(&mut self, invoc: Invocation, ext: Rc) -> Expansion { + fn expand_invoc(&mut self, invoc: Invocation, ext: Lrc) -> Expansion { let result = match invoc.kind { InvocationKind::Bang { .. } => self.expand_bang_invoc(invoc, ext), InvocationKind::Attr { .. } => self.expand_attr_invoc(invoc, ext), @@ -470,7 +471,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { result } - fn expand_attr_invoc(&mut self, invoc: Invocation, ext: Rc) -> Expansion { + fn expand_attr_invoc(&mut self, invoc: Invocation, ext: Lrc) -> Expansion { let Invocation { expansion_kind: kind, .. } = invoc; let (attr, item) = match invoc.kind { InvocationKind::Attr { attr, item, .. } => (attr.unwrap(), item), @@ -525,7 +526,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { } /// Expand a macro invocation. Returns the result of expansion. - fn expand_bang_invoc(&mut self, invoc: Invocation, ext: Rc) -> Expansion { + fn expand_bang_invoc(&mut self, invoc: Invocation, ext: Lrc) -> Expansion { let (mark, kind) = (invoc.expansion_data.mark, invoc.expansion_kind); let (mac, ident, span) = match invoc.kind { InvocationKind::Bang { mac, ident, span } => (mac, ident, span), @@ -651,7 +652,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { } /// Expand a derive invocation. Returns the result of expansion. - fn expand_derive_invoc(&mut self, invoc: Invocation, ext: Rc) -> Expansion { + fn expand_derive_invoc(&mut self, invoc: Invocation, ext: Lrc) -> Expansion { let Invocation { expansion_kind: kind, .. } = invoc; let (path, item) = match invoc.kind { InvocationKind::Derive { path, item } => (path, item), diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index 4da485fc9a42c..42552cc1407ba 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -24,7 +24,7 @@ use util::small_vector::SmallVector; use std::fs::File; use std::io::prelude::*; use std::path::PathBuf; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; // These macros all relate to the file system; they either return // the column/row/filename of the expression, or they include @@ -183,7 +183,7 @@ pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::Toke // dependency information, but don't enter it's contents cx.codemap().new_filemap_and_lines(&file, ""); - base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Rc::new(bytes)))) + base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes)))) } } } diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 5e58f003c2be7..823ca1b025de8 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use rustc_data_structures::sync::RwLock; + use {ast, attr}; use syntax_pos::{Span, DUMMY_SP}; use ext::base::{DummyResult, ExtCtxt, MacResult, SyntaxExtension}; @@ -26,10 +28,10 @@ use parse::token::Token::*; use symbol::Symbol; use tokenstream::{TokenStream, TokenTree}; -use std::cell::RefCell; use std::collections::HashMap; use std::collections::hash_map::Entry; -use std::rc::Rc; + +use rustc_data_structures::sync::Lrc; pub struct ParserAnyMacro<'a> { parser: Parser<'a>, @@ -183,7 +185,7 @@ fn generic_extension<'cx>(cx: &'cx mut ExtCtxt, // Holy self-referential! /// Converts a `macro_rules!` invocation into a syntax extension. -pub fn compile(sess: &ParseSess, features: &RefCell, def: &ast::Item) -> SyntaxExtension { +pub fn compile(sess: &ParseSess, features: &RwLock, def: &ast::Item) -> SyntaxExtension { let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs")); let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs")); @@ -199,7 +201,7 @@ pub fn compile(sess: &ParseSess, features: &RefCell, def: &ast::Item) // ...quasiquoting this would be nice. // These spans won't matter, anyways let argument_gram = vec![ - quoted::TokenTree::Sequence(DUMMY_SP, Rc::new(quoted::SequenceRepetition { + quoted::TokenTree::Sequence(DUMMY_SP, Lrc::new(quoted::SequenceRepetition { tts: vec![ quoted::TokenTree::MetaVarDecl(DUMMY_SP, lhs_nm, ast::Ident::from_str("tt")), quoted::TokenTree::Token(DUMMY_SP, token::FatArrow), @@ -210,7 +212,7 @@ pub fn compile(sess: &ParseSess, features: &RefCell, def: &ast::Item) num_captures: 2, })), // to phase into semicolon-termination instead of semicolon-separation - quoted::TokenTree::Sequence(DUMMY_SP, Rc::new(quoted::SequenceRepetition { + quoted::TokenTree::Sequence(DUMMY_SP, Lrc::new(quoted::SequenceRepetition { tts: vec![quoted::TokenTree::Token(DUMMY_SP, token::Semi)], separator: None, op: quoted::KleeneOp::ZeroOrMore, @@ -293,7 +295,7 @@ pub fn compile(sess: &ParseSess, features: &RefCell, def: &ast::Item) } fn check_lhs_nt_follows(sess: &ParseSess, - features: &RefCell, + features: &RwLock, attrs: &[ast::Attribute], lhs: "ed::TokenTree) -> bool { // lhs is going to be like TokenTree::Delimited(...), where the @@ -350,7 +352,7 @@ fn check_rhs(sess: &ParseSess, rhs: "ed::TokenTree) -> bool { } fn check_matcher(sess: &ParseSess, - features: &RefCell, + features: &RwLock, attrs: &[ast::Attribute], matcher: &[quoted::TokenTree]) -> bool { let first_sets = FirstSets::new(matcher); @@ -598,7 +600,7 @@ impl TokenSet { // Requires that `first_sets` is pre-computed for `matcher`; // see `FirstSets::new`. fn check_matcher_core(sess: &ParseSess, - features: &RefCell, + features: &RwLock, attrs: &[ast::Attribute], first_sets: &FirstSets, matcher: &[quoted::TokenTree], @@ -865,7 +867,7 @@ fn is_in_follow(tok: "ed::TokenTree, frag: &str) -> Result, + features: &RwLock, attrs: &[ast::Attribute], tok: "ed::TokenTree) -> Result<(), String> { debug!("has_legal_fragment_specifier({:?})", tok); @@ -880,7 +882,7 @@ fn has_legal_fragment_specifier(sess: &ParseSess, } fn is_legal_fragment_specifier(sess: &ParseSess, - features: &RefCell, + features: &RwLock, attrs: &[ast::Attribute], frag_name: &str, frag_span: Span) -> bool { diff --git a/src/libsyntax/ext/tt/quoted.rs b/src/libsyntax/ext/tt/quoted.rs index 0e21e3f6b0010..1a9cee768c340 100644 --- a/src/libsyntax/ext/tt/quoted.rs +++ b/src/libsyntax/ext/tt/quoted.rs @@ -16,7 +16,7 @@ use symbol::keywords; use syntax_pos::{DUMMY_SP, Span, BytePos}; use tokenstream; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub struct Delimited { @@ -77,9 +77,9 @@ pub enum KleeneOp { #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)] pub enum TokenTree { Token(Span, token::Token), - Delimited(Span, Rc), + Delimited(Span, Lrc), /// A kleene-style repetition sequence - Sequence(Span, Rc), + Sequence(Span, Lrc), /// E.g. `$var` MetaVar(Span, ast::Ident), /// E.g. `$var:expr`. This is only used in the left hand side of MBE macros. @@ -189,7 +189,7 @@ fn parse_tree(tree: tokenstream::TokenTree, let sequence = parse(delimited.tts.into(), expect_matchers, sess); let (separator, op) = parse_sep_and_kleene_op(trees, span, sess); let name_captures = macro_parser::count_names(&sequence); - TokenTree::Sequence(span, Rc::new(SequenceRepetition { + TokenTree::Sequence(span, Lrc::new(SequenceRepetition { tts: sequence, separator, op, @@ -215,7 +215,7 @@ fn parse_tree(tree: tokenstream::TokenTree, }, tokenstream::TokenTree::Token(span, tok) => TokenTree::Token(span, tok), tokenstream::TokenTree::Delimited(span, delimited) => { - TokenTree::Delimited(span, Rc::new(Delimited { + TokenTree::Delimited(span, Lrc::new(Delimited { delim: delimited.delim, tts: parse(delimited.tts.into(), expect_matchers, sess), })) diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index d51b0d0ae3e93..7883c4bbc1648 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -20,6 +20,7 @@ use tokenstream::{TokenStream, TokenTree, Delimited}; use util::small_vector::SmallVector; use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use std::mem; use std::ops::Add; use std::collections::HashMap; @@ -27,12 +28,12 @@ use std::collections::HashMap; // An iterator over the token trees in a delimited token tree (`{ ... }`) or a sequence (`$(...)`). enum Frame { Delimited { - forest: Rc, + forest: Lrc, idx: usize, span: Span, }, Sequence { - forest: Rc, + forest: Lrc, idx: usize, sep: Option, }, @@ -40,7 +41,7 @@ enum Frame { impl Frame { fn new(tts: Vec) -> Frame { - let forest = Rc::new(quoted::Delimited { delim: token::NoDelim, tts: tts }); + let forest = Lrc::new(quoted::Delimited { delim: token::NoDelim, tts: tts }); Frame::Delimited { forest: forest, idx: 0, span: DUMMY_SP } } } diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 9916b74aeb315..25841578e6297 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -29,7 +29,7 @@ use tokenstream::*; use util::small_vector::SmallVector; use util::move_map::MoveMap; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; pub trait Folder : Sized { // Any additions to this trait should happen in form @@ -577,7 +577,7 @@ pub fn noop_fold_token(t: token::Token, fld: &mut T) -> token::Token token::Ident(id) => token::Ident(fld.fold_ident(id)), token::Lifetime(id) => token::Lifetime(fld.fold_ident(id)), token::Interpolated(nt) => { - let nt = match Rc::try_unwrap(nt) { + let nt = match Lrc::try_unwrap(nt) { Ok(nt) => nt, Err(nt) => (*nt).clone(), }; diff --git a/src/libsyntax/json.rs b/src/libsyntax/json.rs index 54c726d84621f..a31439632cad4 100644 --- a/src/libsyntax/json.rs +++ b/src/libsyntax/json.rs @@ -26,7 +26,7 @@ use errors::{DiagnosticBuilder, SubDiagnostic, CodeSuggestion, CodeMapper}; use errors::DiagnosticId; use errors::emitter::{Emitter, EmitterWriter}; -use std::rc::Rc; +use rustc_data_structures::sync::{self, Sync, Lrc}; use std::io::{self, Write}; use std::vec; use std::sync::{Arc, Mutex}; @@ -36,13 +36,13 @@ use rustc_serialize::json::{as_json, as_pretty_json}; pub struct JsonEmitter { dst: Box, registry: Option, - cm: Rc, + cm: Lrc, pretty: bool, } impl JsonEmitter { pub fn stderr(registry: Option, - code_map: Rc, + code_map: Lrc, pretty: bool) -> JsonEmitter { JsonEmitter { dst: Box::new(io::stderr()), @@ -54,12 +54,12 @@ impl JsonEmitter { pub fn basic(pretty: bool) -> JsonEmitter { let file_path_mapping = FilePathMapping::empty(); - JsonEmitter::stderr(None, Rc::new(CodeMap::new(file_path_mapping)), pretty) + JsonEmitter::stderr(None, Lrc::new(CodeMap::new(file_path_mapping)), pretty) } pub fn new(dst: Box, registry: Option, - code_map: Rc, + code_map: Lrc, pretty: bool) -> JsonEmitter { JsonEmitter { dst, diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index 0b51f2e981456..350f84359f2e5 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -26,6 +26,8 @@ #![feature(i128_type)] #![feature(const_atomic_usize_new)] +#![recursion_limit="256"] + // See librustc_cratesio_shim/Cargo.toml for a comment explaining this. #[allow(unused_extern_crates)] extern crate rustc_cratesio_shim; diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 9828995362a35..6839be9e77595 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -20,7 +20,7 @@ use std_unicode::property::Pattern_White_Space; use std::borrow::Cow; use std::char; use std::mem::replace; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; pub mod comments; mod tokentrees; @@ -48,7 +48,7 @@ pub struct StringReader<'a> { pub col: CharPos, /// The current character (which has been read from self.pos) pub ch: Option, - pub filemap: Rc, + pub filemap: Lrc, /// If Some, stop reading the source at this position (inclusive). pub terminator: Option, /// Whether to record new-lines and multibyte chars in filemap. @@ -61,7 +61,7 @@ pub struct StringReader<'a> { pub fatal_errs: Vec>, // cache a direct reference to the source text, so that we don't have to // retrieve it via `self.filemap.src.as_ref().unwrap()` all the time. - source_text: Rc, + source_text: Lrc, /// Stack of open delimiters and their spans. Used for error message. token: token::Token, span: Span, @@ -152,13 +152,13 @@ impl<'a> StringReader<'a> { impl<'a> StringReader<'a> { /// For comments.rs, which hackily pokes into next_pos and ch - pub fn new_raw(sess: &'a ParseSess, filemap: Rc) -> Self { + pub fn new_raw(sess: &'a ParseSess, filemap: Lrc) -> Self { let mut sr = StringReader::new_raw_internal(sess, filemap); sr.bump(); sr } - fn new_raw_internal(sess: &'a ParseSess, filemap: Rc) -> Self { + fn new_raw_internal(sess: &'a ParseSess, filemap: Lrc) -> Self { if filemap.src.is_none() { sess.span_diagnostic.bug(&format!("Cannot lex filemap without source: {}", filemap.name)); @@ -187,7 +187,7 @@ impl<'a> StringReader<'a> { } } - pub fn new(sess: &'a ParseSess, filemap: Rc) -> Self { + pub fn new(sess: &'a ParseSess, filemap: Lrc) -> Self { let mut sr = StringReader::new_raw(sess, filemap); if sr.advance_token().is_err() { sr.emit_fatal_errors(); @@ -1737,13 +1737,11 @@ mod tests { use errors; use feature_gate::UnstableFeatures; use parse::token; - use std::cell::RefCell; use std::collections::HashSet; use std::io; use std::path::PathBuf; - use std::rc::Rc; - - fn mk_sess(cm: Rc) -> ParseSess { + use rustc_data_structures::sync::{Lrc, Lock}; + fn mk_sess(cm: Lrc) -> ParseSess { let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()), Some(cm.clone()), false); @@ -1751,10 +1749,10 @@ mod tests { span_diagnostic: errors::Handler::with_emitter(true, false, Box::new(emitter)), unstable_features: UnstableFeatures::from_environment(), config: CrateConfig::new(), - included_mod_stack: RefCell::new(Vec::new()), + included_mod_stack: Lock::new(Vec::new()), code_map: cm, - missing_fragment_specifiers: RefCell::new(HashSet::new()), - non_modrs_mods: RefCell::new(vec![]), + missing_fragment_specifiers: Lock::new(HashSet::new()), + non_modrs_mods: Lock::new(vec![]), } } @@ -1769,7 +1767,7 @@ mod tests { #[test] fn t1() { - let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); + let cm = Lrc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); let mut string_reader = setup(&cm, &sh, @@ -1813,7 +1811,7 @@ mod tests { #[test] fn doublecolonparsing() { - let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); + let cm = Lrc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); check_tokenization(setup(&cm, &sh, "a b".to_string()), vec![mk_ident("a"), token::Whitespace, mk_ident("b")]); @@ -1821,7 +1819,7 @@ mod tests { #[test] fn dcparsing_2() { - let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); + let cm = Lrc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); check_tokenization(setup(&cm, &sh, "a::b".to_string()), vec![mk_ident("a"), token::ModSep, mk_ident("b")]); @@ -1829,7 +1827,7 @@ mod tests { #[test] fn dcparsing_3() { - let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); + let cm = Lrc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); check_tokenization(setup(&cm, &sh, "a ::b".to_string()), vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]); @@ -1837,7 +1835,7 @@ mod tests { #[test] fn dcparsing_4() { - let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); + let cm = Lrc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); check_tokenization(setup(&cm, &sh, "a:: b".to_string()), vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]); @@ -1845,7 +1843,7 @@ mod tests { #[test] fn character_a() { - let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); + let cm = Lrc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); assert_eq!(setup(&cm, &sh, "'a'".to_string()).next_token().tok, token::Literal(token::Char(Symbol::intern("a")), None)); @@ -1853,7 +1851,7 @@ mod tests { #[test] fn character_space() { - let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); + let cm = Lrc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); assert_eq!(setup(&cm, &sh, "' '".to_string()).next_token().tok, token::Literal(token::Char(Symbol::intern(" ")), None)); @@ -1861,7 +1859,7 @@ mod tests { #[test] fn character_escaped() { - let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); + let cm = Lrc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); assert_eq!(setup(&cm, &sh, "'\\n'".to_string()).next_token().tok, token::Literal(token::Char(Symbol::intern("\\n")), None)); @@ -1869,7 +1867,7 @@ mod tests { #[test] fn lifetime_name() { - let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); + let cm = Lrc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); assert_eq!(setup(&cm, &sh, "'abc".to_string()).next_token().tok, token::Lifetime(Ident::from_str("'abc"))); @@ -1877,7 +1875,7 @@ mod tests { #[test] fn raw_string() { - let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); + let cm = Lrc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); assert_eq!(setup(&cm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string()) .next_token() @@ -1887,7 +1885,7 @@ mod tests { #[test] fn literal_suffixes() { - let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); + let cm = Lrc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); macro_rules! test { ($input: expr, $tok_type: ident, $tok_contents: expr) => {{ @@ -1931,7 +1929,7 @@ mod tests { #[test] fn nested_block_comments() { - let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); + let cm = Lrc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); let mut lexer = setup(&cm, &sh, "/* /* */ */'a'".to_string()); match lexer.next_token().tok { @@ -1944,7 +1942,7 @@ mod tests { #[test] fn crlf_comments() { - let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); + let cm = Lrc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); let mut lexer = setup(&cm, &sh, "// test\r\n/// test\r\n".to_string()); let comment = lexer.next_token(); diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index a38ceba2f45a9..52fb6e128f08a 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -10,6 +10,7 @@ //! The main parser interface +use rustc_data_structures::sync::{Lrc, Lock}; use ast::{self, CrateConfig}; use codemap::{CodeMap, FilePathMapping}; use syntax_pos::{self, Span, FileMap, NO_EXPANSION, FileName}; @@ -21,11 +22,9 @@ use str::char_at; use symbol::Symbol; use tokenstream::{TokenStream, TokenTree}; -use std::cell::RefCell; use std::collections::HashSet; use std::iter; use std::path::{Path, PathBuf}; -use std::rc::Rc; use std::str; pub type PResult<'a, T> = Result>; @@ -46,18 +45,18 @@ pub struct ParseSess { pub span_diagnostic: Handler, pub unstable_features: UnstableFeatures, pub config: CrateConfig, - pub missing_fragment_specifiers: RefCell>, + pub missing_fragment_specifiers: Lock>, // Spans where a `mod foo;` statement was included in a non-mod.rs file. // These are used to issue errors if the non_modrs_mods feature is not enabled. - pub non_modrs_mods: RefCell>, + pub non_modrs_mods: Lock>, /// Used to determine and report recursive mod inclusions - included_mod_stack: RefCell>, - code_map: Rc, + included_mod_stack: Lock>, + code_map: Lrc, } impl ParseSess { pub fn new(file_path_mapping: FilePathMapping) -> Self { - let cm = Rc::new(CodeMap::new(file_path_mapping)); + let cm = Lrc::new(CodeMap::new(file_path_mapping)); let handler = Handler::with_tty_emitter(ColorConfig::Auto, true, false, @@ -65,15 +64,15 @@ impl ParseSess { ParseSess::with_span_handler(handler, cm) } - pub fn with_span_handler(handler: Handler, code_map: Rc) -> ParseSess { + pub fn with_span_handler(handler: Handler, code_map: Lrc) -> ParseSess { ParseSess { span_diagnostic: handler, unstable_features: UnstableFeatures::from_environment(), config: HashSet::new(), - missing_fragment_specifiers: RefCell::new(HashSet::new()), - included_mod_stack: RefCell::new(vec![]), + missing_fragment_specifiers: Lock::new(HashSet::new()), + included_mod_stack: Lock::new(vec![]), code_map, - non_modrs_mods: RefCell::new(vec![]), + non_modrs_mods: Lock::new(vec![]), } } @@ -183,7 +182,7 @@ pub fn new_sub_parser_from_file<'a>(sess: &'a ParseSess, } /// Given a filemap and config, return a parser -pub fn filemap_to_parser(sess: & ParseSess, filemap: Rc, ) -> Parser { +pub fn filemap_to_parser(sess: & ParseSess, filemap: Lrc) -> Parser { let end_pos = filemap.end_pos; let mut parser = stream_to_parser(sess, filemap_to_stream(sess, filemap, None)); @@ -206,7 +205,7 @@ pub fn new_parser_from_tts(sess: &ParseSess, tts: Vec) -> Parser { /// Given a session and a path and an optional span (for error reporting), /// add the path to the session's codemap and return the new filemap. fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option) - -> Rc { + -> Lrc { match sess.codemap().load_file(path) { Ok(filemap) => filemap, Err(e) => { @@ -220,7 +219,7 @@ fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option) } /// Given a filemap, produce a sequence of token-trees -pub fn filemap_to_stream(sess: &ParseSess, filemap: Rc, override_span: Option) +pub fn filemap_to_stream(sess: &ParseSess, filemap: Lrc, override_span: Option) -> TokenStream { let mut srdr = lexer::StringReader::new(sess, filemap); srdr.override_span = override_span; @@ -422,7 +421,7 @@ pub fn lit_token(lit: token::Lit, suf: Option, diag: Option<(Span, &Hand (true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str())))) } token::ByteStrRaw(i, _) => { - (true, Some(LitKind::ByteStr(Rc::new(i.to_string().into_bytes())))) + (true, Some(LitKind::ByteStr(Lrc::new(i.to_string().into_bytes())))) } } } @@ -496,7 +495,7 @@ pub fn byte_lit(lit: &str) -> (u8, usize) { } } -pub fn byte_str_lit(lit: &str) -> Rc> { +pub fn byte_str_lit(lit: &str) -> Lrc> { let mut res = Vec::with_capacity(lit.len()); // FIXME #8372: This could be a for-loop if it didn't borrow the iterator @@ -553,7 +552,7 @@ pub fn byte_str_lit(lit: &str) -> Rc> { } } - Rc::new(res) + Lrc::new(res) } pub fn integer_lit(s: &str, suffix: Option, diag: Option<(Span, &Handler)>) diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 05368c52d2c32..3405549b36763 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -25,9 +25,8 @@ use syntax_pos::{self, Span, FileName}; use tokenstream::{TokenStream, TokenTree}; use tokenstream; -use std::cell::Cell; use std::{cmp, fmt}; -use std::rc::Rc; +use rustc_data_structures::sync::{Lrc, LockCell}; #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)] pub enum BinOpToken { @@ -179,7 +178,7 @@ pub enum Token { // The `LazyTokenStream` is a pure function of the `Nonterminal`, // and so the `LazyTokenStream` can be ignored by Eq, Hash, etc. - Interpolated(Rc<(Nonterminal, LazyTokenStream)>), + Interpolated(Lrc<(Nonterminal, LazyTokenStream)>), // Can be expanded into several tokens. /// Doc comment DocComment(ast::Name), @@ -199,7 +198,7 @@ pub enum Token { impl Token { pub fn interpolated(nt: Nonterminal) -> Token { - Token::Interpolated(Rc::new((nt, LazyTokenStream::new()))) + Token::Interpolated(Lrc::new((nt, LazyTokenStream::new()))) } /// Returns `true` if the token starts with '>'. @@ -559,13 +558,13 @@ pub fn is_op(tok: &Token) -> bool { } } -pub struct LazyTokenStream(Cell>); +pub struct LazyTokenStream(LockCell>); impl Clone for LazyTokenStream { fn clone(&self) -> Self { let opt_stream = self.0.take(); self.0.set(opt_stream.clone()); - LazyTokenStream(Cell::new(opt_stream)) + LazyTokenStream(LockCell::new(opt_stream)) } } @@ -584,7 +583,7 @@ impl fmt::Debug for LazyTokenStream { impl LazyTokenStream { pub fn new() -> Self { - LazyTokenStream(Cell::new(None)) + LazyTokenStream(LockCell::new(None)) } pub fn force TokenStream>(&self, f: F) -> TokenStream { diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs index 1a0f4e9278da6..adb8f8569eb18 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -21,7 +21,6 @@ use std::mem; use std::vec; use attr::{self, HasAttrs}; use syntax_pos::{self, DUMMY_SP, NO_EXPANSION, Span, FileMap, BytePos}; -use std::rc::Rc; use codemap::{self, CodeMap, ExpnInfo, NameAndSpan, MacroAttribute, dummy_spanned}; use errors; diff --git a/src/libsyntax/test_snippet.rs b/src/libsyntax/test_snippet.rs index 5072f2e2793f1..21053145d9bb9 100644 --- a/src/libsyntax/test_snippet.rs +++ b/src/libsyntax/test_snippet.rs @@ -13,7 +13,7 @@ use errors::Handler; use errors::emitter::EmitterWriter; use std::io; use std::io::prelude::*; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use std::str; use std::sync::{Arc, Mutex}; use std::path::Path; @@ -48,7 +48,7 @@ impl Write for Shared { fn test_harness(file_text: &str, span_labels: Vec, expected_output: &str) { let output = Arc::new(Mutex::new(Vec::new())); - let code_map = Rc::new(CodeMap::new(FilePathMapping::empty())); + let code_map = Lrc::new(CodeMap::new(FilePathMapping::empty())); code_map.new_filemap_and_lines(Path::new("test.rs"), &file_text); let primary_span = make_span(&file_text, &span_labels[0].start, &span_labels[0].end); diff --git a/src/libsyntax/util/rc_slice.rs b/src/libsyntax/util/rc_slice.rs index d6939d71129e4..520b7a48e3025 100644 --- a/src/libsyntax/util/rc_slice.rs +++ b/src/libsyntax/util/rc_slice.rs @@ -10,14 +10,14 @@ use std::fmt; use std::ops::{Deref, Range}; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use rustc_data_structures::stable_hasher::{StableHasher, StableHasherResult, HashStable}; #[derive(Clone)] pub struct RcSlice { - data: Rc>, + data: Lrc>, offset: u32, len: u32, } @@ -27,7 +27,7 @@ impl RcSlice { RcSlice { offset: 0, len: vec.len() as u32, - data: Rc::new(vec.into_boxed_slice()), + data: Lrc::new(vec.into_boxed_slice()), } } diff --git a/src/libsyntax_ext/Cargo.toml b/src/libsyntax_ext/Cargo.toml index 1c4702402886d..d8eeb5ed2554a 100644 --- a/src/libsyntax_ext/Cargo.toml +++ b/src/libsyntax_ext/Cargo.toml @@ -14,3 +14,4 @@ proc_macro = { path = "../libproc_macro" } rustc_errors = { path = "../librustc_errors" } syntax = { path = "../libsyntax" } syntax_pos = { path = "../libsyntax_pos" } +rustc_data_structures = { path = "../librustc_data_structures" } \ No newline at end of file diff --git a/src/libsyntax_ext/deriving/mod.rs b/src/libsyntax_ext/deriving/mod.rs index 8159893e784e4..6bc4ee0b399f9 100644 --- a/src/libsyntax_ext/deriving/mod.rs +++ b/src/libsyntax_ext/deriving/mod.rs @@ -10,7 +10,7 @@ //! The compiler code necessary to implement the `#[derive]` extensions. -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use syntax::ast; use syntax::ext::base::{Annotatable, ExtCtxt, SyntaxExtension, Resolver}; use syntax::ext::build::AstBuilder; @@ -65,7 +65,7 @@ macro_rules! derive_traits { $( resolver.add_builtin( ast::Ident::with_empty_ctxt(Symbol::intern($name)), - Rc::new(SyntaxExtension::BuiltinDerive($func)) + Lrc::new(SyntaxExtension::BuiltinDerive($func)) ); )* } diff --git a/src/libsyntax_ext/lib.rs b/src/libsyntax_ext/lib.rs index 82d6ee5afa05b..772dec72ab98e 100644 --- a/src/libsyntax_ext/lib.rs +++ b/src/libsyntax_ext/lib.rs @@ -23,6 +23,7 @@ extern crate fmt_macros; extern crate syntax; extern crate syntax_pos; extern crate proc_macro; +extern crate rustc_data_structures; extern crate rustc_errors as errors; mod asm; @@ -44,7 +45,7 @@ pub mod deriving; pub mod proc_macro_impl; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; use syntax::ast; use syntax::ext::base::{MacroExpanderFn, NormalTT, NamedSyntaxExtension}; use syntax::symbol::Symbol; @@ -55,7 +56,7 @@ pub fn register_builtins(resolver: &mut syntax::ext::base::Resolver, deriving::register_builtin_derives(resolver); let mut register = |name, ext| { - resolver.add_builtin(ast::Ident::with_empty_ctxt(name), Rc::new(ext)); + resolver.add_builtin(ast::Ident::with_empty_ctxt(name), Lrc::new(ext)); }; macro_rules! register { diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs index 85f0925b98210..623ef8c9bb3af 100644 --- a/src/libsyntax_pos/lib.rs +++ b/src/libsyntax_pos/lib.rs @@ -27,20 +27,20 @@ #![feature(specialization)] use std::borrow::Cow; -use std::cell::{Cell, RefCell}; +use std::cell::Cell; use std::cmp::{self, Ordering}; use std::fmt; use std::hash::{Hasher, Hash}; use std::ops::{Add, Sub}; use std::path::PathBuf; -use std::rc::Rc; use rustc_data_structures::stable_hasher::StableHasher; - -extern crate rustc_data_structures; +use rustc_data_structures::sync::{Lrc, Lock}; use serialize::{Encodable, Decodable, Encoder, Decoder}; +extern crate rustc_data_structures; + extern crate serialize; extern crate serialize as rustc_serialize; // used by deriving @@ -675,22 +675,22 @@ pub struct FileMap { /// Indicates which crate this FileMap was imported from. pub crate_of_origin: u32, /// The complete source code - pub src: Option>, + pub src: Option>, /// The source code's hash pub src_hash: u128, /// The external source code (used for external crates, which will have a `None` /// value as `self.src`. - pub external_src: RefCell, + pub external_src: Lock, /// The start position of this source in the CodeMap pub start_pos: BytePos, /// The end position of this source in the CodeMap pub end_pos: BytePos, /// Locations of lines beginnings in the source code - pub lines: RefCell>, + pub lines: Lock>, /// Locations of multi-byte characters in the source code - pub multibyte_chars: RefCell>, + pub multibyte_chars: Lock>, /// Width of characters that are not narrow in the source code - pub non_narrow_chars: RefCell>, + pub non_narrow_chars: Lock>, /// A hash of the filename, used for speeding up the incr. comp. hashing. pub name_hash: u128, } @@ -820,10 +820,10 @@ impl Decodable for FileMap { end_pos, src: None, src_hash, - external_src: RefCell::new(ExternalSource::AbsentOk), - lines: RefCell::new(lines), - multibyte_chars: RefCell::new(multibyte_chars), - non_narrow_chars: RefCell::new(non_narrow_chars), + external_src: Lock::new(ExternalSource::AbsentOk), + lines: Lock::new(lines), + multibyte_chars: Lock::new(multibyte_chars), + non_narrow_chars: Lock::new(non_narrow_chars), name_hash, }) }) @@ -861,14 +861,14 @@ impl FileMap { name_was_remapped, unmapped_path: Some(unmapped_path), crate_of_origin: 0, - src: Some(Rc::new(src)), + src: Some(Lrc::new(src)), src_hash, - external_src: RefCell::new(ExternalSource::Unneeded), + external_src: Lock::new(ExternalSource::Unneeded), start_pos, end_pos: Pos::from_usize(end_pos), - lines: RefCell::new(Vec::new()), - multibyte_chars: RefCell::new(Vec::new()), - non_narrow_chars: RefCell::new(Vec::new()), + lines: Lock::new(Vec::new()), + multibyte_chars: Lock::new(Vec::new()), + non_narrow_chars: Lock::new(Vec::new()), name_hash, } } @@ -1124,7 +1124,7 @@ impl Sub for CharPos { #[derive(Debug, Clone)] pub struct Loc { /// Information about the original source - pub file: Rc, + pub file: Lrc, /// The (1-based) line number pub line: usize, /// The (0-based) column offset @@ -1141,14 +1141,14 @@ pub struct LocWithOpt { pub filename: FileName, pub line: usize, pub col: CharPos, - pub file: Option>, + pub file: Option>, } // used to be structural records. Better names, anyone? #[derive(Debug)] -pub struct FileMapAndLine { pub fm: Rc, pub line: usize } +pub struct FileMapAndLine { pub fm: Lrc, pub line: usize } #[derive(Debug)] -pub struct FileMapAndBytePos { pub fm: Rc, pub pos: BytePos } +pub struct FileMapAndBytePos { pub fm: Lrc, pub pos: BytePos } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct LineInfo { @@ -1163,7 +1163,7 @@ pub struct LineInfo { } pub struct FileLines { - pub file: Rc, + pub file: Lrc, pub lines: Vec } diff --git a/src/test/run-pass-fulldeps/issue-35829.rs b/src/test/run-pass-fulldeps/issue-35829.rs index f17a0494a69c4..d976114822249 100644 --- a/src/test/run-pass-fulldeps/issue-35829.rs +++ b/src/test/run-pass-fulldeps/issue-35829.rs @@ -13,17 +13,17 @@ #![feature(quote, rustc_private)] extern crate syntax; +extern crate rustc_data_structures; use syntax::ext::base::{ExtCtxt, DummyResolver}; use syntax::ext::expand::ExpansionConfig; use syntax::parse::ParseSess; use syntax::codemap::{FilePathMapping, dummy_spanned}; use syntax::print::pprust::expr_to_string; -use syntax::ast::{Expr, ExprKind, LitKind, StrStyle, RangeLimits}; -use syntax::symbol::Symbol; +use syntax::ast::{ExprKind, LitKind, RangeLimits}; use syntax::ptr::P; -use std::rc::Rc; +use rustc_data_structures::sync::Lrc; fn main() { let parse_sess = ParseSess::new(FilePathMapping::empty()); @@ -33,12 +33,12 @@ fn main() { // check byte string let byte_string = quote_expr!(&cx, b"one"); - let byte_string_lit_kind = LitKind::ByteStr(Rc::new(b"one".to_vec())); + let byte_string_lit_kind = LitKind::ByteStr(Lrc::new(b"one".to_vec())); assert_eq!(byte_string.node, ExprKind::Lit(P(dummy_spanned(byte_string_lit_kind)))); // check raw byte string let raw_byte_string = quote_expr!(&cx, br###"#"two"#"###); - let raw_byte_string_lit_kind = LitKind::ByteStr(Rc::new(b"#\"two\"#".to_vec())); + let raw_byte_string_lit_kind = LitKind::ByteStr(Lrc::new(b"#\"two\"#".to_vec())); assert_eq!(raw_byte_string.node, ExprKind::Lit(P(dummy_spanned(raw_byte_string_lit_kind)))); // check dotdoteq