1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Contains infrastructure for configuring the compiler, including parsing
12 //! command line options.
14 pub use self::EntryFnType::*;
15 pub use self::CrateType::*;
16 pub use self::Passes::*;
17 pub use self::DebugInfoLevel::*;
19 use session::{early_error, early_warn, Session};
20 use session::search_paths::SearchPaths;
22 use ich::StableHashingContext;
23 use rustc_back::{LinkerFlavor, PanicStrategy, RelroLevel};
24 use rustc_back::target::Target;
25 use rustc_data_structures::stable_hasher::ToStableHashKey;
29 use syntax::ast::{self, IntTy, UintTy};
30 use syntax::codemap::{FilePathMapping, FileName};
31 use syntax::parse::token;
33 use syntax::symbol::Symbol;
34 use syntax::feature_gate::UnstableFeatures;
36 use errors::{ColorConfig, FatalError, Handler};
39 use std::collections::{BTreeMap, BTreeSet};
40 use std::collections::btree_map::Iter as BTreeMapIter;
41 use std::collections::btree_map::Keys as BTreeMapKeysIter;
42 use std::collections::btree_map::Values as BTreeMapValuesIter;
45 use std::hash::Hasher;
46 use std::collections::hash_map::DefaultHasher;
47 use std::collections::HashSet;
48 use std::iter::FromIterator;
49 use std::path::PathBuf;
57 #[derive(Clone, Hash, Debug)]
65 #[derive(Clone, Copy, PartialEq, Hash)]
75 #[derive(Clone, Copy, PartialEq, Hash)]
76 pub enum DebugInfoLevel {
82 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord,
83 RustcEncodable, RustcDecodable)]
95 impl_stable_hash_for!(enum self::OutputType {
106 impl<'tcx> ToStableHashKey<StableHashingContext<'tcx>> for OutputType {
107 type KeyType = OutputType;
109 fn to_stable_hash_key(&self, _: &StableHashingContext<'tcx>) -> Self::KeyType {
115 fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
118 OutputType::DepInfo => true,
119 OutputType::Bitcode |
120 OutputType::Assembly |
121 OutputType::LlvmAssembly |
124 OutputType::Metadata => false,
128 fn shorthand(&self) -> &'static str {
130 OutputType::Bitcode => "llvm-bc",
131 OutputType::Assembly => "asm",
132 OutputType::LlvmAssembly => "llvm-ir",
133 OutputType::Mir => "mir",
134 OutputType::Object => "obj",
135 OutputType::Metadata => "metadata",
136 OutputType::Exe => "link",
137 OutputType::DepInfo => "dep-info",
141 fn from_shorthand(shorthand: &str) -> Option<Self> {
142 Some(match shorthand {
143 "asm" => OutputType::Assembly,
144 "llvm-ir" => OutputType::LlvmAssembly,
145 "mir" => OutputType::Mir,
146 "llvm-bc" => OutputType::Bitcode,
147 "obj" => OutputType::Object,
148 "metadata" => OutputType::Metadata,
149 "link" => OutputType::Exe,
150 "dep-info" => OutputType::DepInfo,
155 fn shorthands_display() -> String {
157 "`{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`",
158 OutputType::Bitcode.shorthand(),
159 OutputType::Assembly.shorthand(),
160 OutputType::LlvmAssembly.shorthand(),
161 OutputType::Mir.shorthand(),
162 OutputType::Object.shorthand(),
163 OutputType::Metadata.shorthand(),
164 OutputType::Exe.shorthand(),
165 OutputType::DepInfo.shorthand(),
169 pub fn extension(&self) -> &'static str {
171 OutputType::Bitcode => "bc",
172 OutputType::Assembly => "s",
173 OutputType::LlvmAssembly => "ll",
174 OutputType::Mir => "mir",
175 OutputType::Object => "o",
176 OutputType::Metadata => "rmeta",
177 OutputType::DepInfo => "d",
178 OutputType::Exe => "",
183 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
184 pub enum ErrorOutputType {
185 HumanReadable(ColorConfig),
190 impl Default for ErrorOutputType {
191 fn default() -> ErrorOutputType {
192 ErrorOutputType::HumanReadable(ColorConfig::Auto)
196 // Use tree-based collections to cheaply get a deterministic Hash implementation.
197 // DO NOT switch BTreeMap out for an unsorted container type! That would break
198 // dependency tracking for commandline arguments.
199 #[derive(Clone, Hash)]
200 pub struct OutputTypes(BTreeMap<OutputType, Option<PathBuf>>);
202 impl_stable_hash_for!(tuple_struct self::OutputTypes {
207 pub fn new(entries: &[(OutputType, Option<PathBuf>)]) -> OutputTypes {
208 OutputTypes(BTreeMap::from_iter(entries.iter()
209 .map(|&(k, ref v)| (k, v.clone()))))
212 pub fn get(&self, key: &OutputType) -> Option<&Option<PathBuf>> {
216 pub fn contains_key(&self, key: &OutputType) -> bool {
217 self.0.contains_key(key)
220 pub fn keys<'a>(&'a self) -> BTreeMapKeysIter<'a, OutputType, Option<PathBuf>> {
224 pub fn values<'a>(&'a self) -> BTreeMapValuesIter<'a, OutputType, Option<PathBuf>> {
228 // True if any of the output types require codegen or linking.
229 pub fn should_trans(&self) -> bool {
230 self.0.keys().any(|k| match *k {
231 OutputType::Bitcode |
232 OutputType::Assembly |
233 OutputType::LlvmAssembly |
236 OutputType::Exe => true,
237 OutputType::Metadata |
238 OutputType::DepInfo => false,
244 // Use tree-based collections to cheaply get a deterministic Hash implementation.
245 // DO NOT switch BTreeMap or BTreeSet out for an unsorted container type! That
246 // would break dependency tracking for commandline arguments.
247 #[derive(Clone, Hash)]
248 pub struct Externs(BTreeMap<String, BTreeSet<String>>);
251 pub fn new(data: BTreeMap<String, BTreeSet<String>>) -> Externs {
255 pub fn get(&self, key: &str) -> Option<&BTreeSet<String>> {
259 pub fn iter<'a>(&'a self) -> BTreeMapIter<'a, String, BTreeSet<String>> {
264 macro_rules! hash_option {
265 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [UNTRACKED]) => ({});
266 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({
267 if $sub_hashes.insert(stringify!($opt_name),
268 $opt_expr as &dep_tracking::DepTrackingHash).is_some() {
269 bug!("Duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
275 [UNTRACKED_WITH_WARNING $warn_val:expr, $warn_text:expr, $error_format:expr]) => ({
276 if *$opt_expr == $warn_val {
277 early_warn($error_format, $warn_text)
282 macro_rules! top_level_options {
283 (pub struct Options { $(
284 $opt:ident : $t:ty [$dep_tracking_marker:ident $($warn_val:expr, $warn_text:expr)*],
292 pub fn dep_tracking_hash(&self) -> u64 {
293 let mut sub_hashes = BTreeMap::new();
298 [$dep_tracking_marker $($warn_val,
300 self.error_format)*]);
302 let mut hasher = DefaultHasher::new();
303 dep_tracking::stable_hash(sub_hashes,
312 // The top-level commandline options struct
314 // For each option, one has to specify how it behaves with regard to the
315 // dependency tracking system of incremental compilation. This is done via the
316 // square-bracketed directive after the field type. The options are:
319 // A change in the given field will cause the compiler to completely clear the
320 // incremental compilation cache before proceeding.
323 // Incremental compilation is not influenced by this option.
325 // [UNTRACKED_WITH_WARNING(val, warning)]
326 // The option is incompatible with incremental compilation in some way. If it
327 // has the value `val`, the string `warning` is emitted as a warning.
329 // If you add a new option to this struct or one of the sub-structs like
330 // CodegenOptions, think about how it influences incremental compilation. If in
331 // doubt, specify [TRACKED], which is always "correct" but might lead to
332 // unnecessary re-compilation.
335 // The crate config requested for the session, which may be combined
336 // with additional crate configurations during the compile process
337 crate_types: Vec<CrateType> [TRACKED],
338 optimize: OptLevel [TRACKED],
339 // Include the debug_assertions flag into dependency tracking, since it
340 // can influence whether overflow checks are done or not.
341 debug_assertions: bool [TRACKED],
342 debuginfo: DebugInfoLevel [TRACKED],
343 lint_opts: Vec<(String, lint::Level)> [TRACKED],
344 lint_cap: Option<lint::Level> [TRACKED],
345 describe_lints: bool [UNTRACKED],
346 output_types: OutputTypes [TRACKED],
347 // FIXME(mw): We track this for now but it actually doesn't make too
348 // much sense: The search path can stay the same while the
349 // things discovered there might have changed on disk.
350 search_paths: SearchPaths [TRACKED],
351 libs: Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> [TRACKED],
352 maybe_sysroot: Option<PathBuf> [TRACKED],
354 target_triple: String [TRACKED],
356 test: bool [TRACKED],
357 error_format: ErrorOutputType [UNTRACKED],
359 // if Some, enable incremental compilation, using the given
360 // directory to store intermediate results
361 incremental: Option<PathBuf> [UNTRACKED],
363 debugging_opts: DebuggingOptions [TRACKED],
364 prints: Vec<PrintRequest> [UNTRACKED],
365 // Determines which borrow checker(s) to run. This is the parsed, sanitized
366 // version of `debugging_opts.borrowck`, which is just a plain string.
367 borrowck_mode: BorrowckMode [UNTRACKED],
368 cg: CodegenOptions [TRACKED],
369 // FIXME(mw): We track this for now but it actually doesn't make too
370 // much sense: The value of this option can stay the same
371 // while the files they refer to might have changed on disk.
372 externs: Externs [TRACKED],
373 crate_name: Option<String> [TRACKED],
374 // An optional name to use as the crate for std during std injection,
375 // written `extern crate std = "name"`. Default to "std". Used by
376 // out-of-tree drivers.
377 alt_std_name: Option<String> [TRACKED],
378 // Indicates how the compiler should treat unstable features
379 unstable_features: UnstableFeatures [TRACKED],
381 // Indicates whether this run of the compiler is actually rustdoc. This
382 // is currently just a hack and will be removed eventually, so please
383 // try to not rely on this too much.
384 actually_rustdoc: bool [TRACKED],
386 // Specifications of codegen units / ThinLTO which are forced as a
387 // result of parsing command line options. These are not necessarily
388 // what rustc was invoked with, but massaged a bit to agree with
389 // commands like `--emit llvm-ir` which they're often incompatible with
390 // if we otherwise use the defaults of rustc.
391 cli_forced_codegen_units: Option<usize> [UNTRACKED],
392 cli_forced_thinlto: Option<bool> [UNTRACKED],
396 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
397 pub enum PrintRequest {
412 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
413 pub enum BorrowckMode {
420 /// Should we emit the AST-based borrow checker errors?
421 pub fn use_ast(self) -> bool {
423 BorrowckMode::Ast => true,
424 BorrowckMode::Compare => true,
425 BorrowckMode::Mir => false,
428 /// Should we emit the MIR-based borrow checker errors?
429 pub fn use_mir(self) -> bool {
431 BorrowckMode::Ast => false,
432 BorrowckMode::Compare => true,
433 BorrowckMode::Mir => true,
439 /// Load source from file
442 /// String that is shown in place of a filename
444 /// Anonymous source string
450 pub fn filestem(&self) -> String {
452 Input::File(ref ifile) => ifile.file_stem().unwrap()
453 .to_str().unwrap().to_string(),
454 Input::Str { .. } => "rust_out".to_string(),
460 pub struct OutputFilenames {
461 pub out_directory: PathBuf,
462 pub out_filestem: String,
463 pub single_output_file: Option<PathBuf>,
465 pub outputs: OutputTypes,
468 impl_stable_hash_for!(struct self::OutputFilenames {
476 pub const RUST_CGU_EXT: &str = "rcgu";
478 impl OutputFilenames {
479 pub fn path(&self, flavor: OutputType) -> PathBuf {
480 self.outputs.get(&flavor).and_then(|p| p.to_owned())
481 .or_else(|| self.single_output_file.clone())
482 .unwrap_or_else(|| self.temp_path(flavor, None))
485 /// Get the path where a compilation artifact of the given type for the
486 /// given codegen unit should be placed on disk. If codegen_unit_name is
487 /// None, a path distinct from those of any codegen unit will be generated.
488 pub fn temp_path(&self,
490 codegen_unit_name: Option<&str>)
492 let extension = flavor.extension();
493 self.temp_path_ext(extension, codegen_unit_name)
496 /// Like temp_path, but also supports things where there is no corresponding
497 /// OutputType, like no-opt-bitcode or lto-bitcode.
498 pub fn temp_path_ext(&self,
500 codegen_unit_name: Option<&str>)
502 let base = self.out_directory.join(&self.filestem());
504 let mut extension = String::new();
506 if let Some(codegen_unit_name) = codegen_unit_name {
507 extension.push_str(codegen_unit_name);
511 if !extension.is_empty() {
512 extension.push_str(".");
513 extension.push_str(RUST_CGU_EXT);
514 extension.push_str(".");
517 extension.push_str(ext);
520 let path = base.with_extension(&extension[..]);
524 pub fn with_extension(&self, extension: &str) -> PathBuf {
525 self.out_directory.join(&self.filestem()).with_extension(extension)
528 pub fn filestem(&self) -> String {
529 format!("{}{}", self.out_filestem, self.extra)
532 pub fn contains_path(&self, input_path: &PathBuf) -> bool {
533 let input_path = input_path.canonicalize().ok();
534 if input_path.is_none() {
537 match self.single_output_file {
538 Some(ref output_path) => output_path.canonicalize().ok() == input_path,
540 for k in self.outputs.keys() {
541 let output_path = self.path(k.to_owned());
542 if output_path.canonicalize().ok() == input_path {
552 pub fn host_triple() -> &'static str {
553 // Get the host triple out of the build environment. This ensures that our
554 // idea of the host triple is the same as for the set of libraries we've
555 // actually built. We can't just take LLVM's host triple because they
556 // normalize all ix86 architectures to i386.
558 // Instead of grabbing the host triple (for the current host), we grab (at
559 // compile time) the target triple that this rustc is built with and
560 // calling that (at runtime) the host triple.
561 (option_env!("CFG_COMPILER_HOST_TRIPLE")).
562 expect("CFG_COMPILER_HOST_TRIPLE")
565 /// Some reasonable defaults
566 pub fn basic_options() -> Options {
568 crate_types: Vec::new(),
569 optimize: OptLevel::No,
570 debuginfo: NoDebugInfo,
571 lint_opts: Vec::new(),
573 describe_lints: false,
574 output_types: OutputTypes(BTreeMap::new()),
575 search_paths: SearchPaths::new(),
577 target_triple: host_triple().to_string(),
580 debugging_opts: basic_debugging_options(),
582 borrowck_mode: BorrowckMode::Ast,
583 cg: basic_codegen_options(),
584 error_format: ErrorOutputType::default(),
585 externs: Externs(BTreeMap::new()),
589 unstable_features: UnstableFeatures::Disallow,
590 debug_assertions: true,
591 actually_rustdoc: false,
592 cli_forced_codegen_units: None,
593 cli_forced_thinlto: None,
598 /// True if there is a reason to build the dep graph.
599 pub fn build_dep_graph(&self) -> bool {
600 self.incremental.is_some() ||
601 self.debugging_opts.dump_dep_graph ||
602 self.debugging_opts.query_dep_graph
606 pub fn enable_dep_node_debug_strs(&self) -> bool {
607 cfg!(debug_assertions) &&
608 (self.debugging_opts.query_dep_graph || self.debugging_opts.incremental_info)
611 pub fn file_path_mapping(&self) -> FilePathMapping {
612 FilePathMapping::new(
613 self.debugging_opts.remap_path_prefix_from.iter().zip(
614 self.debugging_opts.remap_path_prefix_to.iter()
615 ).map(|(src, dst)| (src.clone(), dst.clone())).collect()
619 /// True if there will be an output file generated
620 pub fn will_create_output_file(&self) -> bool {
621 !self.debugging_opts.parse_only && // The file is just being parsed
622 !self.debugging_opts.ls // The file is just being queried
626 // The type of entry function, so
627 // users can have their own entry
628 // functions that don't start a
630 #[derive(Copy, Clone, PartialEq)]
631 pub enum EntryFnType {
637 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
647 #[derive(Clone, Hash)]
649 SomePasses(Vec<String>),
654 pub fn is_empty(&self) -> bool {
656 SomePasses(ref v) => v.is_empty(),
662 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
663 /// at once. The goal of this macro is to define an interface that can be
664 /// programmatically used by the option parser in order to initialize the struct
665 /// without hardcoding field names all over the place.
667 /// The goal is to invoke this macro once with the correct fields, and then this
668 /// macro generates all necessary code. The main gotcha of this macro is the
669 /// cgsetters module which is a bunch of generated code to parse an option into
670 /// its respective field in the struct. There are a few hand-written parsers for
671 /// parsing specific types of values in this module.
672 macro_rules! options {
673 ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
674 $buildfn:ident, $prefix:expr, $outputname:expr,
675 $stat:ident, $mod_desc:ident, $mod_set:ident,
676 $($opt:ident : $t:ty = (
679 [$dep_tracking_marker:ident $(($dep_warn_val:expr, $dep_warn_text:expr))*],
684 pub struct $struct_name { $(pub $opt: $t),* }
686 pub fn $defaultfn() -> $struct_name {
687 $struct_name { $($opt: $init),* }
690 pub fn $buildfn(matches: &getopts::Matches, error_format: ErrorOutputType) -> $struct_name
692 let mut op = $defaultfn();
693 for option in matches.opt_strs($prefix) {
694 let mut iter = option.splitn(2, '=');
695 let key = iter.next().unwrap();
696 let value = iter.next();
697 let option_to_lookup = key.replace("-", "_");
698 let mut found = false;
699 for &(candidate, setter, opt_type_desc, _) in $stat {
700 if option_to_lookup != candidate { continue }
701 if !setter(&mut op, value) {
702 match (value, opt_type_desc) {
703 (Some(..), None) => {
704 early_error(error_format, &format!("{} option `{}` takes no \
705 value", $outputname, key))
707 (None, Some(type_desc)) => {
708 early_error(error_format, &format!("{0} option `{1}` requires \
709 {2} ({3} {1}=<value>)",
713 (Some(value), Some(type_desc)) => {
714 early_error(error_format, &format!("incorrect value `{}` for {} \
715 option `{}` - {} was expected",
719 (None, None) => bug!()
726 early_error(error_format, &format!("unknown {} option: `{}`",
733 impl<'a> dep_tracking::DepTrackingHash for $struct_name {
735 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
736 let mut sub_hashes = BTreeMap::new();
741 [$dep_tracking_marker $($dep_warn_val,
745 dep_tracking::stable_hash(sub_hashes, hasher, error_format);
749 pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
750 pub const $stat: &'static [(&'static str, $setter_name,
751 Option<&'static str>, &'static str)] =
752 &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
754 #[allow(non_upper_case_globals, dead_code)]
756 pub const parse_bool: Option<&'static str> = None;
757 pub const parse_opt_bool: Option<&'static str> =
758 Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
759 pub const parse_string: Option<&'static str> = Some("a string");
760 pub const parse_string_push: Option<&'static str> = Some("a string");
761 pub const parse_pathbuf_push: Option<&'static str> = Some("a path");
762 pub const parse_opt_string: Option<&'static str> = Some("a string");
763 pub const parse_opt_pathbuf: Option<&'static str> = Some("a path");
764 pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
765 pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
766 pub const parse_uint: Option<&'static str> = Some("a number");
767 pub const parse_passes: Option<&'static str> =
768 Some("a space-separated list of passes, or `all`");
769 pub const parse_opt_uint: Option<&'static str> =
771 pub const parse_panic_strategy: Option<&'static str> =
772 Some("either `panic` or `abort`");
773 pub const parse_relro_level: Option<&'static str> =
774 Some("one of: `full`, `partial`, or `off`");
775 pub const parse_sanitizer: Option<&'static str> =
776 Some("one of: `address`, `leak`, `memory` or `thread`");
777 pub const parse_linker_flavor: Option<&'static str> =
778 Some(::rustc_back::LinkerFlavor::one_of());
779 pub const parse_optimization_fuel: Option<&'static str> =
780 Some("crate=integer");
785 use super::{$struct_name, Passes, SomePasses, AllPasses, Sanitizer};
786 use rustc_back::{LinkerFlavor, PanicStrategy, RelroLevel};
787 use std::path::PathBuf;
790 pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
791 $parse(&mut cg.$opt, v)
795 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
798 None => { *slot = true; true }
802 fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
806 "n" | "no" | "off" => {
809 "y" | "yes" | "on" => {
812 _ => { return false; }
817 None => { *slot = Some(true); true }
821 fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
823 Some(s) => { *slot = Some(s.to_string()); true },
828 fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
830 Some(s) => { *slot = Some(PathBuf::from(s)); true },
835 fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
837 Some(s) => { *slot = s.to_string(); true },
842 fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
844 Some(s) => { slot.push(s.to_string()); true },
849 fn parse_pathbuf_push(slot: &mut Vec<PathBuf>, v: Option<&str>) -> bool {
851 Some(s) => { slot.push(PathBuf::from(s)); true },
856 fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
860 for s in s.split_whitespace() {
861 slot.push(s.to_string());
869 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
873 let v = s.split_whitespace().map(|s| s.to_string()).collect();
881 fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
882 match v.and_then(|s| s.parse().ok()) {
883 Some(i) => { *slot = i; true },
888 fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
890 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
891 None => { *slot = None; false }
895 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
902 let mut passes = vec![];
903 if parse_list(&mut passes, v) {
904 *slot = SomePasses(passes);
913 fn parse_panic_strategy(slot: &mut Option<PanicStrategy>, v: Option<&str>) -> bool {
915 Some("unwind") => *slot = Some(PanicStrategy::Unwind),
916 Some("abort") => *slot = Some(PanicStrategy::Abort),
922 fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
925 match s.parse::<RelroLevel>() {
926 Ok(level) => *slot = Some(level),
935 fn parse_sanitizer(slote: &mut Option<Sanitizer>, v: Option<&str>) -> bool {
937 Some("address") => *slote = Some(Sanitizer::Address),
938 Some("leak") => *slote = Some(Sanitizer::Leak),
939 Some("memory") => *slote = Some(Sanitizer::Memory),
940 Some("thread") => *slote = Some(Sanitizer::Thread),
946 fn parse_linker_flavor(slote: &mut Option<LinkerFlavor>, v: Option<&str>) -> bool {
947 match v.and_then(LinkerFlavor::from_str) {
948 Some(lf) => *slote = Some(lf),
954 fn parse_optimization_fuel(slot: &mut Option<(String, u64)>, v: Option<&str>) -> bool {
958 let parts = s.split('=').collect::<Vec<_>>();
959 if parts.len() != 2 { return false; }
960 let crate_name = parts[0].to_string();
961 let fuel = parts[1].parse::<u64>();
962 if fuel.is_err() { return false; }
963 *slot = Some((crate_name, fuel.unwrap()));
971 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
972 build_codegen_options, "C", "codegen",
973 CG_OPTIONS, cg_type_desc, cgsetters,
974 ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
975 "this option is deprecated and does nothing"),
976 linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
977 "system linker to link outputs with"),
978 link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
979 "a single extra argument to append to the linker invocation (can be used several times)"),
980 link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
981 "extra arguments to append to the linker invocation (space separated)"),
982 link_dead_code: bool = (false, parse_bool, [UNTRACKED],
983 "don't let linker strip dead code (turning it on can be used for code coverage)"),
984 lto: bool = (false, parse_bool, [TRACKED],
985 "perform LLVM link-time optimizations"),
986 target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
987 "select target processor (rustc --print target-cpus for details)"),
988 target_feature: String = ("".to_string(), parse_string, [TRACKED],
989 "target specific attributes (rustc --print target-features for details)"),
990 passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
991 "a list of extra LLVM passes to run (space separated)"),
992 llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
993 "a list of arguments to pass to llvm (space separated)"),
994 save_temps: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
995 "`-C save-temps` might not produce all requested temporary products \
996 when incremental compilation is enabled.")],
997 "save all temporary output files during compilation"),
998 rpath: bool = (false, parse_bool, [UNTRACKED],
999 "set rpath values in libs/exes"),
1000 overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1001 "use overflow checks for integer arithmetic"),
1002 no_prepopulate_passes: bool = (false, parse_bool, [TRACKED],
1003 "don't pre-populate the pass manager with a list of passes"),
1004 no_vectorize_loops: bool = (false, parse_bool, [TRACKED],
1005 "don't run the loop vectorization optimization passes"),
1006 no_vectorize_slp: bool = (false, parse_bool, [TRACKED],
1007 "don't run LLVM's SLP vectorization pass"),
1008 soft_float: bool = (false, parse_bool, [TRACKED],
1009 "use soft float ABI (*eabihf targets only)"),
1010 prefer_dynamic: bool = (false, parse_bool, [TRACKED],
1011 "prefer dynamic linking to static linking"),
1012 no_integrated_as: bool = (false, parse_bool, [TRACKED],
1013 "use an external assembler rather than LLVM's integrated one"),
1014 no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
1015 "disable the use of the redzone"),
1016 relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
1017 "choose the relocation model to use (rustc --print relocation-models for details)"),
1018 code_model: Option<String> = (None, parse_opt_string, [TRACKED],
1019 "choose the code model to use (rustc --print code-models for details)"),
1020 metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1021 "metadata to mangle symbol names with"),
1022 extra_filename: String = ("".to_string(), parse_string, [UNTRACKED],
1023 "extra data to put in each output filename"),
1024 codegen_units: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1025 "divide crate into N units to optimize in parallel"),
1026 remark: Passes = (SomePasses(Vec::new()), parse_passes, [UNTRACKED],
1027 "print remarks for these optimization passes (space separated, or \"all\")"),
1028 no_stack_check: bool = (false, parse_bool, [UNTRACKED],
1029 "the --no-stack-check flag is deprecated and does nothing"),
1030 debuginfo: Option<usize> = (None, parse_opt_uint, [TRACKED],
1031 "debug info emission level, 0 = no debug info, 1 = line tables only, \
1032 2 = full debug info with variable and type information"),
1033 opt_level: Option<String> = (None, parse_opt_string, [TRACKED],
1034 "optimize with possible levels 0-3, s, or z"),
1035 debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
1036 "explicitly enable the cfg(debug_assertions) directive"),
1037 inline_threshold: Option<usize> = (None, parse_opt_uint, [TRACKED],
1038 "set the threshold for inlining a function (default: 225)"),
1039 panic: Option<PanicStrategy> = (None, parse_panic_strategy,
1040 [TRACKED], "panic strategy to compile crate with"),
1041 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1042 "enable incremental compilation"),
1045 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
1046 build_debugging_options, "Z", "debugging",
1047 DB_OPTIONS, db_type_desc, dbsetters,
1048 codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
1049 "the backend to use"),
1050 verbose: bool = (false, parse_bool, [UNTRACKED],
1051 "in general, enable more debug printouts"),
1052 span_free_formats: bool = (false, parse_bool, [UNTRACKED],
1053 "when debug-printing compiler state, do not include spans"), // o/w tests have closure@path
1054 identify_regions: bool = (false, parse_bool, [UNTRACKED],
1055 "make unnamed regions display as '# (where # is some non-ident unique id)"),
1056 emit_end_regions: bool = (false, parse_bool, [UNTRACKED],
1057 "emit EndRegion as part of MIR; enable transforms that solely process EndRegion"),
1058 borrowck: Option<String> = (None, parse_opt_string, [UNTRACKED],
1059 "select which borrowck is used (`ast`, `mir`, or `compare`)"),
1060 two_phase_borrows: bool = (false, parse_bool, [UNTRACKED],
1061 "use two-phase reserved/active distinction for `&mut` borrows in MIR borrowck"),
1062 time_passes: bool = (false, parse_bool, [UNTRACKED],
1063 "measure time of each rustc pass"),
1064 count_llvm_insns: bool = (false, parse_bool,
1065 [UNTRACKED_WITH_WARNING(true,
1066 "The output generated by `-Z count_llvm_insns` might not be reliable \
1067 when used with incremental compilation")],
1068 "count where LLVM instrs originate"),
1069 time_llvm_passes: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1070 "The output of `-Z time-llvm-passes` will only reflect timings of \
1071 re-translated modules when used with incremental compilation" )],
1072 "measure time of each LLVM pass"),
1073 input_stats: bool = (false, parse_bool, [UNTRACKED],
1074 "gather statistics about the input"),
1075 trans_stats: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1076 "The output of `-Z trans-stats` might not be accurate when incremental \
1077 compilation is enabled")],
1078 "gather trans statistics"),
1079 asm_comments: bool = (false, parse_bool, [TRACKED],
1080 "generate comments into the assembly (may change behavior)"),
1081 no_verify: bool = (false, parse_bool, [TRACKED],
1082 "skip LLVM verification"),
1083 borrowck_stats: bool = (false, parse_bool, [UNTRACKED],
1084 "gather borrowck statistics"),
1085 no_landing_pads: bool = (false, parse_bool, [TRACKED],
1086 "omit landing pads for unwinding"),
1087 fewer_names: bool = (false, parse_bool, [TRACKED],
1088 "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR)"),
1089 meta_stats: bool = (false, parse_bool, [UNTRACKED],
1090 "gather metadata statistics"),
1091 print_link_args: bool = (false, parse_bool, [UNTRACKED],
1092 "print the arguments passed to the linker"),
1093 print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1094 "prints the llvm optimization passes being run"),
1095 ast_json: bool = (false, parse_bool, [UNTRACKED],
1096 "print the AST as JSON and halt"),
1097 query_threads: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1098 "execute queries on a thread pool with N threads"),
1099 ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
1100 "print the pre-expansion AST as JSON and halt"),
1101 ls: bool = (false, parse_bool, [UNTRACKED],
1102 "list the symbols defined by a library crate"),
1103 save_analysis: bool = (false, parse_bool, [UNTRACKED],
1104 "write syntax and type analysis (in JSON format) information, in \
1105 addition to normal output"),
1106 flowgraph_print_loans: bool = (false, parse_bool, [UNTRACKED],
1107 "include loan analysis data in --unpretty flowgraph output"),
1108 flowgraph_print_moves: bool = (false, parse_bool, [UNTRACKED],
1109 "include move analysis data in --unpretty flowgraph output"),
1110 flowgraph_print_assigns: bool = (false, parse_bool, [UNTRACKED],
1111 "include assignment analysis data in --unpretty flowgraph output"),
1112 flowgraph_print_all: bool = (false, parse_bool, [UNTRACKED],
1113 "include all dataflow analysis data in --unpretty flowgraph output"),
1114 print_region_graph: bool = (false, parse_bool, [UNTRACKED],
1115 "prints region inference graph. \
1116 Use with RUST_REGION_GRAPH=help for more info"),
1117 parse_only: bool = (false, parse_bool, [UNTRACKED],
1118 "parse only; do not compile, assemble, or link"),
1119 no_trans: bool = (false, parse_bool, [TRACKED],
1120 "run all passes except translation; no output"),
1121 treat_err_as_bug: bool = (false, parse_bool, [TRACKED],
1122 "treat all errors that occur as bugs"),
1123 external_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1124 "show macro backtraces even for non-local macros"),
1125 teach: bool = (false, parse_bool, [TRACKED],
1126 "show extended diagnostic help"),
1127 continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
1128 "attempt to recover from parse errors (experimental)"),
1129 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1130 "enable incremental compilation (experimental)"),
1131 incremental_queries: bool = (true, parse_bool, [UNTRACKED],
1132 "enable incremental compilation support for queries (experimental)"),
1133 incremental_info: bool = (false, parse_bool, [UNTRACKED],
1134 "print high-level information about incremental reuse (or the lack thereof)"),
1135 incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
1136 "dump hash information in textual format to stdout"),
1137 incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
1138 "verify incr. comp. hashes of green query instances"),
1139 incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
1140 "ignore spans during ICH computation -- used for testing"),
1141 dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1142 "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
1143 query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1144 "enable queries of the dependency graph for regression testing"),
1145 profile_queries: bool = (false, parse_bool, [UNTRACKED],
1146 "trace and profile the queries of the incremental compilation framework"),
1147 profile_queries_and_keys: bool = (false, parse_bool, [UNTRACKED],
1148 "trace and profile the queries and keys of the incremental compilation framework"),
1149 no_analysis: bool = (false, parse_bool, [UNTRACKED],
1150 "parse and expand the source, but run no analysis"),
1151 extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1152 "load extra plugins"),
1153 unstable_options: bool = (false, parse_bool, [UNTRACKED],
1154 "adds unstable command line options to rustc interface"),
1155 force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1156 "force overflow checks on or off"),
1157 trace_macros: bool = (false, parse_bool, [UNTRACKED],
1158 "for every macro invocation, print its name and arguments"),
1159 debug_macros: bool = (false, parse_bool, [TRACKED],
1160 "emit line numbers debug info inside macros"),
1161 enable_nonzeroing_move_hints: bool = (false, parse_bool, [TRACKED],
1162 "force nonzeroing move optimization on"),
1163 keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
1164 "don't clear the hygiene data after analysis"),
1165 keep_ast: bool = (false, parse_bool, [UNTRACKED],
1166 "keep the AST after lowering it to HIR"),
1167 show_span: Option<String> = (None, parse_opt_string, [TRACKED],
1168 "show spans for compiler debugging (expr|pat|ty)"),
1169 print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
1170 "print layout information for each type encountered"),
1171 print_trans_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
1172 "print the result of the translation item collection pass"),
1173 mir_opt_level: usize = (1, parse_uint, [TRACKED],
1174 "set the MIR optimization level (0-3, default: 1)"),
1175 mutable_noalias: bool = (false, parse_bool, [UNTRACKED],
1176 "emit noalias metadata for mutable references"),
1177 dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1178 "dump MIR state at various points in translation"),
1179 dump_mir_dir: String = (String::from("mir_dump"), parse_string, [UNTRACKED],
1180 "the directory the MIR is dumped into"),
1181 dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
1182 "in addition to `.mir` files, create graphviz `.dot` files"),
1183 dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
1184 "if set, exclude the pass number when dumping MIR (used in tests)"),
1185 mir_emit_validate: usize = (0, parse_uint, [TRACKED],
1186 "emit Validate MIR statements, interpreted e.g. by miri (0: do not emit; 1: if function \
1187 contains unsafe block, only validate arguments; 2: always emit full validation)"),
1188 perf_stats: bool = (false, parse_bool, [UNTRACKED],
1189 "print some performance-related statistics"),
1190 hir_stats: bool = (false, parse_bool, [UNTRACKED],
1191 "print some statistics about AST and HIR"),
1192 mir_stats: bool = (false, parse_bool, [UNTRACKED],
1193 "print some statistics about MIR"),
1194 always_encode_mir: bool = (false, parse_bool, [TRACKED],
1195 "encode MIR of all functions into the crate metadata"),
1196 miri: bool = (false, parse_bool, [TRACKED],
1197 "check the miri const evaluator against the old ctfe"),
1198 osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
1199 "pass `-install_name @rpath/...` to the macOS linker"),
1200 sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
1202 linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
1204 fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
1205 "set the optimization fuel quota for a crate"),
1206 print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
1207 "make Rustc print the total optimization fuel used by a crate"),
1208 remap_path_prefix_from: Vec<PathBuf> = (vec![], parse_pathbuf_push, [TRACKED],
1209 "add a source pattern to the file path remapping config"),
1210 remap_path_prefix_to: Vec<PathBuf> = (vec![], parse_pathbuf_push, [TRACKED],
1211 "add a mapping target to the file path remapping config"),
1212 force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
1213 "force all crates to be `rustc_private` unstable"),
1214 pre_link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1215 "a single extra argument to prepend the linker invocation (can be used several times)"),
1216 pre_link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1217 "extra arguments to prepend to the linker invocation (space separated)"),
1218 profile: bool = (false, parse_bool, [TRACKED],
1219 "insert profiling code"),
1220 relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
1221 "choose which RELRO level to use"),
1222 nll: bool = (false, parse_bool, [UNTRACKED],
1223 "run the non-lexical lifetimes MIR pass"),
1224 nll_dump_cause: bool = (false, parse_bool, [UNTRACKED],
1225 "dump cause information when reporting errors from NLL"),
1226 trans_time_graph: bool = (false, parse_bool, [UNTRACKED],
1227 "generate a graphical HTML report of time spent in trans and LLVM"),
1228 thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
1229 "enable ThinLTO when possible"),
1230 inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
1231 "control whether #[inline] functions are in all cgus"),
1232 tls_model: Option<String> = (None, parse_opt_string, [TRACKED],
1233 "choose the TLS model to use (rustc --print tls-models for details)"),
1234 saturating_float_casts: bool = (false, parse_bool, [TRACKED],
1235 "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
1236 the max/min integer respectively, and NaN is mapped to 0"),
1237 lower_128bit_ops: Option<bool> = (None, parse_opt_bool, [TRACKED],
1238 "rewrite operators on i128 and u128 into lang item calls (typically provided \
1239 by compiler-builtins) so translation doesn't need to support them,
1240 overriding the default for the current target"),
1241 human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
1242 "generate human-readable, predictable names for codegen units"),
1243 dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
1244 "in dep-info output, omit targets for tracking dependencies of the dep-info files \
1248 pub fn default_lib_output() -> CrateType {
1252 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
1253 let end = &sess.target.target.target_endian;
1254 let arch = &sess.target.target.arch;
1255 let wordsz = &sess.target.target.target_pointer_width;
1256 let os = &sess.target.target.target_os;
1257 let env = &sess.target.target.target_env;
1258 let vendor = &sess.target.target.target_vendor;
1259 let min_atomic_width = sess.target.target.min_atomic_width();
1260 let max_atomic_width = sess.target.target.max_atomic_width();
1262 let mut ret = HashSet::new();
1264 ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
1265 if let Some(ref fam) = sess.target.target.options.target_family {
1266 ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam))));
1267 if fam == "windows" || fam == "unix" {
1268 ret.insert((Symbol::intern(fam), None));
1271 ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
1272 ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
1273 ret.insert((Symbol::intern("target_pointer_width"), Some(Symbol::intern(wordsz))));
1274 ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
1275 ret.insert((Symbol::intern("target_vendor"), Some(Symbol::intern(vendor))));
1276 if sess.target.target.options.has_elf_tls {
1277 ret.insert((Symbol::intern("target_thread_local"), None));
1279 for &i in &[8, 16, 32, 64, 128] {
1280 if i >= min_atomic_width && i <= max_atomic_width {
1281 let s = i.to_string();
1282 ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern(&s))));
1284 ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern("ptr"))));
1288 if sess.opts.debug_assertions {
1289 ret.insert((Symbol::intern("debug_assertions"), None));
1291 if sess.opts.crate_types.contains(&CrateTypeProcMacro) {
1292 ret.insert((Symbol::intern("proc_macro"), None));
1297 pub fn build_configuration(sess: &Session,
1298 mut user_cfg: ast::CrateConfig)
1299 -> ast::CrateConfig {
1300 // Combine the configuration requested by the session (command line) with
1301 // some default and generated configuration items
1302 let default_cfg = default_configuration(sess);
1303 // If the user wants a test runner, then add the test cfg
1305 user_cfg.insert((Symbol::intern("test"), None));
1307 user_cfg.extend(default_cfg.iter().cloned());
1311 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
1312 let target = match Target::search(&opts.target_triple) {
1315 sp.struct_fatal(&format!("Error loading target specification: {}", e))
1316 .help("Use `--print target-list` for a list of built-in targets")
1322 let (isize_ty, usize_ty) = match &target.target_pointer_width[..] {
1323 "16" => (ast::IntTy::I16, ast::UintTy::U16),
1324 "32" => (ast::IntTy::I32, ast::UintTy::U32),
1325 "64" => (ast::IntTy::I64, ast::UintTy::U64),
1326 w => panic!(sp.fatal(&format!("target specification was invalid: \
1327 unrecognized target-pointer-width {}", w))),
1337 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1338 pub enum OptionStability {
1344 pub struct RustcOptGroup {
1345 pub apply: Box<Fn(&mut getopts::Options) -> &mut getopts::Options>,
1346 pub name: &'static str,
1347 pub stability: OptionStability,
1350 impl RustcOptGroup {
1351 pub fn is_stable(&self) -> bool {
1352 self.stability == OptionStability::Stable
1355 pub fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
1356 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1361 stability: OptionStability::Stable,
1365 pub fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
1366 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1371 stability: OptionStability::Unstable,
1376 // The `opt` local module holds wrappers around the `getopts` API that
1377 // adds extra rustc-specific metadata to each option; such metadata
1378 // is exposed by . The public
1379 // functions below ending with `_u` are the functions that return
1380 // *unstable* options, i.e. options that are only enabled when the
1381 // user also passes the `-Z unstable-options` debugging flag.
1383 // The `fn opt_u` etc below are written so that we can use them
1384 // in the future; do not warn about them not being used right now.
1385 #![allow(dead_code)]
1388 use super::RustcOptGroup;
1390 pub type R = RustcOptGroup;
1391 pub type S = &'static str;
1393 fn stable<F>(name: S, f: F) -> R
1394 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
1396 RustcOptGroup::stable(name, f)
1399 fn unstable<F>(name: S, f: F) -> R
1400 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
1402 RustcOptGroup::unstable(name, f)
1405 fn longer(a: S, b: S) -> S {
1406 if a.len() > b.len() {
1413 pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
1414 stable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1416 pub fn multi_s(a: S, b: S, c: S, d: S) -> R {
1417 stable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1419 pub fn flag_s(a: S, b: S, c: S) -> R {
1420 stable(longer(a, b), move |opts| opts.optflag(a, b, c))
1422 pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R {
1423 stable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1425 pub fn flagmulti_s(a: S, b: S, c: S) -> R {
1426 stable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1429 pub fn opt(a: S, b: S, c: S, d: S) -> R {
1430 unstable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1432 pub fn multi(a: S, b: S, c: S, d: S) -> R {
1433 unstable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1435 pub fn flag(a: S, b: S, c: S) -> R {
1436 unstable(longer(a, b), move |opts| opts.optflag(a, b, c))
1438 pub fn flagopt(a: S, b: S, c: S, d: S) -> R {
1439 unstable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1441 pub fn flagmulti(a: S, b: S, c: S) -> R {
1442 unstable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1446 /// Returns the "short" subset of the rustc command line options,
1447 /// including metadata for each option, such as whether the option is
1448 /// part of the stable long-term interface for rustc.
1449 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
1451 opt::flag_s("h", "help", "Display this message"),
1452 opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
1453 opt::multi_s("L", "", "Add a directory to the library search path. The
1454 optional KIND can be one of dependency, crate, native,
1455 framework or all (the default).", "[KIND=]PATH"),
1456 opt::multi_s("l", "", "Link the generated crate(s) to the specified native
1457 library NAME. The optional KIND can be one of
1458 static, dylib, or framework. If omitted, dylib is
1459 assumed.", "[KIND=]NAME"),
1460 opt::multi_s("", "crate-type", "Comma separated list of types of crates
1461 for the compiler to emit",
1462 "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]"),
1463 opt::opt_s("", "crate-name", "Specify the name of the crate being built",
1465 opt::multi_s("", "emit", "Comma separated list of types of output for \
1466 the compiler to emit",
1467 "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]"),
1468 opt::multi_s("", "print", "Comma separated list of compiler information to \
1470 "[crate-name|file-names|sysroot|cfg|target-list|\
1471 target-cpus|target-features|relocation-models|\
1472 code-models|tls-models|target-spec-json|native-static-libs]"),
1473 opt::flagmulti_s("g", "", "Equivalent to -C debuginfo=2"),
1474 opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
1475 opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
1476 opt::opt_s("", "out-dir", "Write output to compiler-chosen filename \
1478 opt::opt_s("", "explain", "Provide a detailed explanation of an error \
1480 opt::flag_s("", "test", "Build a test harness"),
1481 opt::opt_s("", "target", "Target triple for which the code is compiled", "TARGET"),
1482 opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
1483 opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
1484 opt::multi_s("D", "deny", "Set lint denied", "OPT"),
1485 opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
1486 opt::multi_s("", "cap-lints", "Set the most restrictive lint level. \
1487 More restrictive lints are capped at this \
1489 opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
1490 opt::flag_s("V", "version", "Print version info and exit"),
1491 opt::flag_s("v", "verbose", "Use verbose output"),
1495 /// Returns all rustc command line options, including metadata for
1496 /// each option, such as whether the option is part of the stable
1497 /// long-term interface for rustc.
1498 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
1499 let mut opts = rustc_short_optgroups();
1501 opt::multi_s("", "extern", "Specify where an external rust library is located",
1503 opt::opt_s("", "sysroot", "Override the system root", "PATH"),
1504 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
1505 opt::opt_s("", "error-format",
1506 "How errors and other messages are produced",
1507 "human|json|short"),
1508 opt::opt_s("", "color", "Configure coloring of output:
1509 auto = colorize, if output goes to a tty (default);
1510 always = always colorize output;
1511 never = never colorize output", "auto|always|never"),
1513 opt::opt("", "pretty",
1514 "Pretty-print the input instead of compiling;
1515 valid types are: `normal` (un-annotated source),
1516 `expanded` (crates expanded), or
1517 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
1519 opt::opt("", "unpretty",
1520 "Present the input source, unstable (and less-pretty) variants;
1521 valid types are any of the types for `--pretty`, as well as:
1522 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
1523 `everybody_loops` (all function bodies replaced with `loop {}`),
1524 `hir` (the HIR), `hir,identified`, or
1525 `hir,typed` (HIR with types for each node).",
1531 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
1532 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
1533 cfgspecs.into_iter().map(|s| {
1534 let sess = parse::ParseSess::new(FilePathMapping::empty());
1536 parse::new_parser_from_source_str(&sess, FileName::CfgSpec, s.to_string());
1538 let meta_item = panictry!(parser.parse_meta_item());
1540 if parser.token != token::Eof {
1541 early_error(ErrorOutputType::default(), &format!("invalid --cfg argument: {}", s))
1542 } else if meta_item.is_meta_item_list() {
1544 format!("invalid predicate in --cfg command line argument: `{}`", meta_item.name());
1545 early_error(ErrorOutputType::default(), &msg)
1548 (meta_item.name(), meta_item.value_str())
1549 }).collect::<ast::CrateConfig>()
1552 pub fn build_session_options_and_crate_config(matches: &getopts::Matches)
1553 -> (Options, ast::CrateConfig) {
1554 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
1555 Some("auto") => ColorConfig::Auto,
1556 Some("always") => ColorConfig::Always,
1557 Some("never") => ColorConfig::Never,
1559 None => ColorConfig::Auto,
1562 early_error(ErrorOutputType::default(), &format!("argument for --color must be auto, \
1563 always or never (instead was `{}`)",
1568 // We need the opts_present check because the driver will send us Matches
1569 // with only stable options if no unstable options are used. Since error-format
1570 // is unstable, it will not be present. We have to use opts_present not
1571 // opt_present because the latter will panic.
1572 let error_format = if matches.opts_present(&["error-format".to_owned()]) {
1573 match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
1574 Some("human") => ErrorOutputType::HumanReadable(color),
1575 Some("json") => ErrorOutputType::Json(false),
1576 Some("pretty-json") => ErrorOutputType::Json(true),
1578 if nightly_options::is_unstable_enabled(matches) {
1579 ErrorOutputType::Short(color)
1581 early_error(ErrorOutputType::default(),
1582 &format!("the `-Z unstable-options` flag must also be passed to \
1583 enable the short error message option"));
1586 None => ErrorOutputType::HumanReadable(color),
1589 early_error(ErrorOutputType::HumanReadable(color),
1590 &format!("argument for --error-format must be `human`, `json` or \
1591 `short` (instead was `{}`)",
1596 ErrorOutputType::HumanReadable(color)
1599 let unparsed_crate_types = matches.opt_strs("crate-type");
1600 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
1601 .unwrap_or_else(|e| early_error(error_format, &e[..]));
1603 let mut lint_opts = vec![];
1604 let mut describe_lints = false;
1606 for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
1607 for lint_name in matches.opt_strs(level.as_str()) {
1608 if lint_name == "help" {
1609 describe_lints = true;
1611 lint_opts.push((lint_name.replace("-", "_"), level));
1616 let lint_cap = matches.opt_str("cap-lints").map(|cap| {
1617 lint::Level::from_str(&cap).unwrap_or_else(|| {
1618 early_error(error_format, &format!("unknown lint level: `{}`", cap))
1622 let mut debugging_opts = build_debugging_options(matches, error_format);
1624 if !debugging_opts.unstable_options && error_format == ErrorOutputType::Json(true) {
1625 early_error(ErrorOutputType::Json(false), "--error-format=pretty-json is unstable");
1628 let mut output_types = BTreeMap::new();
1629 if !debugging_opts.parse_only {
1630 for list in matches.opt_strs("emit") {
1631 for output_type in list.split(',') {
1632 let mut parts = output_type.splitn(2, '=');
1633 let shorthand = parts.next().unwrap();
1634 let output_type = match OutputType::from_shorthand(shorthand) {
1635 Some(output_type) => output_type,
1636 None => early_error(error_format, &format!(
1637 "unknown emission type: `{}` - expected one of: {}",
1638 shorthand, OutputType::shorthands_display(),
1641 let path = parts.next().map(PathBuf::from);
1642 output_types.insert(output_type, path);
1646 if output_types.is_empty() {
1647 output_types.insert(OutputType::Exe, None);
1650 let remap_path_prefix_sources = debugging_opts.remap_path_prefix_from.len();
1651 let remap_path_prefix_targets = debugging_opts.remap_path_prefix_from.len();
1653 if remap_path_prefix_targets < remap_path_prefix_sources {
1654 for source in &debugging_opts.remap_path_prefix_from[remap_path_prefix_targets..] {
1655 early_error(error_format,
1656 &format!("option `-Zremap-path-prefix-from='{}'` does not have \
1657 a corresponding `-Zremap-path-prefix-to`", source.display()))
1659 } else if remap_path_prefix_targets > remap_path_prefix_sources {
1660 for target in &debugging_opts.remap_path_prefix_to[remap_path_prefix_sources..] {
1661 early_error(error_format,
1662 &format!("option `-Zremap-path-prefix-to='{}'` does not have \
1663 a corresponding `-Zremap-path-prefix-from`", target.display()))
1667 let mut cg = build_codegen_options(matches, error_format);
1668 let mut codegen_units = cg.codegen_units;
1669 let mut thinlto = None;
1671 // Issue #30063: if user requests llvm-related output to one
1672 // particular path, disable codegen-units.
1673 let incompatible: Vec<_> = output_types.iter()
1674 .map(|ot_path| ot_path.0)
1676 !ot.is_compatible_with_codegen_units_and_single_output_file()
1678 .map(|ot| ot.shorthand())
1680 if !incompatible.is_empty() {
1681 match codegen_units {
1682 Some(n) if n > 1 => {
1683 if matches.opt_present("o") {
1684 for ot in &incompatible {
1685 early_warn(error_format, &format!("--emit={} with -o incompatible with \
1686 -C codegen-units=N for N > 1",
1689 early_warn(error_format, "resetting to default -C codegen-units=1");
1690 codegen_units = Some(1);
1691 thinlto = Some(false);
1695 codegen_units = Some(1);
1696 thinlto = Some(false);
1701 if debugging_opts.query_threads == Some(0) {
1702 early_error(error_format, "Value for query threads must be a positive nonzero integer");
1705 if codegen_units == Some(0) {
1706 early_error(error_format, "Value for codegen units must be a positive nonzero integer");
1709 let incremental = match (&debugging_opts.incremental, &cg.incremental) {
1710 (&Some(ref path1), &Some(ref path2)) => {
1712 early_error(error_format,
1713 &format!("conflicting paths for `-Z incremental` and \
1714 `-C incremental` specified: {} versus {}",
1721 (&Some(ref path), &None) => Some(path),
1722 (&None, &Some(ref path)) => Some(path),
1723 (&None, &None) => None,
1724 }.map(|m| PathBuf::from(m));
1726 if cg.lto && incremental.is_some() {
1727 early_error(error_format, "can't perform LTO when compiling incrementally");
1730 let mut prints = Vec::<PrintRequest>::new();
1731 if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
1732 prints.push(PrintRequest::TargetCPUs);
1733 cg.target_cpu = None;
1735 if cg.target_feature == "help" {
1736 prints.push(PrintRequest::TargetFeatures);
1737 cg.target_feature = "".to_string();
1739 if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
1740 prints.push(PrintRequest::RelocationModels);
1741 cg.relocation_model = None;
1743 if cg.code_model.as_ref().map_or(false, |s| s == "help") {
1744 prints.push(PrintRequest::CodeModels);
1745 cg.code_model = None;
1747 if debugging_opts.tls_model.as_ref().map_or(false, |s| s == "help") {
1748 prints.push(PrintRequest::TlsModels);
1749 debugging_opts.tls_model = None;
1754 let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
1755 let target = matches.opt_str("target").unwrap_or(
1756 host_triple().to_string());
1758 if matches.opt_present("O") {
1759 if cg.opt_level.is_some() {
1760 early_error(error_format, "-O and -C opt-level both provided");
1764 match (cg.opt_level.as_ref().map(String::as_ref),
1765 nightly_options::is_nightly_build()) {
1766 (None, _) => OptLevel::No,
1767 (Some("0"), _) => OptLevel::No,
1768 (Some("1"), _) => OptLevel::Less,
1769 (Some("2"), _) => OptLevel::Default,
1770 (Some("3"), _) => OptLevel::Aggressive,
1771 (Some("s"), true) => OptLevel::Size,
1772 (Some("z"), true) => OptLevel::SizeMin,
1773 (Some("s"), false) | (Some("z"), false) => {
1774 early_error(error_format, &format!("the optimizations s or z are only \
1775 accepted on the nightly compiler"));
1778 early_error(error_format, &format!("optimization level needs to be \
1779 between 0-3 (instead was `{}`)",
1785 let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
1786 let debuginfo = if matches.opt_present("g") {
1787 if cg.debuginfo.is_some() {
1788 early_error(error_format, "-g and -C debuginfo both provided");
1792 match cg.debuginfo {
1793 None | Some(0) => NoDebugInfo,
1794 Some(1) => LimitedDebugInfo,
1795 Some(2) => FullDebugInfo,
1797 early_error(error_format, &format!("debug info level needs to be between \
1798 0-2 (instead was `{}`)",
1804 let mut search_paths = SearchPaths::new();
1805 for s in &matches.opt_strs("L") {
1806 search_paths.add_path(&s[..], error_format);
1809 let libs = matches.opt_strs("l").into_iter().map(|s| {
1810 // Parse string of the form "[KIND=]lib[:new_name]",
1811 // where KIND is one of "dylib", "framework", "static".
1812 let mut parts = s.splitn(2, '=');
1813 let kind = parts.next().unwrap();
1814 let (name, kind) = match (parts.next(), kind) {
1815 (None, name) => (name, None),
1816 (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
1817 (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
1818 (Some(name), "static") => (name, Some(cstore::NativeStatic)),
1819 (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
1821 early_error(error_format, &format!("unknown library kind `{}`, expected \
1822 one of dylib, framework, or static",
1826 if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
1827 early_error(error_format, &format!("the library kind 'static-nobundle' is only \
1828 accepted on the nightly compiler"));
1830 let mut name_parts = name.splitn(2, ':');
1831 let name = name_parts.next().unwrap();
1832 let new_name = name_parts.next();
1833 (name.to_string(), new_name.map(|n| n.to_string()), kind)
1836 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
1837 let test = matches.opt_present("test");
1839 prints.extend(matches.opt_strs("print").into_iter().map(|s| {
1841 "crate-name" => PrintRequest::CrateName,
1842 "file-names" => PrintRequest::FileNames,
1843 "sysroot" => PrintRequest::Sysroot,
1844 "cfg" => PrintRequest::Cfg,
1845 "target-list" => PrintRequest::TargetList,
1846 "target-cpus" => PrintRequest::TargetCPUs,
1847 "target-features" => PrintRequest::TargetFeatures,
1848 "relocation-models" => PrintRequest::RelocationModels,
1849 "code-models" => PrintRequest::CodeModels,
1850 "tls-models" => PrintRequest::TlsModels,
1851 "native-static-libs" => PrintRequest::NativeStaticLibs,
1852 "target-spec-json" => {
1853 if nightly_options::is_unstable_enabled(matches) {
1854 PrintRequest::TargetSpec
1856 early_error(error_format,
1857 &format!("the `-Z unstable-options` flag must also be passed to \
1858 enable the target-spec-json print option"));
1862 early_error(error_format, &format!("unknown print request `{}`", req))
1867 let borrowck_mode = match debugging_opts.borrowck.as_ref().map(|s| &s[..]) {
1868 None | Some("ast") => BorrowckMode::Ast,
1869 Some("mir") => BorrowckMode::Mir,
1870 Some("compare") => BorrowckMode::Compare,
1872 early_error(error_format, &format!("unknown borrowck mode `{}`", m))
1876 if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
1877 early_warn(error_format, "-C remark will not show source locations without \
1881 let mut externs = BTreeMap::new();
1882 for arg in &matches.opt_strs("extern") {
1883 let mut parts = arg.splitn(2, '=');
1884 let name = match parts.next() {
1886 None => early_error(error_format, "--extern value must not be empty"),
1888 let location = match parts.next() {
1890 None => early_error(error_format, "--extern value must be of the format `foo=bar`"),
1893 externs.entry(name.to_string())
1894 .or_insert_with(BTreeSet::new)
1895 .insert(location.to_string());
1898 let crate_name = matches.opt_str("crate-name");
1902 optimize: opt_level,
1907 output_types: OutputTypes(output_types),
1909 maybe_sysroot: sysroot_opt,
1910 target_triple: target,
1918 externs: Externs(externs),
1922 unstable_features: UnstableFeatures::from_environment(),
1924 actually_rustdoc: false,
1925 cli_forced_codegen_units: codegen_units,
1926 cli_forced_thinlto: thinlto,
1931 pub fn parse_crate_types_from_list(list_list: Vec<String>)
1932 -> Result<Vec<CrateType>, String> {
1933 let mut crate_types: Vec<CrateType> = Vec::new();
1934 for unparsed_crate_type in &list_list {
1935 for part in unparsed_crate_type.split(',') {
1936 let new_part = match part {
1937 "lib" => default_lib_output(),
1938 "rlib" => CrateTypeRlib,
1939 "staticlib" => CrateTypeStaticlib,
1940 "dylib" => CrateTypeDylib,
1941 "cdylib" => CrateTypeCdylib,
1942 "bin" => CrateTypeExecutable,
1943 "proc-macro" => CrateTypeProcMacro,
1945 return Err(format!("unknown crate type: `{}`",
1949 if !crate_types.contains(&new_part) {
1950 crate_types.push(new_part)
1958 pub mod nightly_options {
1960 use syntax::feature_gate::UnstableFeatures;
1961 use super::{ErrorOutputType, OptionStability, RustcOptGroup};
1962 use session::early_error;
1964 pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
1965 is_nightly_build() && matches.opt_strs("Z").iter().any(|x| *x == "unstable-options")
1968 pub fn is_nightly_build() -> bool {
1969 UnstableFeatures::from_environment().is_nightly_build()
1972 pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
1973 let has_z_unstable_option = matches.opt_strs("Z").iter().any(|x| *x == "unstable-options");
1974 let really_allows_unstable_options = UnstableFeatures::from_environment()
1975 .is_nightly_build();
1977 for opt in flags.iter() {
1978 if opt.stability == OptionStability::Stable {
1981 if !matches.opt_present(opt.name) {
1984 if opt.name != "Z" && !has_z_unstable_option {
1985 early_error(ErrorOutputType::default(),
1986 &format!("the `-Z unstable-options` flag must also be passed to enable \
1990 if really_allows_unstable_options {
1993 match opt.stability {
1994 OptionStability::Unstable => {
1995 let msg = format!("the option `{}` is only accepted on the \
1996 nightly compiler", opt.name);
1997 early_error(ErrorOutputType::default(), &msg);
1999 OptionStability::Stable => {}
2005 impl fmt::Display for CrateType {
2006 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2008 CrateTypeExecutable => "bin".fmt(f),
2009 CrateTypeDylib => "dylib".fmt(f),
2010 CrateTypeRlib => "rlib".fmt(f),
2011 CrateTypeStaticlib => "staticlib".fmt(f),
2012 CrateTypeCdylib => "cdylib".fmt(f),
2013 CrateTypeProcMacro => "proc-macro".fmt(f),
2018 /// Commandline arguments passed to the compiler have to be incorporated with
2019 /// the dependency tracking system for incremental compilation. This module
2020 /// provides some utilities to make this more convenient.
2022 /// The values of all commandline arguments that are relevant for dependency
2023 /// tracking are hashed into a single value that determines whether the
2024 /// incremental compilation cache can be re-used or not. This hashing is done
2025 /// via the DepTrackingHash trait defined below, since the standard Hash
2026 /// implementation might not be suitable (e.g. arguments are stored in a Vec,
2027 /// the hash of which is order dependent, but we might not want the order of
2028 /// arguments to make a difference for the hash).
2030 /// However, since the value provided by Hash::hash often *is* suitable,
2031 /// especially for primitive types, there is the
2032 /// impl_dep_tracking_hash_via_hash!() macro that allows to simply reuse the
2033 /// Hash implementation for DepTrackingHash. It's important though that
2034 /// we have an opt-in scheme here, so one is hopefully forced to think about
2035 /// how the hash should be calculated when adding a new commandline argument.
2039 use session::search_paths::{PathKind, SearchPaths};
2040 use std::collections::BTreeMap;
2041 use std::hash::Hash;
2042 use std::path::PathBuf;
2043 use std::collections::hash_map::DefaultHasher;
2044 use super::{Passes, CrateType, OptLevel, DebugInfoLevel,
2045 OutputTypes, Externs, ErrorOutputType, Sanitizer};
2046 use syntax::feature_gate::UnstableFeatures;
2047 use rustc_back::{PanicStrategy, RelroLevel};
2049 pub trait DepTrackingHash {
2050 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);
2053 macro_rules! impl_dep_tracking_hash_via_hash {
2055 impl DepTrackingHash for $t {
2056 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
2057 Hash::hash(self, hasher);
2063 macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
2065 impl DepTrackingHash for Vec<$t> {
2066 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2067 let mut elems: Vec<&$t> = self.iter().collect();
2069 Hash::hash(&elems.len(), hasher);
2070 for (index, elem) in elems.iter().enumerate() {
2071 Hash::hash(&index, hasher);
2072 DepTrackingHash::hash(*elem, hasher, error_format);
2079 impl_dep_tracking_hash_via_hash!(bool);
2080 impl_dep_tracking_hash_via_hash!(usize);
2081 impl_dep_tracking_hash_via_hash!(u64);
2082 impl_dep_tracking_hash_via_hash!(String);
2083 impl_dep_tracking_hash_via_hash!(PathBuf);
2084 impl_dep_tracking_hash_via_hash!(lint::Level);
2085 impl_dep_tracking_hash_via_hash!(Option<bool>);
2086 impl_dep_tracking_hash_via_hash!(Option<usize>);
2087 impl_dep_tracking_hash_via_hash!(Option<String>);
2088 impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
2089 impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
2090 impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
2091 impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
2092 impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
2093 impl_dep_tracking_hash_via_hash!(Option<cstore::NativeLibraryKind>);
2094 impl_dep_tracking_hash_via_hash!(CrateType);
2095 impl_dep_tracking_hash_via_hash!(PanicStrategy);
2096 impl_dep_tracking_hash_via_hash!(RelroLevel);
2097 impl_dep_tracking_hash_via_hash!(Passes);
2098 impl_dep_tracking_hash_via_hash!(OptLevel);
2099 impl_dep_tracking_hash_via_hash!(DebugInfoLevel);
2100 impl_dep_tracking_hash_via_hash!(UnstableFeatures);
2101 impl_dep_tracking_hash_via_hash!(Externs);
2102 impl_dep_tracking_hash_via_hash!(OutputTypes);
2103 impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
2104 impl_dep_tracking_hash_via_hash!(Sanitizer);
2105 impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
2107 impl_dep_tracking_hash_for_sortable_vec_of!(String);
2108 impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
2109 impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
2110 impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
2111 impl_dep_tracking_hash_for_sortable_vec_of!((String, Option<String>,
2112 Option<cstore::NativeLibraryKind>));
2113 impl_dep_tracking_hash_for_sortable_vec_of!((String, u64));
2114 impl DepTrackingHash for SearchPaths {
2115 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
2116 let mut elems: Vec<_> = self
2117 .iter(PathKind::All)
2120 Hash::hash(&elems, hasher);
2124 impl<T1, T2> DepTrackingHash for (T1, T2)
2125 where T1: DepTrackingHash,
2128 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2129 Hash::hash(&0, hasher);
2130 DepTrackingHash::hash(&self.0, hasher, error_format);
2131 Hash::hash(&1, hasher);
2132 DepTrackingHash::hash(&self.1, hasher, error_format);
2136 impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
2137 where T1: DepTrackingHash,
2138 T2: DepTrackingHash,
2141 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2142 Hash::hash(&0, hasher);
2143 DepTrackingHash::hash(&self.0, hasher, error_format);
2144 Hash::hash(&1, hasher);
2145 DepTrackingHash::hash(&self.1, hasher, error_format);
2146 Hash::hash(&2, hasher);
2147 DepTrackingHash::hash(&self.2, hasher, error_format);
2151 // This is a stable hash because BTreeMap is a sorted container
2152 pub fn stable_hash(sub_hashes: BTreeMap<&'static str, &DepTrackingHash>,
2153 hasher: &mut DefaultHasher,
2154 error_format: ErrorOutputType) {
2155 for (key, sub_hash) in sub_hashes {
2156 // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
2157 // the keys, as they are just plain strings
2158 Hash::hash(&key.len(), hasher);
2159 Hash::hash(key, hasher);
2160 sub_hash.hash(hasher, error_format);
2171 use session::config::{build_configuration, build_session_options_and_crate_config};
2172 use session::build_session;
2173 use std::collections::{BTreeMap, BTreeSet};
2174 use std::iter::FromIterator;
2175 use std::path::PathBuf;
2176 use super::{OutputType, OutputTypes, Externs};
2177 use rustc_back::{PanicStrategy, RelroLevel};
2178 use syntax::symbol::Symbol;
2180 fn optgroups() -> getopts::Options {
2181 let mut opts = getopts::Options::new();
2182 for group in super::rustc_optgroups() {
2183 (group.apply)(&mut opts);
2188 fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
2189 BTreeMap::from_iter(entries.into_iter())
2192 fn mk_set<V: Ord>(entries: Vec<V>) -> BTreeSet<V> {
2193 BTreeSet::from_iter(entries.into_iter())
2196 // When the user supplies --test we should implicitly supply --cfg test
2198 fn test_switch_implies_cfg_test() {
2200 &match optgroups().parse(&["--test".to_string()]) {
2202 Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
2204 let registry = errors::registry::Registry::new(&[]);
2205 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2206 let sess = build_session(sessopts, None, registry);
2207 let cfg = build_configuration(&sess, cfg);
2208 assert!(cfg.contains(&(Symbol::intern("test"), None)));
2211 // When the user supplies --test and --cfg test, don't implicitly add
2212 // another --cfg test
2214 fn test_switch_implies_cfg_test_unless_cfg_test() {
2216 &match optgroups().parse(&["--test".to_string(), "--cfg=test".to_string()]) {
2219 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
2222 let registry = errors::registry::Registry::new(&[]);
2223 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2224 let sess = build_session(sessopts, None, registry);
2225 let cfg = build_configuration(&sess, cfg);
2226 let mut test_items = cfg.iter().filter(|&&(name, _)| name == "test");
2227 assert!(test_items.next().is_some());
2228 assert!(test_items.next().is_none());
2232 fn test_can_print_warnings() {
2234 let matches = optgroups().parse(&[
2235 "-Awarnings".to_string()
2237 let registry = errors::registry::Registry::new(&[]);
2238 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2239 let sess = build_session(sessopts, None, registry);
2240 assert!(!sess.diagnostic().flags.can_emit_warnings);
2244 let matches = optgroups().parse(&[
2245 "-Awarnings".to_string(),
2246 "-Dwarnings".to_string()
2248 let registry = errors::registry::Registry::new(&[]);
2249 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2250 let sess = build_session(sessopts, None, registry);
2251 assert!(sess.diagnostic().flags.can_emit_warnings);
2255 let matches = optgroups().parse(&[
2256 "-Adead_code".to_string()
2258 let registry = errors::registry::Registry::new(&[]);
2259 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2260 let sess = build_session(sessopts, None, registry);
2261 assert!(sess.diagnostic().flags.can_emit_warnings);
2266 fn test_output_types_tracking_hash_different_paths() {
2267 let mut v1 = super::basic_options();
2268 let mut v2 = super::basic_options();
2269 let mut v3 = super::basic_options();
2271 v1.output_types = OutputTypes::new(&[(OutputType::Exe,
2272 Some(PathBuf::from("./some/thing")))]);
2273 v2.output_types = OutputTypes::new(&[(OutputType::Exe,
2274 Some(PathBuf::from("/some/thing")))]);
2275 v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
2277 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2278 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2279 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2282 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2283 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2284 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2288 fn test_output_types_tracking_hash_different_construction_order() {
2289 let mut v1 = super::basic_options();
2290 let mut v2 = super::basic_options();
2292 v1.output_types = OutputTypes::new(&[
2293 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2294 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2297 v2.output_types = OutputTypes::new(&[
2298 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2299 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2302 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2305 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2309 fn test_externs_tracking_hash_different_values() {
2310 let mut v1 = super::basic_options();
2311 let mut v2 = super::basic_options();
2312 let mut v3 = super::basic_options();
2314 v1.externs = Externs::new(mk_map(vec![
2315 (String::from("a"), mk_set(vec![String::from("b"),
2316 String::from("c")])),
2317 (String::from("d"), mk_set(vec![String::from("e"),
2318 String::from("f")])),
2321 v2.externs = Externs::new(mk_map(vec![
2322 (String::from("a"), mk_set(vec![String::from("b"),
2323 String::from("c")])),
2324 (String::from("X"), mk_set(vec![String::from("e"),
2325 String::from("f")])),
2328 v3.externs = Externs::new(mk_map(vec![
2329 (String::from("a"), mk_set(vec![String::from("b"),
2330 String::from("c")])),
2331 (String::from("d"), mk_set(vec![String::from("X"),
2332 String::from("f")])),
2335 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2336 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2337 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2340 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2341 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2342 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2346 fn test_externs_tracking_hash_different_construction_order() {
2347 let mut v1 = super::basic_options();
2348 let mut v2 = super::basic_options();
2349 let mut v3 = super::basic_options();
2351 v1.externs = Externs::new(mk_map(vec![
2352 (String::from("a"), mk_set(vec![String::from("b"),
2353 String::from("c")])),
2354 (String::from("d"), mk_set(vec![String::from("e"),
2355 String::from("f")])),
2358 v2.externs = Externs::new(mk_map(vec![
2359 (String::from("d"), mk_set(vec![String::from("e"),
2360 String::from("f")])),
2361 (String::from("a"), mk_set(vec![String::from("b"),
2362 String::from("c")])),
2365 v3.externs = Externs::new(mk_map(vec![
2366 (String::from("a"), mk_set(vec![String::from("b"),
2367 String::from("c")])),
2368 (String::from("d"), mk_set(vec![String::from("f"),
2369 String::from("e")])),
2372 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2373 assert_eq!(v1.dep_tracking_hash(), v3.dep_tracking_hash());
2374 assert_eq!(v2.dep_tracking_hash(), v3.dep_tracking_hash());
2377 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2378 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2379 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2383 fn test_lints_tracking_hash_different_values() {
2384 let mut v1 = super::basic_options();
2385 let mut v2 = super::basic_options();
2386 let mut v3 = super::basic_options();
2388 v1.lint_opts = vec![(String::from("a"), lint::Allow),
2389 (String::from("b"), lint::Warn),
2390 (String::from("c"), lint::Deny),
2391 (String::from("d"), lint::Forbid)];
2393 v2.lint_opts = vec![(String::from("a"), lint::Allow),
2394 (String::from("b"), lint::Warn),
2395 (String::from("X"), lint::Deny),
2396 (String::from("d"), lint::Forbid)];
2398 v3.lint_opts = vec![(String::from("a"), lint::Allow),
2399 (String::from("b"), lint::Warn),
2400 (String::from("c"), lint::Forbid),
2401 (String::from("d"), lint::Deny)];
2403 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2404 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2405 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2408 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2409 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2410 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2414 fn test_lints_tracking_hash_different_construction_order() {
2415 let mut v1 = super::basic_options();
2416 let mut v2 = super::basic_options();
2418 v1.lint_opts = vec![(String::from("a"), lint::Allow),
2419 (String::from("b"), lint::Warn),
2420 (String::from("c"), lint::Deny),
2421 (String::from("d"), lint::Forbid)];
2423 v2.lint_opts = vec![(String::from("a"), lint::Allow),
2424 (String::from("c"), lint::Deny),
2425 (String::from("b"), lint::Warn),
2426 (String::from("d"), lint::Forbid)];
2428 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2431 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2432 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2436 fn test_search_paths_tracking_hash_different_values() {
2437 let mut v1 = super::basic_options();
2438 let mut v2 = super::basic_options();
2439 let mut v3 = super::basic_options();
2440 let mut v4 = super::basic_options();
2441 let mut v5 = super::basic_options();
2444 v1.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2445 v1.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2446 v1.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2447 v1.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2448 v1.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2451 v2.search_paths.add_path("native=XXX", super::ErrorOutputType::Json(false));
2452 v2.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2453 v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2454 v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2455 v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2458 v2.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2459 v2.search_paths.add_path("crate=XXX", super::ErrorOutputType::Json(false));
2460 v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2461 v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2462 v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2464 // Dependency changed
2465 v3.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2466 v3.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2467 v3.search_paths.add_path("dependency=XXX", super::ErrorOutputType::Json(false));
2468 v3.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2469 v3.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2471 // Framework changed
2472 v4.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2473 v4.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2474 v4.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2475 v4.search_paths.add_path("framework=XXX", super::ErrorOutputType::Json(false));
2476 v4.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2479 v5.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2480 v5.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2481 v5.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2482 v5.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2483 v5.search_paths.add_path("all=XXX", super::ErrorOutputType::Json(false));
2485 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2486 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2487 assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
2488 assert!(v1.dep_tracking_hash() != v5.dep_tracking_hash());
2491 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2492 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2493 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2494 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2495 assert_eq!(v5.dep_tracking_hash(), v5.clone().dep_tracking_hash());
2499 fn test_search_paths_tracking_hash_different_order() {
2500 let mut v1 = super::basic_options();
2501 let mut v2 = super::basic_options();
2502 let mut v3 = super::basic_options();
2503 let mut v4 = super::basic_options();
2506 v1.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2507 v1.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2508 v1.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2509 v1.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2510 v1.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2512 v2.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2513 v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2514 v2.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2515 v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2516 v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2518 v3.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2519 v3.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2520 v3.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2521 v3.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2522 v3.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2524 v4.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2525 v4.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2526 v4.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2527 v4.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2528 v4.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2530 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2531 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2532 assert!(v1.dep_tracking_hash() == v4.dep_tracking_hash());
2535 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2536 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2537 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2538 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2542 fn test_native_libs_tracking_hash_different_values() {
2543 let mut v1 = super::basic_options();
2544 let mut v2 = super::basic_options();
2545 let mut v3 = super::basic_options();
2546 let mut v4 = super::basic_options();
2549 v1.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2550 (String::from("b"), None, Some(cstore::NativeFramework)),
2551 (String::from("c"), None, Some(cstore::NativeUnknown))];
2554 v2.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2555 (String::from("X"), None, Some(cstore::NativeFramework)),
2556 (String::from("c"), None, Some(cstore::NativeUnknown))];
2559 v3.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2560 (String::from("b"), None, Some(cstore::NativeStatic)),
2561 (String::from("c"), None, Some(cstore::NativeUnknown))];
2564 v4.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2565 (String::from("b"), Some(String::from("X")), Some(cstore::NativeFramework)),
2566 (String::from("c"), None, Some(cstore::NativeUnknown))];
2568 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2569 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2570 assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
2573 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2574 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2575 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2576 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2580 fn test_native_libs_tracking_hash_different_order() {
2581 let mut v1 = super::basic_options();
2582 let mut v2 = super::basic_options();
2583 let mut v3 = super::basic_options();
2586 v1.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2587 (String::from("b"), None, Some(cstore::NativeFramework)),
2588 (String::from("c"), None, Some(cstore::NativeUnknown))];
2590 v2.libs = vec![(String::from("b"), None, Some(cstore::NativeFramework)),
2591 (String::from("a"), None, Some(cstore::NativeStatic)),
2592 (String::from("c"), None, Some(cstore::NativeUnknown))];
2594 v3.libs = vec![(String::from("c"), None, Some(cstore::NativeUnknown)),
2595 (String::from("a"), None, Some(cstore::NativeStatic)),
2596 (String::from("b"), None, Some(cstore::NativeFramework))];
2598 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2599 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2600 assert!(v2.dep_tracking_hash() == v3.dep_tracking_hash());
2603 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2604 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2605 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2609 fn test_codegen_options_tracking_hash() {
2610 let reference = super::basic_options();
2611 let mut opts = super::basic_options();
2613 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2614 opts.cg.ar = Some(String::from("abc"));
2615 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2617 opts.cg.linker = Some(PathBuf::from("linker"));
2618 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2620 opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
2621 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2623 opts.cg.link_dead_code = true;
2624 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2626 opts.cg.rpath = true;
2627 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2629 opts.cg.extra_filename = String::from("extra-filename");
2630 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2632 opts.cg.codegen_units = Some(42);
2633 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2635 opts.cg.remark = super::SomePasses(vec![String::from("pass1"),
2636 String::from("pass2")]);
2637 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2639 opts.cg.save_temps = true;
2640 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2642 opts.cg.incremental = Some(String::from("abc"));
2643 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2646 // Make sure changing a [TRACKED] option changes the hash
2647 opts = reference.clone();
2649 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2651 opts = reference.clone();
2652 opts.cg.target_cpu = Some(String::from("abc"));
2653 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2655 opts = reference.clone();
2656 opts.cg.target_feature = String::from("all the features, all of them");
2657 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2659 opts = reference.clone();
2660 opts.cg.passes = vec![String::from("1"), String::from("2")];
2661 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2663 opts = reference.clone();
2664 opts.cg.llvm_args = vec![String::from("1"), String::from("2")];
2665 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2667 opts = reference.clone();
2668 opts.cg.overflow_checks = Some(true);
2669 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2671 opts = reference.clone();
2672 opts.cg.no_prepopulate_passes = true;
2673 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2675 opts = reference.clone();
2676 opts.cg.no_vectorize_loops = true;
2677 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2679 opts = reference.clone();
2680 opts.cg.no_vectorize_slp = true;
2681 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2683 opts = reference.clone();
2684 opts.cg.soft_float = true;
2685 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2687 opts = reference.clone();
2688 opts.cg.prefer_dynamic = true;
2689 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2691 opts = reference.clone();
2692 opts.cg.no_integrated_as = true;
2693 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2695 opts = reference.clone();
2696 opts.cg.no_redzone = Some(true);
2697 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2699 opts = reference.clone();
2700 opts.cg.relocation_model = Some(String::from("relocation model"));
2701 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2703 opts = reference.clone();
2704 opts.cg.code_model = Some(String::from("code model"));
2705 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2707 opts = reference.clone();
2708 opts.debugging_opts.tls_model = Some(String::from("tls model"));
2709 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2711 opts = reference.clone();
2712 opts.cg.metadata = vec![String::from("A"), String::from("B")];
2713 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2715 opts = reference.clone();
2716 opts.cg.debuginfo = Some(0xdeadbeef);
2717 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2719 opts = reference.clone();
2720 opts.cg.debuginfo = Some(0xba5eba11);
2721 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2723 opts = reference.clone();
2724 opts.cg.debug_assertions = Some(true);
2725 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2727 opts = reference.clone();
2728 opts.cg.inline_threshold = Some(0xf007ba11);
2729 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2731 opts = reference.clone();
2732 opts.cg.panic = Some(PanicStrategy::Abort);
2733 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2737 fn test_debugging_options_tracking_hash() {
2738 let reference = super::basic_options();
2739 let mut opts = super::basic_options();
2741 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2742 opts.debugging_opts.verbose = true;
2743 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2744 opts.debugging_opts.time_passes = true;
2745 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2746 opts.debugging_opts.count_llvm_insns = true;
2747 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2748 opts.debugging_opts.time_llvm_passes = true;
2749 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2750 opts.debugging_opts.input_stats = true;
2751 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2752 opts.debugging_opts.trans_stats = true;
2753 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2754 opts.debugging_opts.borrowck_stats = true;
2755 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2756 opts.debugging_opts.meta_stats = true;
2757 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2758 opts.debugging_opts.print_link_args = true;
2759 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2760 opts.debugging_opts.print_llvm_passes = true;
2761 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2762 opts.debugging_opts.ast_json = true;
2763 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2764 opts.debugging_opts.ast_json_noexpand = true;
2765 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2766 opts.debugging_opts.ls = true;
2767 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2768 opts.debugging_opts.save_analysis = true;
2769 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2770 opts.debugging_opts.flowgraph_print_loans = true;
2771 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2772 opts.debugging_opts.flowgraph_print_moves = true;
2773 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2774 opts.debugging_opts.flowgraph_print_assigns = true;
2775 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2776 opts.debugging_opts.flowgraph_print_all = true;
2777 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2778 opts.debugging_opts.print_region_graph = true;
2779 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2780 opts.debugging_opts.parse_only = true;
2781 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2782 opts.debugging_opts.incremental = Some(String::from("abc"));
2783 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2784 opts.debugging_opts.dump_dep_graph = true;
2785 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2786 opts.debugging_opts.query_dep_graph = true;
2787 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2788 opts.debugging_opts.no_analysis = true;
2789 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2790 opts.debugging_opts.unstable_options = true;
2791 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2792 opts.debugging_opts.trace_macros = true;
2793 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2794 opts.debugging_opts.keep_hygiene_data = true;
2795 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2796 opts.debugging_opts.keep_ast = true;
2797 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2798 opts.debugging_opts.print_trans_items = Some(String::from("abc"));
2799 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2800 opts.debugging_opts.dump_mir = Some(String::from("abc"));
2801 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2802 opts.debugging_opts.dump_mir_dir = String::from("abc");
2803 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2804 opts.debugging_opts.dump_mir_graphviz = true;
2805 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2807 // Make sure changing a [TRACKED] option changes the hash
2808 opts = reference.clone();
2809 opts.debugging_opts.asm_comments = true;
2810 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2812 opts = reference.clone();
2813 opts.debugging_opts.no_verify = true;
2814 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2816 opts = reference.clone();
2817 opts.debugging_opts.no_landing_pads = true;
2818 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2820 opts = reference.clone();
2821 opts.debugging_opts.fewer_names = true;
2822 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2824 opts = reference.clone();
2825 opts.debugging_opts.no_trans = true;
2826 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2828 opts = reference.clone();
2829 opts.debugging_opts.treat_err_as_bug = true;
2830 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2832 opts = reference.clone();
2833 opts.debugging_opts.continue_parse_after_error = true;
2834 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2836 opts = reference.clone();
2837 opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
2838 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2840 opts = reference.clone();
2841 opts.debugging_opts.force_overflow_checks = Some(true);
2842 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2844 opts = reference.clone();
2845 opts.debugging_opts.enable_nonzeroing_move_hints = true;
2846 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2848 opts = reference.clone();
2849 opts.debugging_opts.show_span = Some(String::from("abc"));
2850 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2852 opts = reference.clone();
2853 opts.debugging_opts.mir_opt_level = 3;
2854 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2856 opts = reference.clone();
2857 opts.debugging_opts.relro_level = Some(RelroLevel::Full);
2858 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());