Skip to content

Commit

Permalink
move parse_cfgspecs to rustc_interface
Browse files Browse the repository at this point in the history
  • Loading branch information
Centril committed Oct 19, 2019
1 parent 9578272 commit d945f98
Show file tree
Hide file tree
Showing 9 changed files with 109 additions and 108 deletions.
1 change: 1 addition & 0 deletions Cargo.lock
Expand Up @@ -3556,6 +3556,7 @@ dependencies = [
"rustc_plugin_impl",
"rustc_privacy",
"rustc_resolve",
"rustc_target",
"rustc_traits",
"rustc_typeck",
"serialize",
Expand Down
65 changes: 2 additions & 63 deletions src/librustc/session/config.rs
Expand Up @@ -7,24 +7,19 @@ use crate::session::{early_error, early_warn, Session};
use crate::session::search_paths::SearchPath;

use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::Lrc;

use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
use rustc_target::spec::{Target, TargetTriple};

use syntax;
use syntax::ast::{self, IntTy, UintTy, MetaItemKind};
use syntax::ast::{self, IntTy, UintTy};
use syntax::source_map::{FileName, FilePathMapping};
use syntax::edition::{Edition, EDITION_NAME_LIST, DEFAULT_EDITION};
use syntax::parse::new_parser_from_source_str;
use syntax::parse::token;
use syntax::sess::ParseSess;
use syntax::symbol::{sym, Symbol};
use syntax::feature_gate::UnstableFeatures;
use syntax::source_map::SourceMap;

use errors::emitter::HumanReadableErrorType;
use errors::{ColorConfig, FatalError, Handler, SourceMapperDyn};
use errors::{ColorConfig, FatalError, Handler};

use getopts;

Expand Down Expand Up @@ -1854,59 +1849,6 @@ pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
opts
}

struct NullEmitter;

impl errors::emitter::Emitter for NullEmitter {
fn emit_diagnostic(&mut self, _: &errors::Diagnostic) {}
fn source_map(&self) -> Option<&Lrc<SourceMapperDyn>> { None }
}

// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
syntax::with_default_globals(move || {
let cfg = cfgspecs.into_iter().map(|s| {

let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let handler = Handler::with_emitter(false, None, Box::new(NullEmitter));
let sess = ParseSess::with_span_handler(handler, cm);
let filename = FileName::cfg_spec_source_code(&s);
let mut parser = new_parser_from_source_str(&sess, filename, s.to_string());

macro_rules! error {($reason: expr) => {
early_error(ErrorOutputType::default(),
&format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s));
}}

match &mut parser.parse_meta_item() {
Ok(meta_item) if parser.token == token::Eof => {
if meta_item.path.segments.len() != 1 {
error!("argument key must be an identifier");
}
match &meta_item.kind {
MetaItemKind::List(..) => {
error!(r#"expected `key` or `key="value"`"#);
}
MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
error!("argument value must be a string");
}
MetaItemKind::NameValue(..) | MetaItemKind::Word => {
let ident = meta_item.ident().expect("multi-segment cfg key");
return (ident.name, meta_item.value_str());
}
}
}
Ok(..) => {}
Err(err) => err.cancel(),
}

error!(r#"expected `key` or `key="value"`"#);
}).collect::<ast::CrateConfig>();
cfg.into_iter().map(|(a, b)| {
(a.to_string(), b.map(|b| b.to_string()))
}).collect()
})
}

pub fn get_cmd_lint_options(matches: &getopts::Matches,
error_format: ErrorOutputType)
-> (Vec<(String, lint::Level)>, bool, Option<lint::Level>) {
Expand Down Expand Up @@ -2877,6 +2819,3 @@ mod dep_tracking {
}
}
}

#[cfg(test)]
mod tests;
2 changes: 1 addition & 1 deletion src/librustc_driver/lib.rs
Expand Up @@ -167,7 +167,7 @@ pub fn run_compiler(
};

let sopts = config::build_session_options(&matches);
let cfg = config::parse_cfgspecs(matches.opt_strs("cfg"));
let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg"));

let mut dummy_config = |sopts, cfg, diagnostic_output| {
let mut config = interface::Config {
Expand Down
1 change: 1 addition & 0 deletions src/librustc_interface/Cargo.toml
Expand Up @@ -27,6 +27,7 @@ rustc_codegen_utils = { path = "../librustc_codegen_utils" }
rustc_metadata = { path = "../librustc_metadata" }
rustc_mir = { path = "../librustc_mir" }
rustc_passes = { path = "../librustc_passes" }
rustc_target = { path = "../librustc_target" }
rustc_typeck = { path = "../librustc_typeck" }
rustc_lint = { path = "../librustc_lint" }
rustc_errors = { path = "../librustc_errors" }
Expand Down
63 changes: 60 additions & 3 deletions src/librustc_interface/interface.rs
Expand Up @@ -3,7 +3,8 @@ use crate::util;
pub use crate::passes::BoxedResolver;

use rustc::lint;
use rustc::session::config::{self, Input};
use rustc::session::early_error;
use rustc::session::config::{self, Input, ErrorOutputType};
use rustc::session::{DiagnosticOutput, Session};
use rustc::util::common::ErrorReported;
use rustc_codegen_utils::codegen_backend::CodegenBackend;
Expand All @@ -14,9 +15,13 @@ use rustc_metadata::cstore::CStore;
use std::path::PathBuf;
use std::result;
use std::sync::{Arc, Mutex};
use syntax;
use syntax::source_map::{FileLoader, SourceMap};
use syntax::{self, parse};
use syntax::ast::{self, MetaItemKind};
use syntax::parse::token;
use syntax::source_map::{FileName, FilePathMapping, FileLoader, SourceMap};
use syntax::sess::ParseSess;
use syntax_pos::edition;
use rustc_errors::{Diagnostic, emitter::Emitter, Handler, SourceMapperDyn};

pub type Result<T> = result::Result<T, ErrorReported>;

Expand Down Expand Up @@ -60,6 +65,58 @@ impl Compiler {
}
}

/// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
struct NullEmitter;
impl Emitter for NullEmitter {
fn emit_diagnostic(&mut self, _: &Diagnostic) {}
fn source_map(&self) -> Option<&Lrc<SourceMapperDyn>> { None }
}

syntax::with_default_globals(move || {
let cfg = cfgspecs.into_iter().map(|s| {

let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let handler = Handler::with_emitter(false, None, Box::new(NullEmitter));
let sess = ParseSess::with_span_handler(handler, cm);
let filename = FileName::cfg_spec_source_code(&s);
let mut parser = parse::new_parser_from_source_str(&sess, filename, s.to_string());

macro_rules! error {($reason: expr) => {
early_error(ErrorOutputType::default(),
&format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s));
}}

match &mut parser.parse_meta_item() {
Ok(meta_item) if parser.token == token::Eof => {
if meta_item.path.segments.len() != 1 {
error!("argument key must be an identifier");
}
match &meta_item.kind {
MetaItemKind::List(..) => {
error!(r#"expected `key` or `key="value"`"#);
}
MetaItemKind::NameValue(lit) if !lit.kind.is_str() => {
error!("argument value must be a string");
}
MetaItemKind::NameValue(..) | MetaItemKind::Word => {
let ident = meta_item.ident().expect("multi-segment cfg key");
return (ident.name, meta_item.value_str());
}
}
}
Ok(..) => {}
Err(err) => err.cancel(),
}

error!(r#"expected `key` or `key="value"`"#);
}).collect::<ast::CrateConfig>();
cfg.into_iter().map(|(a, b)| {
(a.to_string(), b.map(|b| b.to_string()))
}).collect()
})
}

/// The compiler configuration
pub struct Config {
/// Command line options
Expand Down
3 changes: 3 additions & 0 deletions src/librustc_interface/lib.rs
Expand Up @@ -18,3 +18,6 @@ pub mod util;
mod proc_macro_decls;

pub use interface::{run_compiler, Config};

#[cfg(test)]
mod tests;
@@ -1,25 +1,24 @@
use getopts;
use crate::lint;
use crate::middle::cstore;
use crate::session::config::{
build_configuration,
build_session_options,
to_crate_config,
parse_cfgspecs,
};
use crate::session::config::{LtoCli, LinkerPluginLto, SwitchWithOptPath, ExternEntry};
use crate::session::build_session;
use crate::session::search_paths::SearchPath;
extern crate getopts;

use crate::interface::parse_cfgspecs;

use rustc::lint;
use rustc::middle::cstore;
use rustc::session::config::{build_configuration, build_session_options, to_crate_config};
use rustc::session::config::{LtoCli, LinkerPluginLto, SwitchWithOptPath, ExternEntry};
use rustc::session::config::{Externs, OutputType, OutputTypes, SymbolManglingVersion};
use rustc::session::config::{rustc_optgroups, Options, ErrorOutputType, Passes};
use rustc::session::build_session;
use rustc::session::search_paths::SearchPath;
use std::collections::{BTreeMap, BTreeSet};
use std::iter::FromIterator;
use std::path::PathBuf;
use super::{Externs, OutputType, OutputTypes, SymbolManglingVersion};
use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel};
use syntax::symbol::sym;
use syntax::edition::{Edition, DEFAULT_EDITION};
use syntax;
use super::Options;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{ColorConfig, emitter::HumanReadableErrorType, registry};

pub fn build_session_options_and_crate_config(
matches: &getopts::Matches,
Expand All @@ -30,22 +29,23 @@ pub fn build_session_options_and_crate_config(
)
}

impl ExternEntry {
fn new_public<S: Into<String>,
I: IntoIterator<Item = Option<S>>>(locations: I) -> ExternEntry {
let locations: BTreeSet<_> = locations.into_iter().map(|o| o.map(|s| s.into()))
.collect();

ExternEntry {
locations,
is_private_dep: false
}
fn new_public_extern_entry<S, I>(locations: I) -> ExternEntry
where
S: Into<String>,
I: IntoIterator<Item = Option<S>>,
{
let locations: BTreeSet<_> = locations.into_iter().map(|o| o.map(|s| s.into()))
.collect();

ExternEntry {
locations,
is_private_dep: false
}
}

fn optgroups() -> getopts::Options {
let mut opts = getopts::Options::new();
for group in super::rustc_optgroups() {
for group in rustc_optgroups() {
(group.apply)(&mut opts);
}
return opts;
Expand All @@ -63,7 +63,7 @@ fn test_switch_implies_cfg_test() {
Ok(m) => m,
Err(f) => panic!("test_switch_implies_cfg_test: {}", f),
};
let registry = errors::registry::Registry::new(&[]);
let registry = registry::Registry::new(&[]);
let (sessopts, cfg) = build_session_options_and_crate_config(matches);
let sess = build_session(sessopts, None, registry);
let cfg = build_configuration(&sess, to_crate_config(cfg));
Expand All @@ -81,7 +81,7 @@ fn test_switch_implies_cfg_test_unless_cfg_test() {
Ok(m) => m,
Err(f) => panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f),
};
let registry = errors::registry::Registry::new(&[]);
let registry = registry::Registry::new(&[]);
let (sessopts, cfg) = build_session_options_and_crate_config(matches);
let sess = build_session(sessopts, None, registry);
let cfg = build_configuration(&sess, to_crate_config(cfg));
Expand All @@ -95,7 +95,7 @@ fn test_switch_implies_cfg_test_unless_cfg_test() {
fn test_can_print_warnings() {
syntax::with_default_globals(|| {
let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
let registry = errors::registry::Registry::new(&[]);
let registry = registry::Registry::new(&[]);
let (sessopts, _) = build_session_options_and_crate_config(&matches);
let sess = build_session(sessopts, None, registry);
assert!(!sess.diagnostic().can_emit_warnings());
Expand All @@ -105,15 +105,15 @@ fn test_can_print_warnings() {
let matches = optgroups()
.parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()])
.unwrap();
let registry = errors::registry::Registry::new(&[]);
let registry = registry::Registry::new(&[]);
let (sessopts, _) = build_session_options_and_crate_config(&matches);
let sess = build_session(sessopts, None, registry);
assert!(sess.diagnostic().can_emit_warnings());
});

syntax::with_default_globals(|| {
let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
let registry = errors::registry::Registry::new(&[]);
let registry = registry::Registry::new(&[]);
let (sessopts, _) = build_session_options_and_crate_config(&matches);
let sess = build_session(sessopts, None, registry);
assert!(sess.diagnostic().can_emit_warnings());
Expand Down Expand Up @@ -172,33 +172,33 @@ fn test_externs_tracking_hash_different_construction_order() {
v1.externs = Externs::new(mk_map(vec![
(
String::from("a"),
ExternEntry::new_public(vec![Some("b"), Some("c")])
new_public_extern_entry(vec![Some("b"), Some("c")])
),
(
String::from("d"),
ExternEntry::new_public(vec![Some("e"), Some("f")])
new_public_extern_entry(vec![Some("e"), Some("f")])
),
]));

v2.externs = Externs::new(mk_map(vec![
(
String::from("d"),
ExternEntry::new_public(vec![Some("e"), Some("f")])
new_public_extern_entry(vec![Some("e"), Some("f")])
),
(
String::from("a"),
ExternEntry::new_public(vec![Some("b"), Some("c")])
new_public_extern_entry(vec![Some("b"), Some("c")])
),
]));

v3.externs = Externs::new(mk_map(vec![
(
String::from("a"),
ExternEntry::new_public(vec![Some("b"), Some("c")])
new_public_extern_entry(vec![Some("b"), Some("c")])
),
(
String::from("d"),
ExternEntry::new_public(vec![Some("f"), Some("e")])
new_public_extern_entry(vec![Some("f"), Some("e")])
),
]));

Expand Down Expand Up @@ -282,9 +282,9 @@ fn test_search_paths_tracking_hash_different_order() {
let mut v3 = Options::default();
let mut v4 = Options::default();

const JSON: super::ErrorOutputType = super::ErrorOutputType::Json {
const JSON: ErrorOutputType = ErrorOutputType::Json {
pretty: false,
json_rendered: super::HumanReadableErrorType::Default(super::ColorConfig::Never),
json_rendered: HumanReadableErrorType::Default(ColorConfig::Never),
};

// Reference
Expand Down Expand Up @@ -455,7 +455,7 @@ fn test_codegen_options_tracking_hash() {
opts.cg.codegen_units = Some(42);
assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

opts.cg.remark = super::Passes::Some(vec![String::from("pass1"), String::from("pass2")]);
opts.cg.remark = Passes::Some(vec![String::from("pass1"), String::from("pass2")]);
assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());

opts.cg.save_temps = true;
Expand Down
2 changes: 1 addition & 1 deletion src/librustdoc/core.rs
Expand Up @@ -329,7 +329,7 @@ pub fn run_core(options: RustdocOptions) -> (clean::Crate, RenderInfo, RenderOpt

let config = interface::Config {
opts: sessopts,
crate_cfg: config::parse_cfgspecs(cfgs),
crate_cfg: interface::parse_cfgspecs(cfgs),
input,
input_path: cpath,
output_file: None,
Expand Down

0 comments on commit d945f98

Please sign in to comment.