use middle::cstore;
use syntax::ast::{self, IntTy, UintTy};
-use syntax::codemap::{FilePathMapping, FileName};
+use syntax::codemap::{FileName, FilePathMapping};
use syntax::parse::token;
use syntax::parse;
use syntax::symbol::Symbol;
#[derive(Clone, Copy, PartialEq, Hash)]
pub enum OptLevel {
- No, // -O0
- Less, // -O1
- Default, // -O2
+ No, // -O0
+ Less, // -O1
+ Default, // -O2
Aggressive, // -O3
- Size, // -Os
- SizeMin, // -Oz
+ Size, // -Os
+ SizeMin, // -Oz
}
#[derive(Clone, Copy, PartialEq, Hash)]
FullDebugInfo,
}
-#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord,
- RustcEncodable, RustcDecodable)]
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
pub enum OutputType {
Bitcode,
Assembly,
#[non_exhaustive]
pub enum Epoch {
// epochs must be kept in order, newest to oldest
-
/// The 2015 epoch
Epoch2015,
/// The 2018 epoch
Epoch2018,
-
// when adding new epochs, be sure to update:
//
// - the list in the `parse_epoch` static
match s {
"2015" => Ok(Epoch::Epoch2015),
"2018" => Ok(Epoch::Epoch2018),
- _ => Err(())
+ _ => Err(()),
}
}
}
impl OutputType {
fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
match *self {
- OutputType::Exe |
- OutputType::DepInfo => true,
- OutputType::Bitcode |
- OutputType::Assembly |
- OutputType::LlvmAssembly |
- OutputType::Mir |
- OutputType::Object |
- OutputType::Metadata => false,
+ OutputType::Exe | OutputType::DepInfo => true,
+ OutputType::Bitcode
+ | OutputType::Assembly
+ | OutputType::LlvmAssembly
+ | OutputType::Mir
+ | OutputType::Object
+ | OutputType::Metadata => false,
}
}
fn from_shorthand(shorthand: &str) -> Option<Self> {
Some(match shorthand {
- "asm" => OutputType::Assembly,
- "llvm-ir" => OutputType::LlvmAssembly,
- "mir" => OutputType::Mir,
- "llvm-bc" => OutputType::Bitcode,
- "obj" => OutputType::Object,
- "metadata" => OutputType::Metadata,
- "link" => OutputType::Exe,
- "dep-info" => OutputType::DepInfo,
+ "asm" => OutputType::Assembly,
+ "llvm-ir" => OutputType::LlvmAssembly,
+ "mir" => OutputType::Mir,
+ "llvm-bc" => OutputType::Bitcode,
+ "obj" => OutputType::Object,
+ "metadata" => OutputType::Metadata,
+ "link" => OutputType::Exe,
+ "dep-info" => OutputType::DepInfo,
_ => return None,
})
}
impl OutputTypes {
pub fn new(entries: &[(OutputType, Option<PathBuf>)]) -> OutputTypes {
- OutputTypes(BTreeMap::from_iter(entries.iter()
- .map(|&(k, ref v)| (k, v.clone()))))
+ OutputTypes(BTreeMap::from_iter(
+ entries.iter().map(|&(k, ref v)| (k, v.clone())),
+ ))
}
pub fn get(&self, key: &OutputType) -> Option<&Option<PathBuf>> {
// True if any of the output types require codegen or linking.
pub fn should_trans(&self) -> bool {
self.0.keys().any(|k| match *k {
- OutputType::Bitcode |
- OutputType::Assembly |
- OutputType::LlvmAssembly |
- OutputType::Mir |
- OutputType::Object |
- OutputType::Exe => true,
- OutputType::Metadata |
- OutputType::DepInfo => false,
+ OutputType::Bitcode
+ | OutputType::Assembly
+ | OutputType::LlvmAssembly
+ | OutputType::Mir
+ | OutputType::Object
+ | OutputType::Exe => true,
+ OutputType::Metadata | OutputType::DepInfo => false,
})
}
}
-
// Use tree-based collections to cheaply get a deterministic Hash implementation.
// DO NOT switch BTreeMap or BTreeSet out for an unsorted container type! That
// would break dependency tracking for commandline arguments.
impl Input {
pub fn filestem(&self) -> String {
match *self {
- Input::File(ref ifile) => ifile.file_stem().unwrap()
- .to_str().unwrap().to_string(),
+ Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap().to_string(),
Input::Str { .. } => "rust_out".to_string(),
}
}
impl OutputFilenames {
pub fn path(&self, flavor: OutputType) -> PathBuf {
- self.outputs.get(&flavor).and_then(|p| p.to_owned())
+ self.outputs
+ .get(&flavor)
+ .and_then(|p| p.to_owned())
.or_else(|| self.single_output_file.clone())
.unwrap_or_else(|| self.temp_path(flavor, None))
}
/// Get the path where a compilation artifact of the given type for the
/// given codegen unit should be placed on disk. If codegen_unit_name is
/// None, a path distinct from those of any codegen unit will be generated.
- pub fn temp_path(&self,
- flavor: OutputType,
- codegen_unit_name: Option<&str>)
- -> PathBuf {
+ pub fn temp_path(&self, flavor: OutputType, codegen_unit_name: Option<&str>) -> PathBuf {
let extension = flavor.extension();
self.temp_path_ext(extension, codegen_unit_name)
}
/// Like temp_path, but also supports things where there is no corresponding
/// OutputType, like no-opt-bitcode or lto-bitcode.
- pub fn temp_path_ext(&self,
- ext: &str,
- codegen_unit_name: Option<&str>)
- -> PathBuf {
+ pub fn temp_path_ext(&self, ext: &str, codegen_unit_name: Option<&str>) -> PathBuf {
let base = self.out_directory.join(&self.filestem());
let mut extension = String::new();
}
pub fn with_extension(&self, extension: &str) -> PathBuf {
- self.out_directory.join(&self.filestem()).with_extension(extension)
+ self.out_directory
+ .join(&self.filestem())
+ .with_extension(extension)
}
pub fn filestem(&self) -> String {
// Instead of grabbing the host triple (for the current host), we grab (at
// compile time) the target triple that this rustc is built with and
// calling that (at runtime) the host triple.
- (option_env!("CFG_COMPILER_HOST_TRIPLE")).
- expect("CFG_COMPILER_HOST_TRIPLE")
+ (option_env!("CFG_COMPILER_HOST_TRIPLE")).expect("CFG_COMPILER_HOST_TRIPLE")
}
/// Some reasonable defaults
impl Options {
/// True if there is a reason to build the dep graph.
pub fn build_dep_graph(&self) -> bool {
- self.incremental.is_some() ||
- self.debugging_opts.dump_dep_graph ||
- self.debugging_opts.query_dep_graph
+ self.incremental.is_some() || self.debugging_opts.dump_dep_graph
+ || self.debugging_opts.query_dep_graph
}
#[inline(always)]
pub fn enable_dep_node_debug_strs(&self) -> bool {
- cfg!(debug_assertions) &&
- (self.debugging_opts.query_dep_graph || self.debugging_opts.incremental_info)
+ cfg!(debug_assertions)
+ && (self.debugging_opts.query_dep_graph || self.debugging_opts.incremental_info)
}
pub fn file_path_mapping(&self) -> FilePathMapping {
}
ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
- ret.insert((Symbol::intern("target_pointer_width"), Some(Symbol::intern(wordsz))));
+ ret.insert((
+ Symbol::intern("target_pointer_width"),
+ Some(Symbol::intern(wordsz)),
+ ));
ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
- ret.insert((Symbol::intern("target_vendor"), Some(Symbol::intern(vendor))));
+ ret.insert((
+ Symbol::intern("target_vendor"),
+ Some(Symbol::intern(vendor)),
+ ));
if sess.target.target.options.has_elf_tls {
ret.insert((Symbol::intern("target_thread_local"), None));
}
for &i in &[8, 16, 32, 64, 128] {
if i >= min_atomic_width && i <= max_atomic_width {
let s = i.to_string();
- ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern(&s))));
+ ret.insert((
+ Symbol::intern("target_has_atomic"),
+ Some(Symbol::intern(&s)),
+ ));
if &s == wordsz {
- ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern("ptr"))));
+ ret.insert((
+ Symbol::intern("target_has_atomic"),
+ Some(Symbol::intern("ptr")),
+ ));
}
}
}
return ret;
}
-pub fn build_configuration(sess: &Session,
- mut user_cfg: ast::CrateConfig)
- -> ast::CrateConfig {
+pub fn build_configuration(sess: &Session, mut user_cfg: ast::CrateConfig) -> ast::CrateConfig {
// Combine the configuration requested by the session (command line) with
// some default and generated configuration items
let default_cfg = default_configuration(sess);
"16" => (ast::IntTy::I16, ast::UintTy::U16),
"32" => (ast::IntTy::I32, ast::UintTy::U32),
"64" => (ast::IntTy::I64, ast::UintTy::U64),
- w => sp.fatal(&format!("target specification was invalid: \
- unrecognized target-pointer-width {}", w)).raise(),
+ w => sp.fatal(&format!(
+ "target specification was invalid: \
+ unrecognized target-pointer-width {}",
+ w
+ )).raise(),
};
Config {
}
pub fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
- where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
+ where
+ F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
{
RustcOptGroup {
name,
}
pub fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
- where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
+ where
+ F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
{
RustcOptGroup {
name,
pub type S = &'static str;
fn stable<F>(name: S, f: F) -> R
- where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
+ where
+ F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
{
RustcOptGroup::stable(name, f)
}
fn unstable<F>(name: S, f: F) -> R
- where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
+ where
+ F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
{
RustcOptGroup::unstable(name, f)
}
vec![
opt::flag_s("h", "help", "Display this message"),
opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
- opt::multi_s("L", "", "Add a directory to the library search path. The
+ opt::multi_s(
+ "L",
+ "",
+ "Add a directory to the library search path. The
optional KIND can be one of dependency, crate, native,
- framework or all (the default).", "[KIND=]PATH"),
- opt::multi_s("l", "", "Link the generated crate(s) to the specified native
+ framework or all (the default).",
+ "[KIND=]PATH",
+ ),
+ opt::multi_s(
+ "l",
+ "",
+ "Link the generated crate(s) to the specified native
library NAME. The optional KIND can be one of
static, dylib, or framework. If omitted, dylib is
- assumed.", "[KIND=]NAME"),
- opt::multi_s("", "crate-type", "Comma separated list of types of crates
+ assumed.",
+ "[KIND=]NAME",
+ ),
+ opt::multi_s(
+ "",
+ "crate-type",
+ "Comma separated list of types of crates
for the compiler to emit",
- "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]"),
- opt::opt_s("", "crate-name", "Specify the name of the crate being built",
- "NAME"),
- opt::multi_s("", "emit", "Comma separated list of types of output for \
- the compiler to emit",
- "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]"),
- opt::multi_s("", "print", "Comma separated list of compiler information to \
- print on stdout",
- "[crate-name|file-names|sysroot|cfg|target-list|\
- target-cpus|target-features|relocation-models|\
- code-models|tls-models|target-spec-json|native-static-libs]"),
- opt::flagmulti_s("g", "", "Equivalent to -C debuginfo=2"),
+ "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]",
+ ),
+ opt::opt_s(
+ "",
+ "crate-name",
+ "Specify the name of the crate being built",
+ "NAME",
+ ),
+ opt::multi_s(
+ "",
+ "emit",
+ "Comma separated list of types of output for \
+ the compiler to emit",
+ "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]",
+ ),
+ opt::multi_s(
+ "",
+ "print",
+ "Comma separated list of compiler information to \
+ print on stdout",
+ "[crate-name|file-names|sysroot|cfg|target-list|\
+ target-cpus|target-features|relocation-models|\
+ code-models|tls-models|target-spec-json|native-static-libs]",
+ ),
+ opt::flagmulti_s("g", "", "Equivalent to -C debuginfo=2"),
opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
- opt::opt_s("", "out-dir", "Write output to compiler-chosen filename \
- in <dir>", "DIR"),
- opt::opt_s("", "explain", "Provide a detailed explanation of an error \
- message", "OPT"),
+ opt::opt_s(
+ "",
+ "out-dir",
+ "Write output to compiler-chosen filename \
+ in <dir>",
+ "DIR",
+ ),
+ opt::opt_s(
+ "",
+ "explain",
+ "Provide a detailed explanation of an error \
+ message",
+ "OPT",
+ ),
opt::flag_s("", "test", "Build a test harness"),
- opt::opt_s("", "target", "Target triple for which the code is compiled", "TARGET"),
+ opt::opt_s(
+ "",
+ "target",
+ "Target triple for which the code is compiled",
+ "TARGET",
+ ),
opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
opt::multi_s("D", "deny", "Set lint denied", "OPT"),
opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
- opt::multi_s("", "cap-lints", "Set the most restrictive lint level. \
- More restrictive lints are capped at this \
- level", "LEVEL"),
+ opt::multi_s(
+ "",
+ "cap-lints",
+ "Set the most restrictive lint level. \
+ More restrictive lints are capped at this \
+ level",
+ "LEVEL",
+ ),
opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
opt::flag_s("V", "version", "Print version info and exit"),
opt::flag_s("v", "verbose", "Use verbose output"),
pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
let mut opts = rustc_short_optgroups();
opts.extend(vec![
- opt::multi_s("", "extern", "Specify where an external rust library is located",
- "NAME=PATH"),
+ opt::multi_s(
+ "",
+ "extern",
+ "Specify where an external rust library is located",
+ "NAME=PATH",
+ ),
opt::opt_s("", "sysroot", "Override the system root", "PATH"),
opt::multi("Z", "", "Set internal debugging options", "FLAG"),
- opt::opt_s("", "error-format",
- "How errors and other messages are produced",
- "human|json|short"),
- opt::opt_s("", "color", "Configure coloring of output:
+ opt::opt_s(
+ "",
+ "error-format",
+ "How errors and other messages are produced",
+ "human|json|short",
+ ),
+ opt::opt_s(
+ "",
+ "color",
+ "Configure coloring of output:
auto = colorize, if output goes to a tty (default);
always = always colorize output;
- never = never colorize output", "auto|always|never"),
-
- opt::opt("", "pretty",
- "Pretty-print the input instead of compiling;
+ never = never colorize output",
+ "auto|always|never",
+ ),
+ opt::opt(
+ "",
+ "pretty",
+ "Pretty-print the input instead of compiling;
valid types are: `normal` (un-annotated source),
`expanded` (crates expanded), or
`expanded,identified` (fully parenthesized, AST nodes with IDs).",
- "TYPE"),
- opt::multi_s("", "remap-path-prefix", "remap source names in output", "FROM=TO"),
+ "TYPE",
+ ),
+ opt::multi_s(
+ "",
+ "remap-path-prefix",
+ "remap source names in output",
+ "FROM=TO",
+ ),
]);
opts
}
// Convert strings provided as --cfg [cfgspec] into a crate_cfg
-pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
- cfgspecs.into_iter().map(|s| {
- let sess = parse::ParseSess::new(FilePathMapping::empty());
- let mut parser =
- parse::new_parser_from_source_str(&sess, FileName::CfgSpec, s.to_string());
-
- let meta_item = panictry!(parser.parse_meta_item());
-
- if parser.token != token::Eof {
- early_error(ErrorOutputType::default(), &format!("invalid --cfg argument: {}", s))
- } else if meta_item.is_meta_item_list() {
- let msg =
- format!("invalid predicate in --cfg command line argument: `{}`", meta_item.name());
- early_error(ErrorOutputType::default(), &msg)
- }
+pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> ast::CrateConfig {
+ cfgspecs
+ .into_iter()
+ .map(|s| {
+ let sess = parse::ParseSess::new(FilePathMapping::empty());
+ let mut parser =
+ parse::new_parser_from_source_str(&sess, FileName::CfgSpec, s.to_string());
+
+ let meta_item = panictry!(parser.parse_meta_item());
+
+ if parser.token != token::Eof {
+ early_error(
+ ErrorOutputType::default(),
+ &format!("invalid --cfg argument: {}", s),
+ )
+ } else if meta_item.is_meta_item_list() {
+ let msg = format!(
+ "invalid predicate in --cfg command line argument: `{}`",
+ meta_item.name()
+ );
+ early_error(ErrorOutputType::default(), &msg)
+ }
- (meta_item.name(), meta_item.value_str())
- }).collect::<ast::CrateConfig>()
+ (meta_item.name(), meta_item.value_str())
+ })
+ .collect::<ast::CrateConfig>()
}
-pub fn build_session_options_and_crate_config(matches: &getopts::Matches)
- -> (Options, ast::CrateConfig) {
+pub fn build_session_options_and_crate_config(
+ matches: &getopts::Matches,
+) -> (Options, ast::CrateConfig) {
let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
- Some("auto") => ColorConfig::Auto,
+ Some("auto") => ColorConfig::Auto,
Some("always") => ColorConfig::Always,
- Some("never") => ColorConfig::Never,
+ Some("never") => ColorConfig::Never,
None => ColorConfig::Auto,
- Some(arg) => {
- early_error(ErrorOutputType::default(), &format!("argument for --color must be auto, \
- always or never (instead was `{}`)",
- arg))
- }
+ Some(arg) => early_error(
+ ErrorOutputType::default(),
+ &format!(
+ "argument for --color must be auto, \
+ always or never (instead was `{}`)",
+ arg
+ ),
+ ),
};
// We need the opts_present check because the driver will send us Matches
let error_format = if matches.opts_present(&["error-format".to_owned()]) {
match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
Some("human") => ErrorOutputType::HumanReadable(color),
- Some("json") => ErrorOutputType::Json(false),
+ Some("json") => ErrorOutputType::Json(false),
Some("pretty-json") => ErrorOutputType::Json(true),
Some("short") => {
if nightly_options::is_unstable_enabled(matches) {
ErrorOutputType::Short(color)
} else {
- early_error(ErrorOutputType::default(),
- &format!("the `-Z unstable-options` flag must also be passed to \
- enable the short error message option"));
+ early_error(
+ ErrorOutputType::default(),
+ &format!(
+ "the `-Z unstable-options` flag must also be passed to \
+ enable the short error message option"
+ ),
+ );
}
}
None => ErrorOutputType::HumanReadable(color),
- Some(arg) => {
- early_error(ErrorOutputType::HumanReadable(color),
- &format!("argument for --error-format must be `human`, `json` or \
- `short` (instead was `{}`)",
- arg))
- }
+ Some(arg) => early_error(
+ ErrorOutputType::HumanReadable(color),
+ &format!(
+ "argument for --error-format must be `human`, `json` or \
+ `short` (instead was `{}`)",
+ arg
+ ),
+ ),
}
} else {
ErrorOutputType::HumanReadable(color)
}
let lint_cap = matches.opt_str("cap-lints").map(|cap| {
- lint::Level::from_str(&cap).unwrap_or_else(|| {
- early_error(error_format, &format!("unknown lint level: `{}`", cap))
- })
+ lint::Level::from_str(&cap)
+ .unwrap_or_else(|| early_error(error_format, &format!("unknown lint level: `{}`", cap)))
});
let mut debugging_opts = build_debugging_options(matches, error_format);
if !debugging_opts.unstable_options && error_format == ErrorOutputType::Json(true) {
- early_error(ErrorOutputType::Json(false), "--error-format=pretty-json is unstable");
+ early_error(
+ ErrorOutputType::Json(false),
+ "--error-format=pretty-json is unstable",
+ );
}
let mut output_types = BTreeMap::new();
let shorthand = parts.next().unwrap();
let output_type = match OutputType::from_shorthand(shorthand) {
Some(output_type) => output_type,
- None => early_error(error_format, &format!(
- "unknown emission type: `{}` - expected one of: {}",
- shorthand, OutputType::shorthands_display(),
- )),
+ None => early_error(
+ error_format,
+ &format!(
+ "unknown emission type: `{}` - expected one of: {}",
+ shorthand,
+ OutputType::shorthands_display(),
+ ),
+ ),
};
let path = parts.next().map(PathBuf::from);
output_types.insert(output_type, path);
// Issue #30063: if user requests llvm-related output to one
// particular path, disable codegen-units.
- let incompatible: Vec<_> = output_types.iter()
+ let incompatible: Vec<_> = output_types
+ .iter()
.map(|ot_path| ot_path.0)
- .filter(|ot| {
- !ot.is_compatible_with_codegen_units_and_single_output_file()
- })
+ .filter(|ot| !ot.is_compatible_with_codegen_units_and_single_output_file())
.map(|ot| ot.shorthand())
.collect();
if !incompatible.is_empty() {
Some(n) if n > 1 => {
if matches.opt_present("o") {
for ot in &incompatible {
- early_warn(error_format, &format!("--emit={} with -o incompatible with \
- -C codegen-units=N for N > 1",
- ot));
+ early_warn(
+ error_format,
+ &format!(
+ "--emit={} with -o incompatible with \
+ -C codegen-units=N for N > 1",
+ ot
+ ),
+ );
}
early_warn(error_format, "resetting to default -C codegen-units=1");
codegen_units = Some(1);
}
if debugging_opts.query_threads == Some(0) {
- early_error(error_format, "Value for query threads must be a positive nonzero integer");
+ early_error(
+ error_format,
+ "Value for query threads must be a positive nonzero integer",
+ );
}
if codegen_units == Some(0) {
- early_error(error_format, "Value for codegen units must be a positive nonzero integer");
+ early_error(
+ error_format,
+ "Value for codegen units must be a positive nonzero integer",
+ );
}
let incremental = match (&debugging_opts.incremental, &cg.incremental) {
(&Some(ref path1), &Some(ref path2)) => {
if path1 != path2 {
- early_error(error_format,
- &format!("conflicting paths for `-Z incremental` and \
- `-C incremental` specified: {} versus {}",
- path1,
- path2));
+ early_error(
+ error_format,
+ &format!(
+ "conflicting paths for `-Z incremental` and \
+ `-C incremental` specified: {} versus {}",
+ path1, path2
+ ),
+ );
} else {
Some(path1)
}
}.map(|m| PathBuf::from(m));
if cg.lto != Lto::No && incremental.is_some() {
- early_error(error_format, "can't perform LTO when compiling incrementally");
+ early_error(
+ error_format,
+ "can't perform LTO when compiling incrementally",
+ );
}
let mut prints = Vec::<PrintRequest>::new();
prints.push(PrintRequest::CodeModels);
cg.code_model = None;
}
- if debugging_opts.tls_model.as_ref().map_or(false, |s| s == "help") {
+ if debugging_opts
+ .tls_model
+ .as_ref()
+ .map_or(false, |s| s == "help")
+ {
prints.push(PrintRequest::TlsModels);
debugging_opts.tls_model = None;
}
let cg = cg;
let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
- let target = matches.opt_str("target").unwrap_or(
- host_triple().to_string());
+ let target = matches
+ .opt_str("target")
+ .unwrap_or(host_triple().to_string());
let opt_level = {
if matches.opt_present("O") {
if cg.opt_level.is_some() {
}
OptLevel::Default
} else {
- match (cg.opt_level.as_ref().map(String::as_ref),
- nightly_options::is_nightly_build()) {
+ match (
+ cg.opt_level.as_ref().map(String::as_ref),
+ nightly_options::is_nightly_build(),
+ ) {
(None, _) => OptLevel::No,
(Some("0"), _) => OptLevel::No,
(Some("1"), _) => OptLevel::Less,
(Some("s"), true) => OptLevel::Size,
(Some("z"), true) => OptLevel::SizeMin,
(Some("s"), false) | (Some("z"), false) => {
- early_error(error_format, &format!("the optimizations s or z are only \
- accepted on the nightly compiler"));
- },
+ early_error(
+ error_format,
+ &format!(
+ "the optimizations s or z are only \
+ accepted on the nightly compiler"
+ ),
+ );
+ }
(Some(arg), _) => {
- early_error(error_format, &format!("optimization level needs to be \
- between 0-3 (instead was `{}`)",
- arg));
+ early_error(
+ error_format,
+ &format!(
+ "optimization level needs to be \
+ between 0-3 (instead was `{}`)",
+ arg
+ ),
+ );
}
}
}
Some(1) => LimitedDebugInfo,
Some(2) => FullDebugInfo,
Some(arg) => {
- early_error(error_format, &format!("debug info level needs to be between \
- 0-2 (instead was `{}`)",
- arg));
+ early_error(
+ error_format,
+ &format!(
+ "debug info level needs to be between \
+ 0-2 (instead was `{}`)",
+ arg
+ ),
+ );
}
}
};
search_paths.add_path(&s[..], error_format);
}
- let libs = matches.opt_strs("l").into_iter().map(|s| {
- // Parse string of the form "[KIND=]lib[:new_name]",
- // where KIND is one of "dylib", "framework", "static".
- let mut parts = s.splitn(2, '=');
- let kind = parts.next().unwrap();
- let (name, kind) = match (parts.next(), kind) {
- (None, name) => (name, None),
- (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
- (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
- (Some(name), "static") => (name, Some(cstore::NativeStatic)),
- (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
- (_, s) => {
- early_error(error_format, &format!("unknown library kind `{}`, expected \
- one of dylib, framework, or static",
- s));
+ let libs = matches
+ .opt_strs("l")
+ .into_iter()
+ .map(|s| {
+ // Parse string of the form "[KIND=]lib[:new_name]",
+ // where KIND is one of "dylib", "framework", "static".
+ let mut parts = s.splitn(2, '=');
+ let kind = parts.next().unwrap();
+ let (name, kind) = match (parts.next(), kind) {
+ (None, name) => (name, None),
+ (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
+ (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
+ (Some(name), "static") => (name, Some(cstore::NativeStatic)),
+ (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
+ (_, s) => {
+ early_error(
+ error_format,
+ &format!(
+ "unknown library kind `{}`, expected \
+ one of dylib, framework, or static",
+ s
+ ),
+ );
+ }
+ };
+ if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
+ early_error(
+ error_format,
+ &format!(
+ "the library kind 'static-nobundle' is only \
+ accepted on the nightly compiler"
+ ),
+ );
}
- };
- if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
- early_error(error_format, &format!("the library kind 'static-nobundle' is only \
- accepted on the nightly compiler"));
- }
- let mut name_parts = name.splitn(2, ':');
- let name = name_parts.next().unwrap();
- let new_name = name_parts.next();
- (name.to_string(), new_name.map(|n| n.to_string()), kind)
- }).collect();
+ let mut name_parts = name.splitn(2, ':');
+ let name = name_parts.next().unwrap();
+ let new_name = name_parts.next();
+ (name.to_string(), new_name.map(|n| n.to_string()), kind)
+ })
+ .collect();
let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
let test = matches.opt_present("test");
- prints.extend(matches.opt_strs("print").into_iter().map(|s| {
- match &*s {
- "crate-name" => PrintRequest::CrateName,
- "file-names" => PrintRequest::FileNames,
- "sysroot" => PrintRequest::Sysroot,
- "cfg" => PrintRequest::Cfg,
- "target-list" => PrintRequest::TargetList,
- "target-cpus" => PrintRequest::TargetCPUs,
- "target-features" => PrintRequest::TargetFeatures,
- "relocation-models" => PrintRequest::RelocationModels,
- "code-models" => PrintRequest::CodeModels,
- "tls-models" => PrintRequest::TlsModels,
- "native-static-libs" => PrintRequest::NativeStaticLibs,
- "target-spec-json" => {
- if nightly_options::is_unstable_enabled(matches) {
- PrintRequest::TargetSpec
- } else {
- early_error(error_format,
- &format!("the `-Z unstable-options` flag must also be passed to \
- enable the target-spec-json print option"));
- }
- },
- req => {
- early_error(error_format, &format!("unknown print request `{}`", req))
+ prints.extend(matches.opt_strs("print").into_iter().map(|s| match &*s {
+ "crate-name" => PrintRequest::CrateName,
+ "file-names" => PrintRequest::FileNames,
+ "sysroot" => PrintRequest::Sysroot,
+ "cfg" => PrintRequest::Cfg,
+ "target-list" => PrintRequest::TargetList,
+ "target-cpus" => PrintRequest::TargetCPUs,
+ "target-features" => PrintRequest::TargetFeatures,
+ "relocation-models" => PrintRequest::RelocationModels,
+ "code-models" => PrintRequest::CodeModels,
+ "tls-models" => PrintRequest::TlsModels,
+ "native-static-libs" => PrintRequest::NativeStaticLibs,
+ "target-spec-json" => {
+ if nightly_options::is_unstable_enabled(matches) {
+ PrintRequest::TargetSpec
+ } else {
+ early_error(
+ error_format,
+ &format!(
+ "the `-Z unstable-options` flag must also be passed to \
+ enable the target-spec-json print option"
+ ),
+ );
}
}
+ req => early_error(error_format, &format!("unknown print request `{}`", req)),
}));
let borrowck_mode = match debugging_opts.borrowck.as_ref().map(|s| &s[..]) {
None | Some("ast") => BorrowckMode::Ast,
Some("mir") => BorrowckMode::Mir,
Some("compare") => BorrowckMode::Compare,
- Some(m) => {
- early_error(error_format, &format!("unknown borrowck mode `{}`", m))
- },
+ Some(m) => early_error(error_format, &format!("unknown borrowck mode `{}`", m)),
};
if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
- early_warn(error_format, "-C remark will not show source locations without \
- --debuginfo");
+ early_warn(
+ error_format,
+ "-C remark will not show source locations without \
+ --debuginfo",
+ );
}
let mut externs = BTreeMap::new();
};
let location = match parts.next() {
Some(s) => s,
- None => early_error(error_format, "--extern value must be of the format `foo=bar`"),
+ None => early_error(
+ error_format,
+ "--extern value must be of the format `foo=bar`",
+ ),
};
- externs.entry(name.to_string())
- .or_insert_with(BTreeSet::new)
- .insert(location.to_string());
+ externs
+ .entry(name.to_string())
+ .or_insert_with(BTreeSet::new)
+ .insert(location.to_string());
}
let crate_name = matches.opt_str("crate-name");
- let remap_path_prefix = matches.opt_strs("remap-path-prefix")
+ let remap_path_prefix = matches
+ .opt_strs("remap-path-prefix")
.into_iter()
.map(|remap| {
let mut parts = remap.rsplitn(2, '='); // reverse iterator
let from = parts.next();
match (from, to) {
(Some(from), Some(to)) => (PathBuf::from(from), PathBuf::from(to)),
- _ => early_error(error_format,
- "--remap-path-prefix must contain '=' between FROM and TO"),
+ _ => early_error(
+ error_format,
+ "--remap-path-prefix must contain '=' between FROM and TO",
+ ),
}
})
.collect();
- (Options {
- crate_types,
- optimize: opt_level,
- debuginfo,
- lint_opts,
- lint_cap,
- describe_lints,
- output_types: OutputTypes(output_types),
- search_paths,
- maybe_sysroot: sysroot_opt,
- target_triple: target,
- test,
- incremental,
- debugging_opts,
- prints,
- borrowck_mode,
- cg,
- error_format,
- externs: Externs(externs),
- crate_name,
- alt_std_name: None,
- libs,
- unstable_features: UnstableFeatures::from_environment(),
- debug_assertions,
- actually_rustdoc: false,
- cli_forced_codegen_units: codegen_units,
- cli_forced_thinlto_off: disable_thinlto,
- remap_path_prefix,
- },
- cfg)
+ (
+ Options {
+ crate_types,
+ optimize: opt_level,
+ debuginfo,
+ lint_opts,
+ lint_cap,
+ describe_lints,
+ output_types: OutputTypes(output_types),
+ search_paths,
+ maybe_sysroot: sysroot_opt,
+ target_triple: target,
+ test,
+ incremental,
+ debugging_opts,
+ prints,
+ borrowck_mode,
+ cg,
+ error_format,
+ externs: Externs(externs),
+ crate_name,
+ alt_std_name: None,
+ libs,
+ unstable_features: UnstableFeatures::from_environment(),
+ debug_assertions,
+ actually_rustdoc: false,
+ cli_forced_codegen_units: codegen_units,
+ cli_forced_thinlto_off: disable_thinlto,
+ remap_path_prefix,
+ },
+ cfg,
+ )
}
-pub fn parse_crate_types_from_list(list_list: Vec<String>)
- -> Result<Vec<CrateType>, String> {
+pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
let mut crate_types: Vec<CrateType> = Vec::new();
for unparsed_crate_type in &list_list {
for part in unparsed_crate_type.split(',') {
let new_part = match part {
- "lib" => default_lib_output(),
- "rlib" => CrateTypeRlib,
+ "lib" => default_lib_output(),
+ "rlib" => CrateTypeRlib,
"staticlib" => CrateTypeStaticlib,
- "dylib" => CrateTypeDylib,
- "cdylib" => CrateTypeCdylib,
- "bin" => CrateTypeExecutable,
+ "dylib" => CrateTypeDylib,
+ "cdylib" => CrateTypeCdylib,
+ "bin" => CrateTypeExecutable,
"proc-macro" => CrateTypeProcMacro,
_ => {
- return Err(format!("unknown crate type: `{}`",
- part));
+ return Err(format!("unknown crate type: `{}`", part));
}
};
if !crate_types.contains(&new_part) {
use session::early_error;
pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
- is_nightly_build() && matches.opt_strs("Z").iter().any(|x| *x == "unstable-options")
+ is_nightly_build()
+ && matches
+ .opt_strs("Z")
+ .iter()
+ .any(|x| *x == "unstable-options")
}
pub fn is_nightly_build() -> bool {
}
pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
- let has_z_unstable_option = matches.opt_strs("Z").iter().any(|x| *x == "unstable-options");
- let really_allows_unstable_options = UnstableFeatures::from_environment()
- .is_nightly_build();
+ let has_z_unstable_option = matches
+ .opt_strs("Z")
+ .iter()
+ .any(|x| *x == "unstable-options");
+ let really_allows_unstable_options =
+ UnstableFeatures::from_environment().is_nightly_build();
for opt in flags.iter() {
if opt.stability == OptionStability::Stable {
- continue
+ continue;
}
if !matches.opt_present(opt.name) {
- continue
+ continue;
}
if opt.name != "Z" && !has_z_unstable_option {
- early_error(ErrorOutputType::default(),
- &format!("the `-Z unstable-options` flag must also be passed to enable \
- the flag `{}`",
- opt.name));
+ early_error(
+ ErrorOutputType::default(),
+ &format!(
+ "the `-Z unstable-options` flag must also be passed to enable \
+ the flag `{}`",
+ opt.name
+ ),
+ );
}
if really_allows_unstable_options {
- continue
+ continue;
}
match opt.stability {
OptionStability::Unstable => {
- let msg = format!("the option `{}` is only accepted on the \
- nightly compiler", opt.name);
+ let msg = format!(
+ "the option `{}` is only accepted on the \
+ nightly compiler",
+ opt.name
+ );
early_error(ErrorOutputType::default(), &msg);
}
OptionStability::Stable => {}
use std::hash::Hash;
use std::path::PathBuf;
use std::collections::hash_map::DefaultHasher;
- use super::{Passes, CrateType, OptLevel, DebugInfoLevel, Lto,
- OutputTypes, ErrorOutputType, Sanitizer, Epoch};
+ use super::{CrateType, DebugInfoLevel, Epoch, ErrorOutputType, Lto, OptLevel, OutputTypes,
+ Passes, Sanitizer};
use syntax::feature_gate::UnstableFeatures;
use rustc_back::{PanicStrategy, RelroLevel};
impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
- impl_dep_tracking_hash_for_sortable_vec_of!((String, Option<String>,
- Option<cstore::NativeLibraryKind>));
+ impl_dep_tracking_hash_for_sortable_vec_of!((
+ String,
+ Option<String>,
+ Option<cstore::NativeLibraryKind>
+ ));
impl_dep_tracking_hash_for_sortable_vec_of!((String, u64));
impl<T1, T2> DepTrackingHash for (T1, T2)
- where T1: DepTrackingHash,
- T2: DepTrackingHash
+ where
+ T1: DepTrackingHash,
+ T2: DepTrackingHash,
{
fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
Hash::hash(&0, hasher);
}
impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
- where T1: DepTrackingHash,
- T2: DepTrackingHash,
- T3: DepTrackingHash
+ where
+ T1: DepTrackingHash,
+ T2: DepTrackingHash,
+ T3: DepTrackingHash,
{
fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
Hash::hash(&0, hasher);
}
// This is a stable hash because BTreeMap is a sorted container
- pub fn stable_hash(sub_hashes: BTreeMap<&'static str, &dyn DepTrackingHash>,
- hasher: &mut DefaultHasher,
- error_format: ErrorOutputType) {
+ pub fn stable_hash(
+ sub_hashes: BTreeMap<&'static str, &dyn DepTrackingHash>,
+ hasher: &mut DefaultHasher,
+ error_format: ErrorOutputType,
+ ) {
for (key, sub_hash) in sub_hashes {
// Using Hash::hash() instead of DepTrackingHash::hash() is fine for
// the keys, as they are just plain strings
use std::collections::{BTreeMap, BTreeSet};
use std::iter::FromIterator;
use std::path::PathBuf;
- use super::{OutputType, OutputTypes, Externs};
+ use super::{Externs, OutputType, OutputTypes};
use rustc_back::{PanicStrategy, RelroLevel};
use syntax::symbol::Symbol;
for group in super::rustc_optgroups() {
(group.apply)(&mut opts);
}
- return opts
+ return opts;
}
fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
// When the user supplies --test we should implicitly supply --cfg test
#[test]
fn test_switch_implies_cfg_test() {
- let matches =
- &match optgroups().parse(&["--test".to_string()]) {
- Ok(m) => m,
- Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
- };
+ let matches = &match optgroups().parse(&["--test".to_string()]) {
+ Ok(m) => m,
+ Err(f) => panic!("test_switch_implies_cfg_test: {}", f),
+ };
let registry = errors::registry::Registry::new(&[]);
let (sessopts, cfg) = build_session_options_and_crate_config(matches);
let sess = build_session(sessopts, None, registry);
// another --cfg test
#[test]
fn test_switch_implies_cfg_test_unless_cfg_test() {
- let matches =
- &match optgroups().parse(&["--test".to_string(), "--cfg=test".to_string()]) {
- Ok(m) => m,
- Err(f) => {
- panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
- }
- };
+ let matches = &match optgroups().parse(&["--test".to_string(), "--cfg=test".to_string()]) {
+ Ok(m) => m,
+ Err(f) => panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f),
+ };
let registry = errors::registry::Registry::new(&[]);
let (sessopts, cfg) = build_session_options_and_crate_config(matches);
let sess = build_session(sessopts, None, registry);
#[test]
fn test_can_print_warnings() {
{
- let matches = optgroups().parse(&[
- "-Awarnings".to_string()
- ]).unwrap();
+ let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
let registry = errors::registry::Registry::new(&[]);
let (sessopts, _) = build_session_options_and_crate_config(&matches);
let sess = build_session(sessopts, None, registry);
}
{
- let matches = optgroups().parse(&[
- "-Awarnings".to_string(),
- "-Dwarnings".to_string()
- ]).unwrap();
+ let matches = optgroups()
+ .parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()])
+ .unwrap();
let registry = errors::registry::Registry::new(&[]);
let (sessopts, _) = build_session_options_and_crate_config(&matches);
let sess = build_session(sessopts, None, registry);
}
{
- let matches = optgroups().parse(&[
- "-Adead_code".to_string()
- ]).unwrap();
+ let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
let registry = errors::registry::Registry::new(&[]);
let (sessopts, _) = build_session_options_and_crate_config(&matches);
let sess = build_session(sessopts, None, registry);
let mut v2 = super::basic_options();
let mut v3 = super::basic_options();
- v1.output_types = OutputTypes::new(&[(OutputType::Exe,
- Some(PathBuf::from("./some/thing")))]);
- v2.output_types = OutputTypes::new(&[(OutputType::Exe,
- Some(PathBuf::from("/some/thing")))]);
+ v1.output_types =
+ OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("./some/thing")))]);
+ v2.output_types =
+ OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("/some/thing")))]);
v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
let mut v3 = super::basic_options();
v1.externs = Externs::new(mk_map(vec![
- (String::from("a"), mk_set(vec![String::from("b"),
- String::from("c")])),
- (String::from("d"), mk_set(vec![String::from("e"),
- String::from("f")])),
+ (
+ String::from("a"),
+ mk_set(vec![String::from("b"), String::from("c")]),
+ ),
+ (
+ String::from("d"),
+ mk_set(vec![String::from("e"), String::from("f")]),
+ ),
]));
v2.externs = Externs::new(mk_map(vec![
- (String::from("d"), mk_set(vec![String::from("e"),
- String::from("f")])),
- (String::from("a"), mk_set(vec![String::from("b"),
- String::from("c")])),
+ (
+ String::from("d"),
+ mk_set(vec![String::from("e"), String::from("f")]),
+ ),
+ (
+ String::from("a"),
+ mk_set(vec![String::from("b"), String::from("c")]),
+ ),
]));
v3.externs = Externs::new(mk_map(vec![
- (String::from("a"), mk_set(vec![String::from("b"),
- String::from("c")])),
- (String::from("d"), mk_set(vec![String::from("f"),
- String::from("e")])),
+ (
+ String::from("a"),
+ mk_set(vec![String::from("b"), String::from("c")]),
+ ),
+ (
+ String::from("d"),
+ mk_set(vec![String::from("f"), String::from("e")]),
+ ),
]));
assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
let mut v2 = super::basic_options();
let mut v3 = super::basic_options();
- v1.lint_opts = vec![(String::from("a"), lint::Allow),
- (String::from("b"), lint::Warn),
- (String::from("c"), lint::Deny),
- (String::from("d"), lint::Forbid)];
-
- v2.lint_opts = vec![(String::from("a"), lint::Allow),
- (String::from("b"), lint::Warn),
- (String::from("X"), lint::Deny),
- (String::from("d"), lint::Forbid)];
-
- v3.lint_opts = vec![(String::from("a"), lint::Allow),
- (String::from("b"), lint::Warn),
- (String::from("c"), lint::Forbid),
- (String::from("d"), lint::Deny)];
+ v1.lint_opts = vec![
+ (String::from("a"), lint::Allow),
+ (String::from("b"), lint::Warn),
+ (String::from("c"), lint::Deny),
+ (String::from("d"), lint::Forbid),
+ ];
+
+ v2.lint_opts = vec![
+ (String::from("a"), lint::Allow),
+ (String::from("b"), lint::Warn),
+ (String::from("X"), lint::Deny),
+ (String::from("d"), lint::Forbid),
+ ];
+
+ v3.lint_opts = vec![
+ (String::from("a"), lint::Allow),
+ (String::from("b"), lint::Warn),
+ (String::from("c"), lint::Forbid),
+ (String::from("d"), lint::Deny),
+ ];
assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
let mut v1 = super::basic_options();
let mut v2 = super::basic_options();
- v1.lint_opts = vec![(String::from("a"), lint::Allow),
- (String::from("b"), lint::Warn),
- (String::from("c"), lint::Deny),
- (String::from("d"), lint::Forbid)];
+ v1.lint_opts = vec![
+ (String::from("a"), lint::Allow),
+ (String::from("b"), lint::Warn),
+ (String::from("c"), lint::Deny),
+ (String::from("d"), lint::Forbid),
+ ];
- v2.lint_opts = vec![(String::from("a"), lint::Allow),
- (String::from("c"), lint::Deny),
- (String::from("b"), lint::Warn),
- (String::from("d"), lint::Forbid)];
+ v2.lint_opts = vec![
+ (String::from("a"), lint::Allow),
+ (String::from("c"), lint::Deny),
+ (String::from("b"), lint::Warn),
+ (String::from("d"), lint::Forbid),
+ ];
assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
let mut v4 = super::basic_options();
// Reference
- v1.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
- v1.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
- v1.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
- v1.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
- v1.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
-
- v2.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
- v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
- v2.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
- v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
- v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
-
- v3.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
- v3.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
- v3.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
- v3.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
- v3.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
-
- v4.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
- v4.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
- v4.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
- v4.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
- v4.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
+ v1.search_paths
+ .add_path("native=abc", super::ErrorOutputType::Json(false));
+ v1.search_paths
+ .add_path("crate=def", super::ErrorOutputType::Json(false));
+ v1.search_paths
+ .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
+ v1.search_paths
+ .add_path("framework=jkl", super::ErrorOutputType::Json(false));
+ v1.search_paths
+ .add_path("all=mno", super::ErrorOutputType::Json(false));
+
+ v2.search_paths
+ .add_path("native=abc", super::ErrorOutputType::Json(false));
+ v2.search_paths
+ .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
+ v2.search_paths
+ .add_path("crate=def", super::ErrorOutputType::Json(false));
+ v2.search_paths
+ .add_path("framework=jkl", super::ErrorOutputType::Json(false));
+ v2.search_paths
+ .add_path("all=mno", super::ErrorOutputType::Json(false));
+
+ v3.search_paths
+ .add_path("crate=def", super::ErrorOutputType::Json(false));
+ v3.search_paths
+ .add_path("framework=jkl", super::ErrorOutputType::Json(false));
+ v3.search_paths
+ .add_path("native=abc", super::ErrorOutputType::Json(false));
+ v3.search_paths
+ .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
+ v3.search_paths
+ .add_path("all=mno", super::ErrorOutputType::Json(false));
+
+ v4.search_paths
+ .add_path("all=mno", super::ErrorOutputType::Json(false));
+ v4.search_paths
+ .add_path("native=abc", super::ErrorOutputType::Json(false));
+ v4.search_paths
+ .add_path("crate=def", super::ErrorOutputType::Json(false));
+ v4.search_paths
+ .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
+ v4.search_paths
+ .add_path("framework=jkl", super::ErrorOutputType::Json(false));
assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
let mut v4 = super::basic_options();
// Reference
- v1.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
- (String::from("b"), None, Some(cstore::NativeFramework)),
- (String::from("c"), None, Some(cstore::NativeUnknown))];
+ v1.libs = vec![
+ (String::from("a"), None, Some(cstore::NativeStatic)),
+ (String::from("b"), None, Some(cstore::NativeFramework)),
+ (String::from("c"), None, Some(cstore::NativeUnknown)),
+ ];
// Change label
- v2.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
- (String::from("X"), None, Some(cstore::NativeFramework)),
- (String::from("c"), None, Some(cstore::NativeUnknown))];
+ v2.libs = vec![
+ (String::from("a"), None, Some(cstore::NativeStatic)),
+ (String::from("X"), None, Some(cstore::NativeFramework)),
+ (String::from("c"), None, Some(cstore::NativeUnknown)),
+ ];
// Change kind
- v3.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
- (String::from("b"), None, Some(cstore::NativeStatic)),
- (String::from("c"), None, Some(cstore::NativeUnknown))];
+ v3.libs = vec![
+ (String::from("a"), None, Some(cstore::NativeStatic)),
+ (String::from("b"), None, Some(cstore::NativeStatic)),
+ (String::from("c"), None, Some(cstore::NativeUnknown)),
+ ];
// Change new-name
- v4.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
- (String::from("b"), Some(String::from("X")), Some(cstore::NativeFramework)),
- (String::from("c"), None, Some(cstore::NativeUnknown))];
+ v4.libs = vec![
+ (String::from("a"), None, Some(cstore::NativeStatic)),
+ (
+ String::from("b"),
+ Some(String::from("X")),
+ Some(cstore::NativeFramework),
+ ),
+ (String::from("c"), None, Some(cstore::NativeUnknown)),
+ ];
assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
let mut v3 = super::basic_options();
// Reference
- v1.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
- (String::from("b"), None, Some(cstore::NativeFramework)),
- (String::from("c"), None, Some(cstore::NativeUnknown))];
-
- v2.libs = vec![(String::from("b"), None, Some(cstore::NativeFramework)),
- (String::from("a"), None, Some(cstore::NativeStatic)),
- (String::from("c"), None, Some(cstore::NativeUnknown))];
-
- v3.libs = vec![(String::from("c"), None, Some(cstore::NativeUnknown)),
- (String::from("a"), None, Some(cstore::NativeStatic)),
- (String::from("b"), None, Some(cstore::NativeFramework))];
+ v1.libs = vec![
+ (String::from("a"), None, Some(cstore::NativeStatic)),
+ (String::from("b"), None, Some(cstore::NativeFramework)),
+ (String::from("c"), None, Some(cstore::NativeUnknown)),
+ ];
+
+ v2.libs = vec![
+ (String::from("b"), None, Some(cstore::NativeFramework)),
+ (String::from("a"), None, Some(cstore::NativeStatic)),
+ (String::from("c"), None, Some(cstore::NativeUnknown)),
+ ];
+
+ v3.libs = vec![
+ (String::from("c"), None, Some(cstore::NativeUnknown)),
+ (String::from("a"), None, Some(cstore::NativeStatic)),
+ (String::from("b"), None, Some(cstore::NativeFramework)),
+ ];
assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
opts.cg.codegen_units = Some(42);
assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
- opts.cg.remark = super::SomePasses(vec![String::from("pass1"),
- String::from("pass2")]);
+ opts.cg.remark = super::SomePasses(vec![String::from("pass1"), String::from("pass2")]);
assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
opts.cg.save_temps = true;
opts.cg.incremental = Some(String::from("abc"));
assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
-
// Make sure changing a [TRACKED] option changes the hash
opts = reference.clone();
opts.cg.lto = Lto::Fat;
use middle::allocator::AllocatorKind;
use middle::dependency_format;
use session::search_paths::PathKind;
-use session::config::{DebugInfoLevel, OutputType, Epoch};
+use session::config::{DebugInfoLevel, Epoch, OutputType};
use ty::tls;
use util::nodemap::{FxHashMap, FxHashSet};
use util::common::{duration_to_secs_str, ErrorReported};
use syntax::parse::ParseSess;
use syntax::{ast, codemap};
use syntax::feature_gate::AttributeType;
-use syntax_pos::{Span, MultiSpan};
+use syntax_pos::{MultiSpan, Span};
use rustc_back::{LinkerFlavor, PanicStrategy};
use rustc_back::target::Target;
pub plugin_attributes: RefCell<Vec<(String, AttributeType)>>,
pub crate_types: RefCell<Vec<config::CrateType>>,
pub dependency_formats: RefCell<dependency_format::Dependencies>,
- /// The crate_disambiguator is constructed out of all the `-C metadata`
+ /// 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
out_of_fuel: Cell<bool>,
// The next two are public because the driver needs to read them.
-
/// If -zprint-fuel=crate, Some(crate).
pub print_fuel_crate: Option<String>,
/// Always set to zero and incremented so that we can print fuel expended by a crate.
Note,
SpanNote,
SpanSuggestion(String), // suggestion
- // add more variants as needed to support one-time diagnostics
+ // add more variants as needed to support one-time diagnostics
}
/// Diagnostic message ID—used by `Session.one_time_diagnostics` to avoid
pub enum DiagnosticMessageId {
ErrorId(u16), // EXXXX error code as integer
LintId(lint::LintId),
- StabilityId(u32) // issue number
+ StabilityId(u32), // issue number
}
impl From<&'static lint::Lint> for DiagnosticMessageId {
}
}
- pub fn struct_span_warn<'a, S: Into<MultiSpan>>(&'a self,
- sp: S,
- msg: &str)
- -> DiagnosticBuilder<'a> {
+ pub fn struct_span_warn<'a, S: Into<MultiSpan>>(
+ &'a self,
+ sp: S,
+ msg: &str,
+ ) -> DiagnosticBuilder<'a> {
self.diagnostic().struct_span_warn(sp, msg)
}
- pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(&'a self,
- sp: S,
- msg: &str,
- code: DiagnosticId)
- -> DiagnosticBuilder<'a> {
+ pub fn struct_span_warn_with_code<'a, S: Into<MultiSpan>>(
+ &'a self,
+ sp: S,
+ msg: &str,
+ code: DiagnosticId,
+ ) -> DiagnosticBuilder<'a> {
self.diagnostic().struct_span_warn_with_code(sp, msg, code)
}
- pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
+ pub fn struct_warn<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
self.diagnostic().struct_warn(msg)
}
- pub fn struct_span_err<'a, S: Into<MultiSpan>>(&'a self,
- sp: S,
- msg: &str)
- -> DiagnosticBuilder<'a> {
+ pub fn struct_span_err<'a, S: Into<MultiSpan>>(
+ &'a self,
+ sp: S,
+ msg: &str,
+ ) -> DiagnosticBuilder<'a> {
self.diagnostic().struct_span_err(sp, msg)
}
- pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(&'a self,
- sp: S,
- msg: &str,
- code: DiagnosticId)
- -> DiagnosticBuilder<'a> {
+ pub fn struct_span_err_with_code<'a, S: Into<MultiSpan>>(
+ &'a self,
+ sp: S,
+ msg: &str,
+ code: DiagnosticId,
+ ) -> DiagnosticBuilder<'a> {
self.diagnostic().struct_span_err_with_code(sp, msg, code)
}
// FIXME: This method should be removed (every error should have an associated error code).
) -> DiagnosticBuilder<'a> {
self.diagnostic().struct_err_with_code(msg, code)
}
- pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(&'a self,
- sp: S,
- msg: &str)
- -> DiagnosticBuilder<'a> {
+ pub fn struct_span_fatal<'a, S: Into<MultiSpan>>(
+ &'a self,
+ sp: S,
+ msg: &str,
+ ) -> DiagnosticBuilder<'a> {
self.diagnostic().struct_span_fatal(sp, msg)
}
- pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(&'a self,
- sp: S,
- msg: &str,
- code: DiagnosticId)
- -> DiagnosticBuilder<'a> {
+ pub fn struct_span_fatal_with_code<'a, S: Into<MultiSpan>>(
+ &'a self,
+ sp: S,
+ msg: &str,
+ code: DiagnosticId,
+ ) -> DiagnosticBuilder<'a> {
self.diagnostic().struct_span_fatal_with_code(sp, msg, code)
}
- pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
+ pub fn struct_fatal<'a>(&'a self, msg: &str) -> DiagnosticBuilder<'a> {
self.diagnostic().struct_fatal(msg)
}
msg: &str,
code: DiagnosticId,
) -> ! {
- self.diagnostic().span_fatal_with_code(sp, msg, code).raise()
+ self.diagnostic()
+ .span_fatal_with_code(sp, msg, code)
+ .raise()
}
pub fn fatal(&self, msg: &str) -> ! {
self.diagnostic().fatal(msg).raise()
compile_result_from_err_count(self.err_count())
}
pub fn track_errors<F, T>(&self, f: F) -> Result<T, ErrorReported>
- where F: FnOnce() -> T
+ where
+ F: FnOnce() -> T,
{
let old_count = self.err_count();
let result = f();
self.diagnostic().unimpl(msg)
}
- pub fn buffer_lint<S: Into<MultiSpan>>(&self,
- lint: &'static lint::Lint,
- id: ast::NodeId,
- sp: S,
- msg: &str) {
+ pub fn buffer_lint<S: Into<MultiSpan>>(
+ &self,
+ lint: &'static lint::Lint,
+ id: ast::NodeId,
+ sp: S,
+ msg: &str,
+ ) {
match *self.buffered_lints.borrow_mut() {
- Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(),
- msg, BuiltinLintDiagnostics::Normal),
+ Some(ref mut buffer) => {
+ buffer.add_lint(lint, id, sp.into(), msg, BuiltinLintDiagnostics::Normal)
+ }
None => bug!("can't buffer lints after HIR lowering"),
}
}
- pub fn buffer_lint_with_diagnostic<S: Into<MultiSpan>>(&self,
- lint: &'static lint::Lint, id: ast::NodeId, sp: S,
- msg: &str, diagnostic: BuiltinLintDiagnostics) {
+ pub fn buffer_lint_with_diagnostic<S: Into<MultiSpan>>(
+ &self,
+ lint: &'static lint::Lint,
+ id: ast::NodeId,
+ sp: S,
+ msg: &str,
+ diagnostic: BuiltinLintDiagnostics,
+ ) {
match *self.buffered_lints.borrow_mut() {
- Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(),
- msg, diagnostic),
+ Some(ref mut buffer) => buffer.add_lint(lint, id, sp.into(), msg, diagnostic),
None => bug!("can't buffer lints after HIR lowering"),
}
}
Some(next) => {
self.next_node_id.set(ast::NodeId::new(next));
}
- None => bug!("Input too large, ran out of node ids!")
+ None => bug!("Input too large, ran out of node ids!"),
}
id
/// Analogous to calling methods on the given `DiagnosticBuilder`, but
/// deduplicates on lint ID, span (if any), and message for this `Session`
- fn diag_once<'a, 'b>(&'a self,
- diag_builder: &'b mut DiagnosticBuilder<'a>,
- method: DiagnosticBuilderMethod,
- msg_id: DiagnosticMessageId,
- message: &str,
- span_maybe: Option<Span>) {
-
+ fn diag_once<'a, 'b>(
+ &'a self,
+ diag_builder: &'b mut DiagnosticBuilder<'a>,
+ method: DiagnosticBuilderMethod,
+ msg_id: DiagnosticMessageId,
+ message: &str,
+ span_maybe: Option<Span>,
+ ) {
let id_span_message = (msg_id, span_maybe, message.to_owned());
- let fresh = self.one_time_diagnostics.borrow_mut().insert(id_span_message);
+ let fresh = self.one_time_diagnostics
+ .borrow_mut()
+ .insert(id_span_message);
if fresh {
match method {
DiagnosticBuilderMethod::Note => {
diag_builder.note(message);
- },
+ }
DiagnosticBuilderMethod::SpanNote => {
let span = span_maybe.expect("span_note needs a span");
diag_builder.span_note(span, message);
- },
+ }
DiagnosticBuilderMethod::SpanSuggestion(suggestion) => {
let span = span_maybe.expect("span_suggestion needs a span");
diag_builder.span_suggestion(span, message, suggestion);
}
}
- pub fn diag_span_note_once<'a, 'b>(&'a self,
- diag_builder: &'b mut DiagnosticBuilder<'a>,
- msg_id: DiagnosticMessageId, span: Span, message: &str) {
- self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanNote,
- msg_id, message, Some(span));
- }
-
- pub fn diag_note_once<'a, 'b>(&'a self,
- diag_builder: &'b mut DiagnosticBuilder<'a>,
- msg_id: DiagnosticMessageId, message: &str) {
- self.diag_once(diag_builder, DiagnosticBuilderMethod::Note, msg_id, message, None);
- }
-
- pub fn diag_span_suggestion_once<'a, 'b>(&'a self,
- diag_builder: &'b mut DiagnosticBuilder<'a>,
- msg_id: DiagnosticMessageId,
- span: Span,
- message: &str,
- suggestion: String) {
- self.diag_once(diag_builder, DiagnosticBuilderMethod::SpanSuggestion(suggestion),
- msg_id, message, Some(span));
+ pub fn diag_span_note_once<'a, 'b>(
+ &'a self,
+ diag_builder: &'b mut DiagnosticBuilder<'a>,
+ msg_id: DiagnosticMessageId,
+ span: Span,
+ message: &str,
+ ) {
+ self.diag_once(
+ diag_builder,
+ DiagnosticBuilderMethod::SpanNote,
+ msg_id,
+ message,
+ Some(span),
+ );
+ }
+
+ pub fn diag_note_once<'a, 'b>(
+ &'a self,
+ diag_builder: &'b mut DiagnosticBuilder<'a>,
+ msg_id: DiagnosticMessageId,
+ message: &str,
+ ) {
+ self.diag_once(
+ diag_builder,
+ DiagnosticBuilderMethod::Note,
+ msg_id,
+ message,
+ None,
+ );
+ }
+
+ pub fn diag_span_suggestion_once<'a, 'b>(
+ &'a self,
+ diag_builder: &'b mut DiagnosticBuilder<'a>,
+ msg_id: DiagnosticMessageId,
+ span: Span,
+ message: &str,
+ suggestion: String,
+ ) {
+ self.diag_once(
+ diag_builder,
+ DiagnosticBuilderMethod::SpanSuggestion(suggestion),
+ msg_id,
+ message,
+ Some(span),
+ );
}
pub fn codemap<'a>(&'a self) -> &'a codemap::CodeMap {
self.parse_sess.codemap()
}
- pub fn verbose(&self) -> bool { self.opts.debugging_opts.verbose }
- pub fn time_passes(&self) -> bool { self.opts.debugging_opts.time_passes }
+ pub fn verbose(&self) -> bool {
+ self.opts.debugging_opts.verbose
+ }
+ pub fn time_passes(&self) -> bool {
+ self.opts.debugging_opts.time_passes
+ }
pub fn profile_queries(&self) -> bool {
- self.opts.debugging_opts.profile_queries ||
- self.opts.debugging_opts.profile_queries_and_keys
+ self.opts.debugging_opts.profile_queries
+ || self.opts.debugging_opts.profile_queries_and_keys
}
pub fn profile_queries_and_keys(&self) -> bool {
self.opts.debugging_opts.profile_queries_and_keys
pub fn time_llvm_passes(&self) -> bool {
self.opts.debugging_opts.time_llvm_passes
}
- pub fn trans_stats(&self) -> bool { self.opts.debugging_opts.trans_stats }
- pub fn meta_stats(&self) -> bool { self.opts.debugging_opts.meta_stats }
- pub fn asm_comments(&self) -> bool { self.opts.debugging_opts.asm_comments }
- pub fn no_verify(&self) -> bool { self.opts.debugging_opts.no_verify }
- pub fn borrowck_stats(&self) -> bool { self.opts.debugging_opts.borrowck_stats }
+ pub fn trans_stats(&self) -> bool {
+ self.opts.debugging_opts.trans_stats
+ }
+ pub fn meta_stats(&self) -> bool {
+ self.opts.debugging_opts.meta_stats
+ }
+ pub fn asm_comments(&self) -> bool {
+ self.opts.debugging_opts.asm_comments
+ }
+ pub fn no_verify(&self) -> bool {
+ self.opts.debugging_opts.no_verify
+ }
+ pub fn borrowck_stats(&self) -> bool {
+ self.opts.debugging_opts.borrowck_stats
+ }
pub fn print_llvm_passes(&self) -> bool {
self.opts.debugging_opts.print_llvm_passes
}
pub fn lto(&self) -> config::Lto {
// If our target has codegen requirements ignore the command line
if self.target.target.options.requires_lto {
- return config::Lto::Fat
+ return config::Lto::Fat;
}
// If the user specified something, return that. If they only said `-C
// then ensure we can't use a ThinLTO.
match self.opts.cg.lto {
config::Lto::No => {}
- config::Lto::Yes if self.opts.cli_forced_thinlto_off => {
- return config::Lto::Fat
- }
+ config::Lto::Yes if self.opts.cli_forced_thinlto_off => return config::Lto::Fat,
other => return other,
}
// If processing command line options determined that we're incompatible
// with ThinLTO (e.g. `-C lto --emit llvm-ir`) then return that option.
if self.opts.cli_forced_thinlto_off {
- return config::Lto::No
+ return config::Lto::No;
}
// If `-Z thinlto` specified process that, but note that this is mostly
// a deprecated option now that `-C lto=thin` exists.
if let Some(enabled) = self.opts.debugging_opts.thinlto {
if enabled {
- return config::Lto::ThinLocal
+ return config::Lto::ThinLocal;
} else {
- return config::Lto::No
+ return config::Lto::No;
}
}
// If there's only one codegen unit and LTO isn't enabled then there's
// no need for ThinLTO so just return false.
if self.codegen_units() == 1 {
- return config::Lto::No
+ return config::Lto::No;
}
// Right now ThinLTO isn't compatible with incremental compilation.
if self.opts.incremental.is_some() {
- return config::Lto::No
+ return config::Lto::No;
}
// Now we're in "defaults" territory. By default we enable ThinLTO for
/// Returns the panic strategy for this compile session. If the user explicitly selected one
/// using '-C panic', use that, otherwise use the panic strategy defined by the target.
pub fn panic_strategy(&self) -> PanicStrategy {
- self.opts.cg.panic.unwrap_or(self.target.target.options.panic_strategy)
+ self.opts
+ .cg
+ .panic
+ .unwrap_or(self.target.target.options.panic_strategy)
}
pub fn linker_flavor(&self) -> LinkerFlavor {
- self.opts.debugging_opts.linker_flavor.unwrap_or(self.target.target.linker_flavor)
+ self.opts
+ .debugging_opts
+ .linker_flavor
+ .unwrap_or(self.target.target.linker_flavor)
}
pub fn fewer_names(&self) -> bool {
- let more_names = self.opts.output_types.contains_key(&OutputType::LlvmAssembly) ||
- self.opts.output_types.contains_key(&OutputType::Bitcode);
+ let more_names = self.opts
+ .output_types
+ .contains_key(&OutputType::LlvmAssembly)
+ || self.opts.output_types.contains_key(&OutputType::Bitcode);
self.opts.debugging_opts.fewer_names || !more_names
}
self.opts.debugging_opts.enable_nonzeroing_move_hints
}
pub fn overflow_checks(&self) -> bool {
- self.opts.cg.overflow_checks
+ self.opts
+ .cg
+ .overflow_checks
.or(self.opts.debugging_opts.force_overflow_checks)
.unwrap_or(self.opts.debug_assertions)
}
}
pub fn must_not_eliminate_frame_pointers(&self) -> bool {
- self.opts.debuginfo != DebugInfoLevel::NoDebugInfo ||
- !self.target.target.options.eliminate_frame_pointer
+ self.opts.debuginfo != DebugInfoLevel::NoDebugInfo
+ || !self.target.target.options.eliminate_frame_pointer
}
/// Returns the symbol name for the registrar function,
/// given the crate Svh and the function DefIndex.
- pub fn generate_plugin_registrar_symbol(&self,
- disambiguator: CrateDisambiguator)
- -> String {
- format!("__rustc_plugin_registrar_{}__", disambiguator.to_fingerprint().to_hex())
+ pub fn generate_plugin_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
+ format!(
+ "__rustc_plugin_registrar_{}__",
+ disambiguator.to_fingerprint().to_hex()
+ )
}
- pub fn generate_derive_registrar_symbol(&self,
- disambiguator: CrateDisambiguator)
- -> String {
- format!("__rustc_derive_registrar_{}__", disambiguator.to_fingerprint().to_hex())
+ pub fn generate_derive_registrar_symbol(&self, disambiguator: CrateDisambiguator) -> String {
+ format!(
+ "__rustc_derive_registrar_{}__",
+ disambiguator.to_fingerprint().to_hex()
+ )
}
pub fn sysroot<'a>(&'a self) -> &'a Path {
match self.opts.maybe_sysroot {
- Some (ref sysroot) => sysroot,
- None => self.default_sysroot.as_ref()
- .expect("missing sysroot and default_sysroot in Session")
+ Some(ref sysroot) => sysroot,
+ None => self.default_sysroot
+ .as_ref()
+ .expect("missing sysroot and default_sysroot in Session"),
}
}
pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
- filesearch::FileSearch::new(self.sysroot(),
- &self.opts.target_triple,
- &self.opts.search_paths,
- kind)
+ filesearch::FileSearch::new(
+ self.sysroot(),
+ &self.opts.target_triple,
+ &self.opts.search_paths,
+ kind,
+ )
}
pub fn host_filesearch(&self, kind: PathKind) -> filesearch::FileSearch {
filesearch::FileSearch::new(
self.sysroot(),
config::host_triple(),
&self.opts.search_paths,
- kind)
+ kind,
+ )
}
pub fn set_incr_session_load_dep_graph(&self, load: bool) {
let mut incr_comp_session = self.incr_comp_session.borrow_mut();
match *incr_comp_session {
- IncrCompSession::Active { ref mut load_dep_graph, .. } => {
+ IncrCompSession::Active {
+ ref mut load_dep_graph,
+ ..
+ } => {
*load_dep_graph = load;
}
_ => {}
}
}
- pub fn init_incr_comp_session(&self,
- session_dir: PathBuf,
- lock_file: flock::Lock,
- load_dep_graph: bool) {
+ pub fn init_incr_comp_session(
+ &self,
+ session_dir: PathBuf,
+ lock_file: flock::Lock,
+ load_dep_graph: bool,
+ ) {
let mut incr_comp_session = self.incr_comp_session.borrow_mut();
- if let IncrCompSession::NotInitialized = *incr_comp_session { } else {
- bug!("Trying to initialize IncrCompSession `{:?}`", *incr_comp_session)
+ if let IncrCompSession::NotInitialized = *incr_comp_session {
+ } else {
+ bug!(
+ "Trying to initialize IncrCompSession `{:?}`",
+ *incr_comp_session
+ )
}
*incr_comp_session = IncrCompSession::Active {
pub fn finalize_incr_comp_session(&self, new_directory_path: PathBuf) {
let mut incr_comp_session = self.incr_comp_session.borrow_mut();
- if let IncrCompSession::Active { .. } = *incr_comp_session { } else {
- bug!("Trying to finalize IncrCompSession `{:?}`", *incr_comp_session)
+ if let IncrCompSession::Active { .. } = *incr_comp_session {
+ } else {
+ bug!(
+ "Trying to finalize IncrCompSession `{:?}`",
+ *incr_comp_session
+ )
}
// Note: This will also drop the lock file, thus unlocking the directory
let mut incr_comp_session = self.incr_comp_session.borrow_mut();
let session_directory = match *incr_comp_session {
- IncrCompSession::Active { ref session_directory, .. } => {
- session_directory.clone()
- }
+ IncrCompSession::Active {
+ ref session_directory,
+ ..
+ } => session_directory.clone(),
IncrCompSession::InvalidBecauseOfErrors { .. } => return,
- _ => bug!("Trying to invalidate IncrCompSession `{:?}`",
- *incr_comp_session),
+ _ => bug!(
+ "Trying to invalidate IncrCompSession `{:?}`",
+ *incr_comp_session
+ ),
};
// Note: This will also drop the lock file, thus unlocking the directory
- *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors {
- session_directory,
- };
+ *incr_comp_session = IncrCompSession::InvalidBecauseOfErrors { session_directory };
}
pub fn incr_comp_session_dir(&self) -> cell::Ref<PathBuf> {
let incr_comp_session = self.incr_comp_session.borrow();
- cell::Ref::map(incr_comp_session, |incr_comp_session| {
- match *incr_comp_session {
- IncrCompSession::NotInitialized => {
- bug!("Trying to get session directory from IncrCompSession `{:?}`",
- *incr_comp_session)
+ cell::Ref::map(
+ incr_comp_session,
+ |incr_comp_session| match *incr_comp_session {
+ IncrCompSession::NotInitialized => bug!(
+ "Trying to get session directory from IncrCompSession `{:?}`",
+ *incr_comp_session
+ ),
+ IncrCompSession::Active {
+ ref session_directory,
+ ..
}
- IncrCompSession::Active { ref session_directory, .. } |
- IncrCompSession::Finalized { ref session_directory } |
- IncrCompSession::InvalidBecauseOfErrors { ref session_directory } => {
- session_directory
+ | IncrCompSession::Finalized {
+ ref session_directory,
}
- }
- })
+ | IncrCompSession::InvalidBecauseOfErrors {
+ ref session_directory,
+ } => session_directory,
+ },
+ )
}
pub fn incr_comp_session_dir_opt(&self) -> Option<cell::Ref<PathBuf>> {
}
pub fn print_perf_stats(&self) {
- println!("Total time spent computing SVHs: {}",
- duration_to_secs_str(self.perf_stats.svh_time.get()));
- println!("Total time spent computing incr. comp. hashes: {}",
- duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get()));
- println!("Total number of incr. comp. hashes computed: {}",
- self.perf_stats.incr_comp_hashes_count.get());
- println!("Total number of bytes hashed for incr. comp.: {}",
- self.perf_stats.incr_comp_bytes_hashed.get());
+ println!(
+ "Total time spent computing SVHs: {}",
+ duration_to_secs_str(self.perf_stats.svh_time.get())
+ );
+ println!(
+ "Total time spent computing incr. comp. hashes: {}",
+ duration_to_secs_str(self.perf_stats.incr_comp_hashes_time.get())
+ );
+ println!(
+ "Total number of incr. comp. hashes computed: {}",
+ self.perf_stats.incr_comp_hashes_count.get()
+ );
+ println!(
+ "Total number of bytes hashed for incr. comp.: {}",
+ self.perf_stats.incr_comp_bytes_hashed.get()
+ );
if self.perf_stats.incr_comp_hashes_count.get() != 0 {
- println!("Average bytes hashed per incr. comp. HIR node: {}",
- self.perf_stats.incr_comp_bytes_hashed.get() /
- self.perf_stats.incr_comp_hashes_count.get());
+ println!(
+ "Average bytes hashed per incr. comp. HIR node: {}",
+ self.perf_stats.incr_comp_bytes_hashed.get()
+ / self.perf_stats.incr_comp_hashes_count.get()
+ );
} else {
println!("Average bytes hashed per incr. comp. HIR node: N/A");
}
- println!("Total time spent computing symbol hashes: {}",
- duration_to_secs_str(self.perf_stats.symbol_hash_time.get()));
- println!("Total time spent decoding DefPath tables: {}",
- duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get()));
+ println!(
+ "Total time spent computing symbol hashes: {}",
+ duration_to_secs_str(self.perf_stats.symbol_hash_time.get())
+ );
+ println!(
+ "Total time spent decoding DefPath tables: {}",
+ duration_to_secs_str(self.perf_stats.decode_def_path_tables_time.get())
+ );
}
/// We want to know if we're allowed to do an optimization for crate foo from -z fuel=foo=n.
println!("optimization-fuel-exhausted: {}", msg());
self.out_of_fuel.set(true);
} else if fuel > 0 {
- self.optimization_fuel_limit.set(fuel-1);
+ self.optimization_fuel_limit.set(fuel - 1);
}
}
_ => {}
}
match self.print_fuel_crate {
- Some(ref c) if c == crate_name=> {
- self.print_fuel.set(self.print_fuel.get()+1);
- },
+ Some(ref c) if c == crate_name => {
+ self.print_fuel.set(self.print_fuel.get() + 1);
+ }
_ => {}
}
ret
/// compilation
pub fn codegen_units(&self) -> usize {
if let Some(n) = self.opts.cli_forced_codegen_units {
- return n
+ return n;
}
if let Some(n) = self.target.target.options.default_codegen_units {
- return n as usize
+ return n as usize;
}
// Why is 16 codegen units the default all the time?
}
}
-pub fn build_session(sopts: config::Options,
- local_crate_source_file: Option<PathBuf>,
- registry: errors::registry::Registry)
- -> Session {
+pub fn build_session(
+ sopts: config::Options,
+ local_crate_source_file: Option<PathBuf>,
+ registry: errors::registry::Registry,
+) -> Session {
let file_path_mapping = sopts.file_path_mapping();
- build_session_with_codemap(sopts,
- local_crate_source_file,
- registry,
- Lrc::new(codemap::CodeMap::new(file_path_mapping)),
- None)
+ build_session_with_codemap(
+ sopts,
+ local_crate_source_file,
+ registry,
+ Lrc::new(codemap::CodeMap::new(file_path_mapping)),
+ None,
+ )
}
-pub fn build_session_with_codemap(sopts: config::Options,
- local_crate_source_file: Option<PathBuf>,
- registry: errors::registry::Registry,
- codemap: Lrc<codemap::CodeMap>,
- emitter_dest: Option<Box<dyn Write + Send>>)
- -> Session {
+pub fn build_session_with_codemap(
+ sopts: config::Options,
+ local_crate_source_file: Option<PathBuf>,
+ registry: errors::registry::Registry,
+ codemap: Lrc<codemap::CodeMap>,
+ emitter_dest: Option<Box<dyn Write + Send>>,
+) -> Session {
// FIXME: This is not general enough to make the warning lint completely override
// normal diagnostic warnings, since the warning lint can also be denied and changed
// later via the source code.
- let warnings_allow = sopts.lint_opts
+ let warnings_allow = sopts
+ .lint_opts
.iter()
.filter(|&&(ref key, _)| *key == "warnings")
.map(|&(_, ref level)| *level == lint::Allow)
let external_macro_backtrace = sopts.debugging_opts.external_macro_backtrace;
- let emitter: Box<dyn Emitter> = match (sopts.error_format, emitter_dest) {
- (config::ErrorOutputType::HumanReadable(color_config), None) => {
- Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()),
- false, sopts.debugging_opts.teach)
- .ui_testing(sopts.debugging_opts.ui_testing))
- }
- (config::ErrorOutputType::HumanReadable(_), Some(dst)) => {
- Box::new(EmitterWriter::new(dst, Some(codemap.clone()),
- false, false)
- .ui_testing(sopts.debugging_opts.ui_testing))
- }
- (config::ErrorOutputType::Json(pretty), None) => {
- Box::new(JsonEmitter::stderr(Some(registry), codemap.clone(),
- pretty, sopts.debugging_opts.approximate_suggestions)
- .ui_testing(sopts.debugging_opts.ui_testing))
- }
- (config::ErrorOutputType::Json(pretty), Some(dst)) => {
- Box::new(JsonEmitter::new(dst, Some(registry), codemap.clone(),
- pretty, sopts.debugging_opts.approximate_suggestions)
- .ui_testing(sopts.debugging_opts.ui_testing))
- }
- (config::ErrorOutputType::Short(color_config), None) => {
- Box::new(EmitterWriter::stderr(color_config, Some(codemap.clone()), true, false))
- }
- (config::ErrorOutputType::Short(_), Some(dst)) => {
- Box::new(EmitterWriter::new(dst, Some(codemap.clone()), true, false))
- }
- };
+ let emitter: Box<dyn Emitter> =
+ match (sopts.error_format, emitter_dest) {
+ (config::ErrorOutputType::HumanReadable(color_config), None) => Box::new(
+ EmitterWriter::stderr(
+ color_config,
+ Some(codemap.clone()),
+ false,
+ sopts.debugging_opts.teach,
+ ).ui_testing(sopts.debugging_opts.ui_testing),
+ ),
+ (config::ErrorOutputType::HumanReadable(_), Some(dst)) => Box::new(
+ EmitterWriter::new(dst, Some(codemap.clone()), false, false)
+ .ui_testing(sopts.debugging_opts.ui_testing),
+ ),
+ (config::ErrorOutputType::Json(pretty), None) => Box::new(
+ JsonEmitter::stderr(
+ Some(registry),
+ codemap.clone(),
+ pretty,
+ sopts.debugging_opts.approximate_suggestions,
+ ).ui_testing(sopts.debugging_opts.ui_testing),
+ ),
+ (config::ErrorOutputType::Json(pretty), Some(dst)) => Box::new(
+ JsonEmitter::new(
+ dst,
+ Some(registry),
+ codemap.clone(),
+ pretty,
+ sopts.debugging_opts.approximate_suggestions,
+ ).ui_testing(sopts.debugging_opts.ui_testing),
+ ),
+ (config::ErrorOutputType::Short(color_config), None) => Box::new(
+ EmitterWriter::stderr(color_config, Some(codemap.clone()), true, false),
+ ),
+ (config::ErrorOutputType::Short(_), Some(dst)) => {
+ Box::new(EmitterWriter::new(dst, Some(codemap.clone()), true, false))
+ }
+ };
- let diagnostic_handler =
- errors::Handler::with_emitter_and_flags(
- emitter,
- errors::HandlerFlags {
- can_emit_warnings,
- treat_err_as_bug,
- external_macro_backtrace,
- .. Default::default()
- });
+ let diagnostic_handler = errors::Handler::with_emitter_and_flags(
+ emitter,
+ errors::HandlerFlags {
+ can_emit_warnings,
+ treat_err_as_bug,
+ external_macro_backtrace,
+ ..Default::default()
+ },
+ );
- build_session_(sopts,
- local_crate_source_file,
- diagnostic_handler,
- codemap)
+ build_session_(sopts, local_crate_source_file, diagnostic_handler, codemap)
}
-pub fn build_session_(sopts: config::Options,
- local_crate_source_file: Option<PathBuf>,
- span_diagnostic: errors::Handler,
- codemap: Lrc<codemap::CodeMap>)
- -> Session {
+pub fn build_session_(
+ sopts: config::Options,
+ local_crate_source_file: Option<PathBuf>,
+ span_diagnostic: errors::Handler,
+ codemap: Lrc<codemap::CodeMap>,
+) -> Session {
let host = match Target::search(config::host_triple()) {
Ok(t) => t,
Err(e) => {
- span_diagnostic.fatal(&format!("Error loading host specification: {}", e)).raise();
+ span_diagnostic
+ .fatal(&format!("Error loading host specification: {}", e))
+ .raise();
}
};
let target_cfg = config::build_target_config(&sopts, &span_diagnostic);
let p_s = parse::ParseSess::with_span_handler(span_diagnostic, codemap);
let default_sysroot = match sopts.maybe_sysroot {
Some(_) => None,
- None => Some(filesearch::get_or_default_sysroot())
+ None => Some(filesearch::get_or_default_sysroot()),
};
let file_path_mapping = sopts.file_path_mapping();
- let local_crate_source_file = local_crate_source_file.map(|path| {
- file_path_mapping.map_prefix(path).0
- });
+ let local_crate_source_file =
+ local_crate_source_file.map(|path| file_path_mapping.map_prefix(path).0);
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()
- .map(|i| i.1).unwrap_or(0));
+ let optimization_fuel_limit =
+ Cell::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 working_dir = match env::current_dir() {
Ok(dir) => dir,
- Err(e) => {
- p_s.span_diagnostic.fatal(&format!("Current directory is invalid: {}", e)).raise()
- }
+ Err(e) => p_s.span_diagnostic
+ .fatal(&format!("Current directory is invalid: {}", e))
+ .raise(),
};
let working_dir = file_path_mapping.map_prefix(working_dir);
},
/// This is the state after the session directory has been finalized. In this
/// state, the contents of the directory must not be modified any more.
- Finalized {
- session_directory: PathBuf,
- },
+ Finalized { session_directory: PathBuf },
/// This is an error state that is reached when some compilation error has
/// occurred. It indicates that the contents of the session directory must
/// not be used, since they might be invalid.
- InvalidBecauseOfErrors {
- session_directory: PathBuf,
- }
+ InvalidBecauseOfErrors { session_directory: PathBuf },
}
pub fn early_error(output: config::ErrorOutputType, msg: &str) -> ! {
#[derive(Copy, Clone, Debug)]
pub enum CompileIncomplete {
Stopped,
- Errored(ErrorReported)
+ Errored(ErrorReported),
}
impl From<ErrorReported> for CompileIncomplete {
fn from(err: ErrorReported) -> CompileIncomplete {
#[cold]
#[inline(never)]
-pub fn span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
- line: u32,
- span: S,
- args: fmt::Arguments) -> ! {
+pub fn span_bug_fmt<S: Into<MultiSpan>>(
+ file: &'static str,
+ line: u32,
+ span: S,
+ args: fmt::Arguments,
+) -> ! {
opt_span_bug_fmt(file, line, Some(span), args);
}
-fn opt_span_bug_fmt<S: Into<MultiSpan>>(file: &'static str,
- line: u32,
- span: Option<S>,
- args: fmt::Arguments) -> ! {
+fn opt_span_bug_fmt<S: Into<MultiSpan>>(
+ file: &'static str,
+ line: u32,
+ span: Option<S>,
+ args: fmt::Arguments,
+) -> ! {
tls::with_opt(move |tcx| {
let msg = format!("{}:{}: {}", file, line, args);
match (tcx, span) {
(Some(tcx), Some(span)) => tcx.sess.diagnostic().span_bug(span, &msg),
(Some(tcx), None) => tcx.sess.diagnostic().bug(&msg),
- (None, _) => panic!(msg)
+ (None, _) => panic!(msg),
}
});
unreachable!();