Move Session to librustc_session

This commit is contained in:
Mark Rousskov 2019-11-29 16:05:28 -05:00
parent 52d4d478a1
commit cc2c33a156
9 changed files with 86 additions and 64 deletions

View File

@ -3893,9 +3893,13 @@ name = "rustc_session"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"log", "log",
"num_cpus",
"rustc_data_structures", "rustc_data_structures",
"rustc_errors", "rustc_errors",
"rustc_feature",
"rustc_fs_util",
"rustc_index", "rustc_index",
"rustc_target",
"serialize", "serialize",
"syntax_pos", "syntax_pos",
] ]

View File

@ -64,7 +64,6 @@
#![recursion_limit="512"] #![recursion_limit="512"]
#[macro_use] extern crate bitflags; #[macro_use] extern crate bitflags;
extern crate getopts;
#[macro_use] extern crate scoped_tls; #[macro_use] extern crate scoped_tls;
#[cfg(windows)] #[cfg(windows)]
extern crate libc; extern crate libc;
@ -74,10 +73,6 @@ extern crate libc;
#[macro_use] extern crate syntax; #[macro_use] extern crate syntax;
#[macro_use] extern crate smallvec; #[macro_use] extern crate smallvec;
// Use the test crate here so we depend on getopts through it. This allow tools to link to both
// librustc_driver and libtest.
extern crate test as _;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
@ -113,7 +108,7 @@ pub mod middle {
} }
pub mod mir; pub mod mir;
pub mod session; pub use rustc_session as session;
pub mod traits; pub mod traits;
pub mod ty; pub mod ty;

View File

@ -11,7 +11,11 @@ path = "lib.rs"
[dependencies] [dependencies]
log = "0.4" log = "0.4"
rustc_errors = { path = "../librustc_errors" } rustc_errors = { path = "../librustc_errors" }
rustc_feature = { path = "../librustc_feature" }
rustc_target = { path = "../librustc_target" }
rustc_serialize = { path = "../libserialize", package = "serialize" } rustc_serialize = { path = "../libserialize", package = "serialize" }
rustc_data_structures = { path = "../librustc_data_structures" } rustc_data_structures = { path = "../librustc_data_structures" }
syntax_pos = { path = "../libsyntax_pos" } syntax_pos = { path = "../libsyntax_pos" }
rustc_index = { path = "../librustc_index" } rustc_index = { path = "../librustc_index" }
rustc_fs_util = { path = "../librustc_fs_util" }
num_cpus = "1.0"

View File

@ -1,13 +1,13 @@
//! Contains infrastructure for configuring the compiler, including parsing //! Contains infrastructure for configuring the compiler, including parsing
//! command-line options. //! command-line options.
use rustc_session::lint; use crate::lint;
use rustc_session::utils::NativeLibraryKind; use crate::utils::NativeLibraryKind;
use crate::session::{early_error, early_warn, Session}; use crate::{early_error, early_warn, Session};
use crate::session::search_paths::SearchPath; use crate::search_paths::SearchPath;
use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::fx::FxHashSet;
use rustc_feature::UnstableFeatures; use rustc_data_structures::impl_stable_hash_via_hash;
use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel}; use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
use rustc_target::spec::{Target, TargetTriple}; use rustc_target::spec::{Target, TargetTriple};
@ -15,12 +15,13 @@ use rustc_target::spec::{Target, TargetTriple};
// Duplicated from syntax::ast for now // Duplicated from syntax::ast for now
type CrateConfig = FxHashSet<(Symbol, Option<Symbol>)>; type CrateConfig = FxHashSet<(Symbol, Option<Symbol>)>;
use syntax::source_map::{FileName, FilePathMapping}; use syntax_pos::source_map::{FileName, FilePathMapping};
use syntax::edition::{Edition, EDITION_NAME_LIST, DEFAULT_EDITION}; use syntax_pos::edition::{Edition, EDITION_NAME_LIST, DEFAULT_EDITION};
use syntax::symbol::{sym, Symbol}; use syntax_pos::symbol::{sym, Symbol};
use rustc_feature::UnstableFeatures;
use errors::emitter::HumanReadableErrorType; use rustc_errors::emitter::HumanReadableErrorType;
use errors::{ColorConfig, FatalError, Handler}; use rustc_errors::{ColorConfig, FatalError, Handler};
use getopts; use getopts;
@ -349,7 +350,7 @@ macro_rules! hash_option {
($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({ ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({
if $sub_hashes.insert(stringify!($opt_name), if $sub_hashes.insert(stringify!($opt_name),
$opt_expr as &dyn dep_tracking::DepTrackingHash).is_some() { $opt_expr as &dyn dep_tracking::DepTrackingHash).is_some() {
bug!("duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name)) panic!("duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
} }
}); });
} }
@ -702,7 +703,7 @@ pub enum EntryFnType {
impl_stable_hash_via_hash!(EntryFnType); impl_stable_hash_via_hash!(EntryFnType);
#[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug, HashStable)] #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
pub enum CrateType { pub enum CrateType {
Executable, Executable,
Dylib, Dylib,
@ -712,6 +713,8 @@ pub enum CrateType {
ProcMacro, ProcMacro,
} }
impl_stable_hash_via_hash!(CrateType);
#[derive(Clone, Hash)] #[derive(Clone, Hash)]
pub enum Passes { pub enum Passes {
Some(Vec<String>), Some(Vec<String>),
@ -782,7 +785,7 @@ macro_rules! options {
value, $outputname, value, $outputname,
key, type_desc)) key, type_desc))
} }
(None, None) => bug!() (None, None) => panic!()
} }
} }
found = true; found = true;
@ -2720,7 +2723,7 @@ pub mod nightly_options {
use getopts; use getopts;
use rustc_feature::UnstableFeatures; use rustc_feature::UnstableFeatures;
use super::{ErrorOutputType, OptionStability, RustcOptGroup}; use super::{ErrorOutputType, OptionStability, RustcOptGroup};
use crate::session::early_error; use crate::early_error;
pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool { pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
is_nightly_build() is_nightly_build()
@ -2858,8 +2861,8 @@ impl PpMode {
/// we have an opt-in scheme here, so one is hopefully forced to think about /// we have an opt-in scheme here, so one is hopefully forced to think about
/// how the hash should be calculated when adding a new command-line argument. /// how the hash should be calculated when adding a new command-line argument.
mod dep_tracking { mod dep_tracking {
use rustc_session::lint; use crate::lint;
use rustc_session::utils::NativeLibraryKind; use crate::utils::NativeLibraryKind;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::hash::Hash; use std::hash::Hash;
use std::path::PathBuf; use std::path::PathBuf;
@ -2867,9 +2870,9 @@ mod dep_tracking {
use super::{CrateType, DebugInfo, ErrorOutputType, OptLevel, OutputTypes, use super::{CrateType, DebugInfo, ErrorOutputType, OptLevel, OutputTypes,
Passes, Sanitizer, LtoCli, LinkerPluginLto, SwitchWithOptPath, Passes, Sanitizer, LtoCli, LinkerPluginLto, SwitchWithOptPath,
SymbolManglingVersion}; SymbolManglingVersion};
use rustc_feature::UnstableFeatures;
use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel, TargetTriple}; use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel, TargetTriple};
use syntax::edition::Edition; use syntax_pos::edition::Edition;
use rustc_feature::UnstableFeatures;
pub trait DepTrackingHash { pub trait DepTrackingHash {
fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType); fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);

View File

@ -7,8 +7,9 @@ use std::env;
use std::fs; use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use crate::session::search_paths::{SearchPath, PathKind}; use crate::search_paths::{SearchPath, PathKind};
use rustc_fs_util::fix_windows_verbatim_for_gcc; use rustc_fs_util::fix_windows_verbatim_for_gcc;
use log::debug;
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub enum FileMatch { pub enum FileMatch {
@ -124,7 +125,7 @@ pub fn get_or_default_sysroot() -> PathBuf {
// gcc chokes on verbatim paths which fs::canonicalize generates // gcc chokes on verbatim paths which fs::canonicalize generates
// so we try to avoid those kinds of paths. // so we try to avoid those kinds of paths.
Ok(canon) => Some(fix_windows_verbatim_for_gcc(&canon)), Ok(canon) => Some(fix_windows_verbatim_for_gcc(&canon)),
Err(e) => bug!("failed to get realpath: {}", e), Err(e) => panic!("failed to get realpath: {}", e),
} }
}) })
} }
@ -133,7 +134,7 @@ pub fn get_or_default_sysroot() -> PathBuf {
Ok(exe) => { Ok(exe) => {
match canonicalize(Some(exe)) { match canonicalize(Some(exe)) {
Some(mut p) => { p.pop(); p.pop(); p }, Some(mut p) => { p.pop(); p.pop(); p },
None => bug!("can't determine value for sysroot") None => panic!("can't determine value for sysroot")
} }
} }
Err(ref e) => panic!(format!("failed to get current_exe: {}", e)) Err(ref e) => panic!(format!("failed to get current_exe: {}", e))

View File

@ -1,6 +1,21 @@
#![feature(test)]
// Use the test crate here so we depend on getopts through it. This allow tools to link to both
// librustc_session and libtest.
extern crate test as _;
extern crate getopts;
pub mod cgu_reuse_tracker; pub mod cgu_reuse_tracker;
pub mod utils; pub mod utils;
#[macro_use] #[macro_use]
pub mod lint; pub mod lint;
pub mod node_id; pub mod node_id;
pub mod parse; pub mod parse;
mod code_stats;
pub mod config;
pub mod filesearch;
pub mod search_paths;
mod session;
pub use session::*;

View File

@ -1,6 +1,6 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use crate::session::{early_error, config}; use crate::{early_error, config};
use crate::session::filesearch::make_target_lib_path; use crate::filesearch::make_target_lib_path;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct SearchPath { pub struct SearchPath {
@ -9,7 +9,7 @@ pub struct SearchPath {
pub files: Vec<PathBuf>, pub files: Vec<PathBuf>,
} }
#[derive(PartialEq, Clone, Copy, Debug, HashStable)] #[derive(PartialEq, Clone, Copy, Debug, Hash, Eq)]
pub enum PathKind { pub enum PathKind {
Native, Native,
Crate, Crate,
@ -19,6 +19,8 @@ pub enum PathKind {
All, All,
} }
rustc_data_structures::impl_stable_hash_via_hash!(PathKind);
impl PathKind { impl PathKind {
pub fn matches(&self, kind: PathKind) -> bool { pub fn matches(&self, kind: PathKind) -> bool {
match (self, kind) { match (self, kind) {

View File

@ -1,29 +1,32 @@
pub use self::code_stats::{DataTypeKind, SizeKind, FieldInfo, VariantInfo}; pub use crate::code_stats::{DataTypeKind, SizeKind, FieldInfo, VariantInfo};
use self::code_stats::CodeStats; use crate::code_stats::CodeStats;
use rustc_session::cgu_reuse_tracker::CguReuseTracker; use crate::cgu_reuse_tracker::CguReuseTracker;
use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fingerprint::Fingerprint;
use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_session::lint; use crate::lint;
use crate::session::config::{OutputType, PrintRequest, Sanitizer, SwitchWithOptPath}; use crate::filesearch;
use crate::session::search_paths::{PathKind, SearchPath}; use crate::config::{self, OutputType, PrintRequest, Sanitizer, SwitchWithOptPath};
use crate::util::common::{duration_to_secs_str, ErrorReported}; use crate::search_paths::{PathKind, SearchPath};
use crate::utils::duration_to_secs_str;
use rustc_errors::ErrorReported;
use rustc_data_structures::base_n; use rustc_data_structures::base_n;
use rustc_data_structures::sync::{ use rustc_data_structures::sync::{
self, Lrc, Lock, OneThread, Once, AtomicU64, AtomicUsize, Ordering, self, Lrc, Lock, OneThread, Once, AtomicU64, AtomicUsize, Ordering,
Ordering::SeqCst, Ordering::SeqCst,
}; };
use rustc_data_structures::impl_stable_hash_via_hash;
use errors::{DiagnosticBuilder, DiagnosticId, Applicability}; use rustc_errors::{DiagnosticBuilder, DiagnosticId, Applicability};
use errors::emitter::{Emitter, EmitterWriter}; use rustc_errors::emitter::{Emitter, EmitterWriter};
use errors::emitter::HumanReadableErrorType; use rustc_errors::emitter::HumanReadableErrorType;
use errors::annotate_snippet_emitter_writer::{AnnotateSnippetEmitterWriter}; use rustc_errors::annotate_snippet_emitter_writer::{AnnotateSnippetEmitterWriter};
use syntax::edition::Edition; use syntax_pos::edition::Edition;
use errors::json::JsonEmitter; use rustc_errors::json::JsonEmitter;
use syntax::source_map; use syntax_pos::source_map;
use syntax::sess::ParseSess; use crate::parse::ParseSess;
use syntax_pos::{MultiSpan, Span}; use syntax_pos::{MultiSpan, Span};
use rustc_target::spec::{PanicStrategy, RelroLevel, Target, TargetTriple}; use rustc_target::spec::{PanicStrategy, RelroLevel, Target, TargetTriple};
@ -41,11 +44,6 @@ use std::path::PathBuf;
use std::time::Duration; use std::time::Duration;
use std::sync::Arc; use std::sync::Arc;
mod code_stats;
pub mod config;
pub mod filesearch;
pub mod search_paths;
pub struct OptimizationFuel { pub struct OptimizationFuel {
/// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`. /// If `-zfuel=crate=n` is specified, initially set to `n`, otherwise `0`.
remaining: u64, remaining: u64,
@ -334,7 +332,7 @@ impl Session {
self.diagnostic().span_note_without_error(sp, msg) self.diagnostic().span_note_without_error(sp, msg)
} }
pub fn diagnostic(&self) -> &errors::Handler { pub fn diagnostic(&self) -> &rustc_errors::Handler {
&self.parse_sess.span_diagnostic &self.parse_sess.span_diagnostic
} }
@ -679,7 +677,7 @@ impl Session {
if let IncrCompSession::NotInitialized = *incr_comp_session { if let IncrCompSession::NotInitialized = *incr_comp_session {
} else { } else {
bug!( panic!(
"Trying to initialize IncrCompSession `{:?}`", "Trying to initialize IncrCompSession `{:?}`",
*incr_comp_session *incr_comp_session
) )
@ -697,7 +695,7 @@ impl Session {
if let IncrCompSession::Active { .. } = *incr_comp_session { if let IncrCompSession::Active { .. } = *incr_comp_session {
} else { } else {
bug!( panic!(
"trying to finalize `IncrCompSession` `{:?}`", "trying to finalize `IncrCompSession` `{:?}`",
*incr_comp_session *incr_comp_session
); );
@ -718,7 +716,7 @@ impl Session {
.. ..
} => session_directory.clone(), } => session_directory.clone(),
IncrCompSession::InvalidBecauseOfErrors { .. } => return, IncrCompSession::InvalidBecauseOfErrors { .. } => return,
_ => bug!( _ => panic!(
"trying to invalidate `IncrCompSession` `{:?}`", "trying to invalidate `IncrCompSession` `{:?}`",
*incr_comp_session *incr_comp_session
), ),
@ -735,7 +733,7 @@ impl Session {
cell::Ref::map( cell::Ref::map(
incr_comp_session, incr_comp_session,
|incr_comp_session| match *incr_comp_session { |incr_comp_session| match *incr_comp_session {
IncrCompSession::NotInitialized => bug!( IncrCompSession::NotInitialized => panic!(
"trying to get session directory from `IncrCompSession`: {:?}", "trying to get session directory from `IncrCompSession`: {:?}",
*incr_comp_session, *incr_comp_session,
), ),
@ -915,7 +913,7 @@ impl Session {
pub fn build_session( pub fn build_session(
sopts: config::Options, sopts: config::Options,
local_crate_source_file: Option<PathBuf>, local_crate_source_file: Option<PathBuf>,
registry: errors::registry::Registry, registry: rustc_errors::registry::Registry,
) -> Session { ) -> Session {
let file_path_mapping = sopts.file_path_mapping(); let file_path_mapping = sopts.file_path_mapping();
@ -931,7 +929,7 @@ pub fn build_session(
fn default_emitter( fn default_emitter(
sopts: &config::Options, sopts: &config::Options,
registry: errors::registry::Registry, registry: rustc_errors::registry::Registry,
source_map: &Lrc<source_map::SourceMap>, source_map: &Lrc<source_map::SourceMap>,
emitter_dest: Option<Box<dyn Write + Send>>, emitter_dest: Option<Box<dyn Write + Send>>,
) -> Box<dyn Emitter + sync::Send> { ) -> Box<dyn Emitter + sync::Send> {
@ -1000,7 +998,7 @@ pub enum DiagnosticOutput {
pub fn build_session_with_source_map( pub fn build_session_with_source_map(
sopts: config::Options, sopts: config::Options,
local_crate_source_file: Option<PathBuf>, local_crate_source_file: Option<PathBuf>,
registry: errors::registry::Registry, registry: rustc_errors::registry::Registry,
source_map: Lrc<source_map::SourceMap>, source_map: Lrc<source_map::SourceMap>,
diagnostics_output: DiagnosticOutput, diagnostics_output: DiagnosticOutput,
lint_caps: FxHashMap<lint::LintId, lint::Level>, lint_caps: FxHashMap<lint::LintId, lint::Level>,
@ -1031,9 +1029,9 @@ pub fn build_session_with_source_map(
}; };
let emitter = default_emitter(&sopts, registry, &source_map, write_dest); let emitter = default_emitter(&sopts, registry, &source_map, write_dest);
let diagnostic_handler = errors::Handler::with_emitter_and_flags( let diagnostic_handler = rustc_errors::Handler::with_emitter_and_flags(
emitter, emitter,
errors::HandlerFlags { rustc_errors::HandlerFlags {
can_emit_warnings, can_emit_warnings,
treat_err_as_bug, treat_err_as_bug,
report_delayed_bugs, report_delayed_bugs,
@ -1055,7 +1053,7 @@ pub fn build_session_with_source_map(
fn build_session_( fn build_session_(
sopts: config::Options, sopts: config::Options,
local_crate_source_file: Option<PathBuf>, local_crate_source_file: Option<PathBuf>,
span_diagnostic: errors::Handler, span_diagnostic: rustc_errors::Handler,
source_map: Lrc<source_map::SourceMap>, source_map: Lrc<source_map::SourceMap>,
driver_lint_caps: FxHashMap<lint::LintId, lint::Level>, driver_lint_caps: FxHashMap<lint::LintId, lint::Level>,
) -> Session { ) -> Session {
@ -1280,9 +1278,9 @@ pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
config::ErrorOutputType::Json { pretty, json_rendered } => config::ErrorOutputType::Json { pretty, json_rendered } =>
Box::new(JsonEmitter::basic(pretty, json_rendered, false)), Box::new(JsonEmitter::basic(pretty, json_rendered, false)),
}; };
let handler = errors::Handler::with_emitter(true, None, emitter); let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
handler.struct_fatal(msg).emit(); handler.struct_fatal(msg).emit();
errors::FatalError.raise(); rustc_errors::FatalError.raise();
} }
pub fn early_warn(output: config::ErrorOutputType, msg: &str) { pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
@ -1294,7 +1292,7 @@ pub fn early_warn(output: config::ErrorOutputType, msg: &str) {
config::ErrorOutputType::Json { pretty, json_rendered } => config::ErrorOutputType::Json { pretty, json_rendered } =>
Box::new(JsonEmitter::basic(pretty, json_rendered, false)), Box::new(JsonEmitter::basic(pretty, json_rendered, false)),
}; };
let handler = errors::Handler::with_emitter(true, None, emitter); let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
handler.struct_warn(msg).emit(); handler.struct_warn(msg).emit();
} }