Skip to content

Commit 913ad6d

Browse files
committed
Auto merge of #56732 - Zoxc:rustc-interface, r=oli-obk
Make the rustc driver and interface demand driven This introduces a new crate `rustc_interface` which is the canonical interface for creating and using the compiler. It allows you to access a `Compiler` type in a closure and that types have methods to run passes on demand. The interesting parts are found [here (defining the queries)](https://github.com/Zoxc/rust/blob/rustc-interface/src/librustc_interface/queries.rs#L78) and [here (methods to create a `Compiler`)](https://github.com/Zoxc/rust/blob/rustc-interface/src/librustc_interface/interface.rs). cc @rust-lang/compiler @rust-lang/dev-tools @rust-lang/rustdoc
2 parents 8ad727e + 51938c6 commit 913ad6d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+2511
-2745
lines changed

src/librustc/ich/impls_ty.rs

-5
Original file line numberDiff line numberDiff line change
@@ -946,11 +946,6 @@ impl_stable_hash_for!(struct ty::CrateInherentImpls {
946946
inherent_impls
947947
});
948948

949-
impl_stable_hash_for!(enum crate::session::CompileIncomplete {
950-
Stopped,
951-
Errored(error_reported)
952-
});
953-
954949
impl_stable_hash_for!(struct crate::util::common::ErrorReported {});
955950

956951
impl_stable_hash_for!(tuple_struct crate::middle::reachable::ReachableSet {

src/librustc/session/config.rs

+26-10
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use rustc_target::spec::{Target, TargetTriple};
1111
use crate::lint;
1212
use crate::middle::cstore;
1313

14+
use syntax;
1415
use syntax::ast::{self, IntTy, UintTy, MetaItemKind};
1516
use syntax::source_map::{FileName, FilePathMapping};
1617
use syntax::edition::{Edition, EDITION_NAME_LIST, DEFAULT_EDITION};
@@ -1494,6 +1495,15 @@ pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
14941495
ret
14951496
}
14961497

1498+
/// Converts the crate cfg! configuration from String to Symbol.
1499+
/// `rustc_interface::interface::Config` accepts this in the compiler configuration,
1500+
/// but the symbol interner is not yet set up then, so we must convert it later.
1501+
pub fn to_crate_config(cfg: FxHashSet<(String, Option<String>)>) -> ast::CrateConfig {
1502+
cfg.into_iter()
1503+
.map(|(a, b)| (Symbol::intern(&a), b.map(|b| Symbol::intern(&b))))
1504+
.collect()
1505+
}
1506+
14971507
pub fn build_configuration(sess: &Session, mut user_cfg: ast::CrateConfig) -> ast::CrateConfig {
14981508
// Combine the configuration requested by the session (command line) with
14991509
// some default and generated configuration items
@@ -1800,10 +1810,9 @@ pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
18001810
}
18011811

18021812
// Convert strings provided as --cfg [cfgspec] into a crate_cfg
1803-
pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> ast::CrateConfig {
1804-
cfgspecs
1805-
.into_iter()
1806-
.map(|s| {
1813+
pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
1814+
syntax::with_globals(move || {
1815+
let cfg = cfgspecs.into_iter().map(|s| {
18071816
let sess = parse::ParseSess::new(FilePathMapping::empty());
18081817
let filename = FileName::cfg_spec_source_code(&s);
18091818
let mut parser = parse::new_parser_from_source_str(&sess, filename, s.to_string());
@@ -1835,8 +1844,11 @@ pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> ast::CrateConfig {
18351844
}
18361845

18371846
error!(r#"expected `key` or `key="value"`"#);
1838-
})
1839-
.collect::<ast::CrateConfig>()
1847+
}).collect::<ast::CrateConfig>();
1848+
cfg.into_iter().map(|(a, b)| {
1849+
(a.to_string(), b.map(|b| b.to_string()))
1850+
}).collect()
1851+
})
18401852
}
18411853

18421854
pub fn get_cmd_lint_options(matches: &getopts::Matches,
@@ -1864,7 +1876,7 @@ pub fn get_cmd_lint_options(matches: &getopts::Matches,
18641876

18651877
pub fn build_session_options_and_crate_config(
18661878
matches: &getopts::Matches,
1867-
) -> (Options, ast::CrateConfig) {
1879+
) -> (Options, FxHashSet<(String, Option<String>)>) {
18681880
let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
18691881
Some("auto") => ColorConfig::Auto,
18701882
Some("always") => ColorConfig::Always,
@@ -2590,7 +2602,11 @@ mod tests {
25902602
use getopts;
25912603
use crate::lint;
25922604
use crate::middle::cstore;
2593-
use crate::session::config::{build_configuration, build_session_options_and_crate_config};
2605+
use crate::session::config::{
2606+
build_configuration,
2607+
build_session_options_and_crate_config,
2608+
to_crate_config
2609+
};
25942610
use crate::session::config::{LtoCli, LinkerPluginLto};
25952611
use crate::session::build_session;
25962612
use crate::session::search_paths::SearchPath;
@@ -2631,7 +2647,7 @@ mod tests {
26312647
let registry = errors::registry::Registry::new(&[]);
26322648
let (sessopts, cfg) = build_session_options_and_crate_config(matches);
26332649
let sess = build_session(sessopts, None, registry);
2634-
let cfg = build_configuration(&sess, cfg);
2650+
let cfg = build_configuration(&sess, to_crate_config(cfg));
26352651
assert!(cfg.contains(&(Symbol::intern("test"), None)));
26362652
});
26372653
}
@@ -2649,7 +2665,7 @@ mod tests {
26492665
let registry = errors::registry::Registry::new(&[]);
26502666
let (sessopts, cfg) = build_session_options_and_crate_config(matches);
26512667
let sess = build_session(sessopts, None, registry);
2652-
let cfg = build_configuration(&sess, cfg);
2668+
let cfg = build_configuration(&sess, to_crate_config(cfg));
26532669
let mut test_items = cfg.iter().filter(|&&(name, _)| name == "test");
26542670
assert!(test_items.next().is_some());
26552671
assert!(test_items.next().is_none());

src/librustc/session/mod.rs

+4-14
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,7 @@ impl Session {
311311
pub fn abort_if_errors(&self) {
312312
self.diagnostic().abort_if_errors();
313313
}
314-
pub fn compile_status(&self) -> Result<(), CompileIncomplete> {
314+
pub fn compile_status(&self) -> Result<(), ErrorReported> {
315315
compile_result_from_err_count(self.err_count())
316316
}
317317
pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
@@ -1124,7 +1124,7 @@ pub fn build_session_with_source_map(
11241124
build_session_(sopts, local_crate_source_file, diagnostic_handler, source_map, lint_caps)
11251125
}
11261126

1127-
pub fn build_session_(
1127+
fn build_session_(
11281128
sopts: config::Options,
11291129
local_crate_source_file: Option<PathBuf>,
11301130
span_diagnostic: errors::Handler,
@@ -1334,22 +1334,12 @@ pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
13341334
handler.emit(&MultiSpan::new(), msg, errors::Level::Warning);
13351335
}
13361336

1337-
#[derive(Copy, Clone, Debug)]
1338-
pub enum CompileIncomplete {
1339-
Stopped,
1340-
Errored(ErrorReported),
1341-
}
1342-
impl From<ErrorReported> for CompileIncomplete {
1343-
fn from(err: ErrorReported) -> CompileIncomplete {
1344-
CompileIncomplete::Errored(err)
1345-
}
1346-
}
1347-
pub type CompileResult = Result<(), CompileIncomplete>;
1337+
pub type CompileResult = Result<(), ErrorReported>;
13481338

13491339
pub fn compile_result_from_err_count(err_count: usize) -> CompileResult {
13501340
if err_count == 0 {
13511341
Ok(())
13521342
} else {
1353-
Err(CompileIncomplete::Errored(ErrorReported))
1343+
Err(ErrorReported)
13541344
}
13551345
}

src/librustc/ty/context.rs

+37-50
Original file line numberDiff line numberDiff line change
@@ -78,15 +78,13 @@ use crate::hir;
7878
pub struct AllArenas<'tcx> {
7979
pub global: WorkerLocal<GlobalArenas<'tcx>>,
8080
pub interner: SyncDroplessArena,
81-
global_ctxt: Option<GlobalCtxt<'tcx>>,
8281
}
8382

8483
impl<'tcx> AllArenas<'tcx> {
8584
pub fn new() -> Self {
8685
AllArenas {
8786
global: WorkerLocal::new(|_| GlobalArenas::default()),
8887
interner: SyncDroplessArena::default(),
89-
global_ctxt: None,
9088
}
9189
}
9290
}
@@ -1182,20 +1180,19 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
11821180
/// to the context. The closure enforces that the type context and any interned
11831181
/// value (types, substs, etc.) can only be used while `ty::tls` has a valid
11841182
/// reference to the context, to allow formatting values that need it.
1185-
pub fn create_and_enter<F, R>(s: &'tcx Session,
1186-
cstore: &'tcx CrateStoreDyn,
1187-
local_providers: ty::query::Providers<'tcx>,
1188-
extern_providers: ty::query::Providers<'tcx>,
1189-
arenas: &'tcx mut AllArenas<'tcx>,
1190-
resolutions: ty::Resolutions,
1191-
hir: hir_map::Map<'tcx>,
1192-
on_disk_query_result_cache: query::OnDiskCache<'tcx>,
1193-
crate_name: &str,
1194-
tx: mpsc::Sender<Box<dyn Any + Send>>,
1195-
output_filenames: &OutputFilenames,
1196-
f: F) -> R
1197-
where F: for<'b> FnOnce(TyCtxt<'b, 'tcx, 'tcx>) -> R
1198-
{
1183+
pub fn create_global_ctxt(
1184+
s: &'tcx Session,
1185+
cstore: &'tcx CrateStoreDyn,
1186+
local_providers: ty::query::Providers<'tcx>,
1187+
extern_providers: ty::query::Providers<'tcx>,
1188+
arenas: &'tcx AllArenas<'tcx>,
1189+
resolutions: ty::Resolutions,
1190+
hir: hir_map::Map<'tcx>,
1191+
on_disk_query_result_cache: query::OnDiskCache<'tcx>,
1192+
crate_name: &str,
1193+
tx: mpsc::Sender<Box<dyn Any + Send>>,
1194+
output_filenames: &OutputFilenames,
1195+
) -> GlobalCtxt<'tcx> {
11991196
let data_layout = TargetDataLayout::parse(&s.target.target).unwrap_or_else(|err| {
12001197
s.fatal(&err);
12011198
});
@@ -1247,7 +1244,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
12471244
Lrc::new(StableVec::new(v)));
12481245
}
12491246

1250-
arenas.global_ctxt = Some(GlobalCtxt {
1247+
GlobalCtxt {
12511248
sess: s,
12521249
cstore,
12531250
global_arenas: &arenas.global,
@@ -1293,15 +1290,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
12931290
alloc_map: Lock::new(interpret::AllocMap::new()),
12941291
tx_to_llvm_workers: Lock::new(tx),
12951292
output_filenames: Arc::new(output_filenames.clone()),
1296-
});
1297-
1298-
let gcx = arenas.global_ctxt.as_ref().unwrap();
1299-
1300-
let r = tls::enter_global(gcx, f);
1301-
1302-
gcx.queries.record_computed_queries(s);
1303-
1304-
r
1293+
}
13051294
}
13061295

13071296
pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
@@ -1985,31 +1974,29 @@ pub mod tls {
19851974
pub fn enter_global<'gcx, F, R>(gcx: &'gcx GlobalCtxt<'gcx>, f: F) -> R
19861975
where F: FnOnce(TyCtxt<'gcx, 'gcx, 'gcx>) -> R
19871976
{
1988-
with_thread_locals(|| {
1989-
// Update GCX_PTR to indicate there's a GlobalCtxt available
1990-
GCX_PTR.with(|lock| {
1991-
*lock.lock() = gcx as *const _ as usize;
1992-
});
1993-
// Set GCX_PTR back to 0 when we exit
1994-
let _on_drop = OnDrop(move || {
1995-
GCX_PTR.with(|lock| *lock.lock() = 0);
1996-
});
1977+
// Update GCX_PTR to indicate there's a GlobalCtxt available
1978+
GCX_PTR.with(|lock| {
1979+
*lock.lock() = gcx as *const _ as usize;
1980+
});
1981+
// Set GCX_PTR back to 0 when we exit
1982+
let _on_drop = OnDrop(move || {
1983+
GCX_PTR.with(|lock| *lock.lock() = 0);
1984+
});
19971985

1998-
let tcx = TyCtxt {
1999-
gcx,
2000-
interners: &gcx.global_interners,
2001-
dummy: PhantomData,
2002-
};
2003-
let icx = ImplicitCtxt {
2004-
tcx,
2005-
query: None,
2006-
diagnostics: None,
2007-
layout_depth: 0,
2008-
task_deps: None,
2009-
};
2010-
enter_context(&icx, |_| {
2011-
f(tcx)
2012-
})
1986+
let tcx = TyCtxt {
1987+
gcx,
1988+
interners: &gcx.global_interners,
1989+
dummy: PhantomData,
1990+
};
1991+
let icx = ImplicitCtxt {
1992+
tcx,
1993+
query: None,
1994+
diagnostics: None,
1995+
layout_depth: 0,
1996+
task_deps: None,
1997+
};
1998+
enter_context(&icx, |_| {
1999+
f(tcx)
20132000
})
20142001
}
20152002

src/librustc/ty/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ pub use self::binding::BindingMode;
7171
pub use self::binding::BindingMode::*;
7272

7373
pub use self::context::{TyCtxt, FreeRegionInfo, GlobalArenas, AllArenas, tls, keep_local};
74-
pub use self::context::{Lift, TypeckTables, CtxtInterners};
74+
pub use self::context::{Lift, TypeckTables, CtxtInterners, GlobalCtxt};
7575
pub use self::context::{
7676
UserTypeAnnotationIndex, UserType, CanonicalUserType,
7777
CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, ResolvedOpaqueTy,

src/librustc_codegen_llvm/lib.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,12 @@ use std::sync::{mpsc, Arc};
6363
use rustc::dep_graph::DepGraph;
6464
use rustc::middle::allocator::AllocatorKind;
6565
use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
66-
use rustc::session::{Session, CompileIncomplete};
66+
use rustc::session::Session;
6767
use rustc::session::config::{OutputFilenames, OutputType, PrintRequest, OptLevel};
6868
use rustc::ty::{self, TyCtxt};
6969
use rustc::util::time_graph;
7070
use rustc::util::profiling::ProfileCategory;
71+
use rustc::util::common::ErrorReported;
7172
use rustc_mir::monomorphize;
7273
use rustc_codegen_ssa::ModuleCodegen;
7374
use rustc_codegen_utils::codegen_backend::CodegenBackend;
@@ -311,7 +312,7 @@ impl CodegenBackend for LlvmCodegenBackend {
311312
sess: &Session,
312313
dep_graph: &DepGraph,
313314
outputs: &OutputFilenames,
314-
) -> Result<(), CompileIncomplete>{
315+
) -> Result<(), ErrorReported>{
315316
use rustc::util::common::time;
316317
let (codegen_results, work_products) =
317318
ongoing_codegen.downcast::

src/librustc_codegen_utils/codegen_backend.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ use flate2::write::DeflateEncoder;
2121

2222
use syntax::symbol::Symbol;
2323
use rustc::hir::def_id::LOCAL_CRATE;
24-
use rustc::session::{Session, CompileIncomplete};
24+
use rustc::session::Session;
25+
use rustc::util::common::ErrorReported;
2526
use rustc::session::config::{CrateType, OutputFilenames, PrintRequest};
2627
use rustc::ty::TyCtxt;
2728
use rustc::ty::query::Providers;
@@ -61,7 +62,7 @@ pub trait CodegenBackend {
6162
sess: &Session,
6263
dep_graph: &DepGraph,
6364
outputs: &OutputFilenames,
64-
) -> Result<(), CompileIncomplete>;
65+
) -> Result<(), ErrorReported>;
6566
}
6667

6768
pub struct NoLlvmMetadataLoader;
@@ -163,7 +164,7 @@ impl CodegenBackend for MetadataOnlyCodegenBackend {
163164
sess: &Session,
164165
_dep_graph: &DepGraph,
165166
outputs: &OutputFilenames,
166-
) -> Result<(), CompileIncomplete> {
167+
) -> Result<(), ErrorReported> {
167168
let ongoing_codegen = ongoing_codegen.downcast::<OngoingCodegen>()
168169
.expect("Expected MetadataOnlyCodegenBackend's OngoingCodegen, found Box<dyn Any>");
169170
for &crate_type in sess.opts.crate_types.iter() {

0 commit comments

Comments
 (0)