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)]
77 /// Don't do any LTO whatsoever
80 /// Do a full crate graph LTO. The flavor is determined by the compiler
81 /// (currently the default is "fat").
84 /// Do a full crate graph LTO with ThinLTO
87 /// Do a local graph LTO with ThinLTO (only relevant for multiple codegen
91 /// Do a full crate graph LTO with "fat" LTO
95 #[derive(Clone, Copy, PartialEq, Hash)]
96 pub enum DebugInfoLevel {
102 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord,
103 RustcEncodable, RustcDecodable)]
104 pub enum OutputType {
115 impl_stable_hash_for!(enum self::OutputType {
126 impl<'tcx> ToStableHashKey<StableHashingContext<'tcx>> for OutputType {
127 type KeyType = OutputType;
129 fn to_stable_hash_key(&self, _: &StableHashingContext<'tcx>) -> Self::KeyType {
135 fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
138 OutputType::DepInfo => true,
139 OutputType::Bitcode |
140 OutputType::Assembly |
141 OutputType::LlvmAssembly |
144 OutputType::Metadata => false,
148 fn shorthand(&self) -> &'static str {
150 OutputType::Bitcode => "llvm-bc",
151 OutputType::Assembly => "asm",
152 OutputType::LlvmAssembly => "llvm-ir",
153 OutputType::Mir => "mir",
154 OutputType::Object => "obj",
155 OutputType::Metadata => "metadata",
156 OutputType::Exe => "link",
157 OutputType::DepInfo => "dep-info",
161 fn from_shorthand(shorthand: &str) -> Option<Self> {
162 Some(match shorthand {
163 "asm" => OutputType::Assembly,
164 "llvm-ir" => OutputType::LlvmAssembly,
165 "mir" => OutputType::Mir,
166 "llvm-bc" => OutputType::Bitcode,
167 "obj" => OutputType::Object,
168 "metadata" => OutputType::Metadata,
169 "link" => OutputType::Exe,
170 "dep-info" => OutputType::DepInfo,
175 fn shorthands_display() -> String {
177 "`{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`",
178 OutputType::Bitcode.shorthand(),
179 OutputType::Assembly.shorthand(),
180 OutputType::LlvmAssembly.shorthand(),
181 OutputType::Mir.shorthand(),
182 OutputType::Object.shorthand(),
183 OutputType::Metadata.shorthand(),
184 OutputType::Exe.shorthand(),
185 OutputType::DepInfo.shorthand(),
189 pub fn extension(&self) -> &'static str {
191 OutputType::Bitcode => "bc",
192 OutputType::Assembly => "s",
193 OutputType::LlvmAssembly => "ll",
194 OutputType::Mir => "mir",
195 OutputType::Object => "o",
196 OutputType::Metadata => "rmeta",
197 OutputType::DepInfo => "d",
198 OutputType::Exe => "",
203 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
204 pub enum ErrorOutputType {
205 HumanReadable(ColorConfig),
210 impl Default for ErrorOutputType {
211 fn default() -> ErrorOutputType {
212 ErrorOutputType::HumanReadable(ColorConfig::Auto)
216 // Use tree-based collections to cheaply get a deterministic Hash implementation.
217 // DO NOT switch BTreeMap out for an unsorted container type! That would break
218 // dependency tracking for commandline arguments.
219 #[derive(Clone, Hash)]
220 pub struct OutputTypes(BTreeMap<OutputType, Option<PathBuf>>);
222 impl_stable_hash_for!(tuple_struct self::OutputTypes {
227 pub fn new(entries: &[(OutputType, Option<PathBuf>)]) -> OutputTypes {
228 OutputTypes(BTreeMap::from_iter(entries.iter()
229 .map(|&(k, ref v)| (k, v.clone()))))
232 pub fn get(&self, key: &OutputType) -> Option<&Option<PathBuf>> {
236 pub fn contains_key(&self, key: &OutputType) -> bool {
237 self.0.contains_key(key)
240 pub fn keys<'a>(&'a self) -> BTreeMapKeysIter<'a, OutputType, Option<PathBuf>> {
244 pub fn values<'a>(&'a self) -> BTreeMapValuesIter<'a, OutputType, Option<PathBuf>> {
248 // True if any of the output types require codegen or linking.
249 pub fn should_trans(&self) -> bool {
250 self.0.keys().any(|k| match *k {
251 OutputType::Bitcode |
252 OutputType::Assembly |
253 OutputType::LlvmAssembly |
256 OutputType::Exe => true,
257 OutputType::Metadata |
258 OutputType::DepInfo => false,
264 // Use tree-based collections to cheaply get a deterministic Hash implementation.
265 // DO NOT switch BTreeMap or BTreeSet out for an unsorted container type! That
266 // would break dependency tracking for commandline arguments.
267 #[derive(Clone, Hash)]
268 pub struct Externs(BTreeMap<String, BTreeSet<String>>);
271 pub fn new(data: BTreeMap<String, BTreeSet<String>>) -> Externs {
275 pub fn get(&self, key: &str) -> Option<&BTreeSet<String>> {
279 pub fn iter<'a>(&'a self) -> BTreeMapIter<'a, String, BTreeSet<String>> {
284 macro_rules! hash_option {
285 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [UNTRACKED]) => ({});
286 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({
287 if $sub_hashes.insert(stringify!($opt_name),
288 $opt_expr as &dep_tracking::DepTrackingHash).is_some() {
289 bug!("Duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
295 [UNTRACKED_WITH_WARNING $warn_val:expr, $warn_text:expr, $error_format:expr]) => ({
296 if *$opt_expr == $warn_val {
297 early_warn($error_format, $warn_text)
302 macro_rules! top_level_options {
303 (pub struct Options { $(
304 $opt:ident : $t:ty [$dep_tracking_marker:ident $($warn_val:expr, $warn_text:expr)*],
312 pub fn dep_tracking_hash(&self) -> u64 {
313 let mut sub_hashes = BTreeMap::new();
318 [$dep_tracking_marker $($warn_val,
320 self.error_format)*]);
322 let mut hasher = DefaultHasher::new();
323 dep_tracking::stable_hash(sub_hashes,
332 // The top-level commandline options struct
334 // For each option, one has to specify how it behaves with regard to the
335 // dependency tracking system of incremental compilation. This is done via the
336 // square-bracketed directive after the field type. The options are:
339 // A change in the given field will cause the compiler to completely clear the
340 // incremental compilation cache before proceeding.
343 // Incremental compilation is not influenced by this option.
345 // [UNTRACKED_WITH_WARNING(val, warning)]
346 // The option is incompatible with incremental compilation in some way. If it
347 // has the value `val`, the string `warning` is emitted as a warning.
349 // If you add a new option to this struct or one of the sub-structs like
350 // CodegenOptions, think about how it influences incremental compilation. If in
351 // doubt, specify [TRACKED], which is always "correct" but might lead to
352 // unnecessary re-compilation.
355 // The crate config requested for the session, which may be combined
356 // with additional crate configurations during the compile process
357 crate_types: Vec<CrateType> [TRACKED],
358 optimize: OptLevel [TRACKED],
359 // Include the debug_assertions flag into dependency tracking, since it
360 // can influence whether overflow checks are done or not.
361 debug_assertions: bool [TRACKED],
362 debuginfo: DebugInfoLevel [TRACKED],
363 lint_opts: Vec<(String, lint::Level)> [TRACKED],
364 lint_cap: Option<lint::Level> [TRACKED],
365 describe_lints: bool [UNTRACKED],
366 output_types: OutputTypes [TRACKED],
367 // FIXME(mw): We track this for now but it actually doesn't make too
368 // much sense: The search path can stay the same while the
369 // things discovered there might have changed on disk.
370 search_paths: SearchPaths [TRACKED],
371 libs: Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> [TRACKED],
372 maybe_sysroot: Option<PathBuf> [TRACKED],
374 target_triple: String [TRACKED],
376 test: bool [TRACKED],
377 error_format: ErrorOutputType [UNTRACKED],
379 // if Some, enable incremental compilation, using the given
380 // directory to store intermediate results
381 incremental: Option<PathBuf> [UNTRACKED],
383 debugging_opts: DebuggingOptions [TRACKED],
384 prints: Vec<PrintRequest> [UNTRACKED],
385 // Determines which borrow checker(s) to run. This is the parsed, sanitized
386 // version of `debugging_opts.borrowck`, which is just a plain string.
387 borrowck_mode: BorrowckMode [UNTRACKED],
388 cg: CodegenOptions [TRACKED],
389 // FIXME(mw): We track this for now but it actually doesn't make too
390 // much sense: The value of this option can stay the same
391 // while the files they refer to might have changed on disk.
392 externs: Externs [TRACKED],
393 crate_name: Option<String> [TRACKED],
394 // An optional name to use as the crate for std during std injection,
395 // written `extern crate std = "name"`. Default to "std". Used by
396 // out-of-tree drivers.
397 alt_std_name: Option<String> [TRACKED],
398 // Indicates how the compiler should treat unstable features
399 unstable_features: UnstableFeatures [TRACKED],
401 // Indicates whether this run of the compiler is actually rustdoc. This
402 // is currently just a hack and will be removed eventually, so please
403 // try to not rely on this too much.
404 actually_rustdoc: bool [TRACKED],
406 // Specifications of codegen units / ThinLTO which are forced as a
407 // result of parsing command line options. These are not necessarily
408 // what rustc was invoked with, but massaged a bit to agree with
409 // commands like `--emit llvm-ir` which they're often incompatible with
410 // if we otherwise use the defaults of rustc.
411 cli_forced_codegen_units: Option<usize> [UNTRACKED],
412 cli_forced_thinlto_off: bool [UNTRACKED],
416 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
417 pub enum PrintRequest {
432 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
433 pub enum BorrowckMode {
440 /// Should we emit the AST-based borrow checker errors?
441 pub fn use_ast(self) -> bool {
443 BorrowckMode::Ast => true,
444 BorrowckMode::Compare => true,
445 BorrowckMode::Mir => false,
448 /// Should we emit the MIR-based borrow checker errors?
449 pub fn use_mir(self) -> bool {
451 BorrowckMode::Ast => false,
452 BorrowckMode::Compare => true,
453 BorrowckMode::Mir => true,
459 /// Load source from file
462 /// String that is shown in place of a filename
464 /// Anonymous source string
470 pub fn filestem(&self) -> String {
472 Input::File(ref ifile) => ifile.file_stem().unwrap()
473 .to_str().unwrap().to_string(),
474 Input::Str { .. } => "rust_out".to_string(),
480 pub struct OutputFilenames {
481 pub out_directory: PathBuf,
482 pub out_filestem: String,
483 pub single_output_file: Option<PathBuf>,
485 pub outputs: OutputTypes,
488 impl_stable_hash_for!(struct self::OutputFilenames {
496 pub const RUST_CGU_EXT: &str = "rcgu";
498 impl OutputFilenames {
499 pub fn path(&self, flavor: OutputType) -> PathBuf {
500 self.outputs.get(&flavor).and_then(|p| p.to_owned())
501 .or_else(|| self.single_output_file.clone())
502 .unwrap_or_else(|| self.temp_path(flavor, None))
505 /// Get the path where a compilation artifact of the given type for the
506 /// given codegen unit should be placed on disk. If codegen_unit_name is
507 /// None, a path distinct from those of any codegen unit will be generated.
508 pub fn temp_path(&self,
510 codegen_unit_name: Option<&str>)
512 let extension = flavor.extension();
513 self.temp_path_ext(extension, codegen_unit_name)
516 /// Like temp_path, but also supports things where there is no corresponding
517 /// OutputType, like no-opt-bitcode or lto-bitcode.
518 pub fn temp_path_ext(&self,
520 codegen_unit_name: Option<&str>)
522 let base = self.out_directory.join(&self.filestem());
524 let mut extension = String::new();
526 if let Some(codegen_unit_name) = codegen_unit_name {
527 extension.push_str(codegen_unit_name);
531 if !extension.is_empty() {
532 extension.push_str(".");
533 extension.push_str(RUST_CGU_EXT);
534 extension.push_str(".");
537 extension.push_str(ext);
540 let path = base.with_extension(&extension[..]);
544 pub fn with_extension(&self, extension: &str) -> PathBuf {
545 self.out_directory.join(&self.filestem()).with_extension(extension)
548 pub fn filestem(&self) -> String {
549 format!("{}{}", self.out_filestem, self.extra)
552 pub fn contains_path(&self, input_path: &PathBuf) -> bool {
553 let input_path = input_path.canonicalize().ok();
554 if input_path.is_none() {
557 match self.single_output_file {
558 Some(ref output_path) => output_path.canonicalize().ok() == input_path,
560 for k in self.outputs.keys() {
561 let output_path = self.path(k.to_owned());
562 if output_path.canonicalize().ok() == input_path {
572 pub fn host_triple() -> &'static str {
573 // Get the host triple out of the build environment. This ensures that our
574 // idea of the host triple is the same as for the set of libraries we've
575 // actually built. We can't just take LLVM's host triple because they
576 // normalize all ix86 architectures to i386.
578 // Instead of grabbing the host triple (for the current host), we grab (at
579 // compile time) the target triple that this rustc is built with and
580 // calling that (at runtime) the host triple.
581 (option_env!("CFG_COMPILER_HOST_TRIPLE")).
582 expect("CFG_COMPILER_HOST_TRIPLE")
585 /// Some reasonable defaults
586 pub fn basic_options() -> Options {
588 crate_types: Vec::new(),
589 optimize: OptLevel::No,
590 debuginfo: NoDebugInfo,
591 lint_opts: Vec::new(),
593 describe_lints: false,
594 output_types: OutputTypes(BTreeMap::new()),
595 search_paths: SearchPaths::new(),
597 target_triple: host_triple().to_string(),
600 debugging_opts: basic_debugging_options(),
602 borrowck_mode: BorrowckMode::Ast,
603 cg: basic_codegen_options(),
604 error_format: ErrorOutputType::default(),
605 externs: Externs(BTreeMap::new()),
609 unstable_features: UnstableFeatures::Disallow,
610 debug_assertions: true,
611 actually_rustdoc: false,
612 cli_forced_codegen_units: None,
613 cli_forced_thinlto_off: false,
618 /// True if there is a reason to build the dep graph.
619 pub fn build_dep_graph(&self) -> bool {
620 self.incremental.is_some() ||
621 self.debugging_opts.dump_dep_graph ||
622 self.debugging_opts.query_dep_graph
626 pub fn enable_dep_node_debug_strs(&self) -> bool {
627 cfg!(debug_assertions) &&
628 (self.debugging_opts.query_dep_graph || self.debugging_opts.incremental_info)
631 pub fn file_path_mapping(&self) -> FilePathMapping {
632 FilePathMapping::new(
633 self.debugging_opts.remap_path_prefix_from.iter().zip(
634 self.debugging_opts.remap_path_prefix_to.iter()
635 ).map(|(src, dst)| (src.clone(), dst.clone())).collect()
639 /// True if there will be an output file generated
640 pub fn will_create_output_file(&self) -> bool {
641 !self.debugging_opts.parse_only && // The file is just being parsed
642 !self.debugging_opts.ls // The file is just being queried
646 // The type of entry function, so
647 // users can have their own entry
648 // functions that don't start a
650 #[derive(Copy, Clone, PartialEq)]
651 pub enum EntryFnType {
657 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
667 #[derive(Clone, Hash)]
669 SomePasses(Vec<String>),
674 pub fn is_empty(&self) -> bool {
676 SomePasses(ref v) => v.is_empty(),
682 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
683 /// at once. The goal of this macro is to define an interface that can be
684 /// programmatically used by the option parser in order to initialize the struct
685 /// without hardcoding field names all over the place.
687 /// The goal is to invoke this macro once with the correct fields, and then this
688 /// macro generates all necessary code. The main gotcha of this macro is the
689 /// cgsetters module which is a bunch of generated code to parse an option into
690 /// its respective field in the struct. There are a few hand-written parsers for
691 /// parsing specific types of values in this module.
692 macro_rules! options {
693 ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
694 $buildfn:ident, $prefix:expr, $outputname:expr,
695 $stat:ident, $mod_desc:ident, $mod_set:ident,
696 $($opt:ident : $t:ty = (
699 [$dep_tracking_marker:ident $(($dep_warn_val:expr, $dep_warn_text:expr))*],
704 pub struct $struct_name { $(pub $opt: $t),* }
706 pub fn $defaultfn() -> $struct_name {
707 $struct_name { $($opt: $init),* }
710 pub fn $buildfn(matches: &getopts::Matches, error_format: ErrorOutputType) -> $struct_name
712 let mut op = $defaultfn();
713 for option in matches.opt_strs($prefix) {
714 let mut iter = option.splitn(2, '=');
715 let key = iter.next().unwrap();
716 let value = iter.next();
717 let option_to_lookup = key.replace("-", "_");
718 let mut found = false;
719 for &(candidate, setter, opt_type_desc, _) in $stat {
720 if option_to_lookup != candidate { continue }
721 if !setter(&mut op, value) {
722 match (value, opt_type_desc) {
723 (Some(..), None) => {
724 early_error(error_format, &format!("{} option `{}` takes no \
725 value", $outputname, key))
727 (None, Some(type_desc)) => {
728 early_error(error_format, &format!("{0} option `{1}` requires \
729 {2} ({3} {1}=<value>)",
733 (Some(value), Some(type_desc)) => {
734 early_error(error_format, &format!("incorrect value `{}` for {} \
735 option `{}` - {} was expected",
739 (None, None) => bug!()
746 early_error(error_format, &format!("unknown {} option: `{}`",
753 impl<'a> dep_tracking::DepTrackingHash for $struct_name {
755 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
756 let mut sub_hashes = BTreeMap::new();
761 [$dep_tracking_marker $($dep_warn_val,
765 dep_tracking::stable_hash(sub_hashes, hasher, error_format);
769 pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
770 pub const $stat: &'static [(&'static str, $setter_name,
771 Option<&'static str>, &'static str)] =
772 &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
774 #[allow(non_upper_case_globals, dead_code)]
776 pub const parse_bool: Option<&'static str> = None;
777 pub const parse_opt_bool: Option<&'static str> =
778 Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
779 pub const parse_string: Option<&'static str> = Some("a string");
780 pub const parse_string_push: Option<&'static str> = Some("a string");
781 pub const parse_pathbuf_push: Option<&'static str> = Some("a path");
782 pub const parse_opt_string: Option<&'static str> = Some("a string");
783 pub const parse_opt_pathbuf: Option<&'static str> = Some("a path");
784 pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
785 pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
786 pub const parse_uint: Option<&'static str> = Some("a number");
787 pub const parse_passes: Option<&'static str> =
788 Some("a space-separated list of passes, or `all`");
789 pub const parse_opt_uint: Option<&'static str> =
791 pub const parse_panic_strategy: Option<&'static str> =
792 Some("either `panic` or `abort`");
793 pub const parse_relro_level: Option<&'static str> =
794 Some("one of: `full`, `partial`, or `off`");
795 pub const parse_sanitizer: Option<&'static str> =
796 Some("one of: `address`, `leak`, `memory` or `thread`");
797 pub const parse_linker_flavor: Option<&'static str> =
798 Some(::rustc_back::LinkerFlavor::one_of());
799 pub const parse_optimization_fuel: Option<&'static str> =
800 Some("crate=integer");
801 pub const parse_unpretty: Option<&'static str> =
802 Some("`string` or `string=string`");
803 pub const parse_lto: Option<&'static str> =
804 Some("one of `thin`, `fat`, or omitted");
809 use super::{$struct_name, Passes, SomePasses, AllPasses, Sanitizer, Lto};
810 use rustc_back::{LinkerFlavor, PanicStrategy, RelroLevel};
811 use std::path::PathBuf;
814 pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
815 $parse(&mut cg.$opt, v)
819 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
822 None => { *slot = true; true }
826 fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
830 "n" | "no" | "off" => {
833 "y" | "yes" | "on" => {
836 _ => { return false; }
841 None => { *slot = Some(true); true }
845 fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
847 Some(s) => { *slot = Some(s.to_string()); true },
852 fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
854 Some(s) => { *slot = Some(PathBuf::from(s)); true },
859 fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
861 Some(s) => { *slot = s.to_string(); true },
866 fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
868 Some(s) => { slot.push(s.to_string()); true },
873 fn parse_pathbuf_push(slot: &mut Vec<PathBuf>, v: Option<&str>) -> bool {
875 Some(s) => { slot.push(PathBuf::from(s)); true },
880 fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
884 for s in s.split_whitespace() {
885 slot.push(s.to_string());
893 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
897 let v = s.split_whitespace().map(|s| s.to_string()).collect();
905 fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
906 match v.and_then(|s| s.parse().ok()) {
907 Some(i) => { *slot = i; true },
912 fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
914 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
915 None => { *slot = None; false }
919 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
926 let mut passes = vec![];
927 if parse_list(&mut passes, v) {
928 *slot = SomePasses(passes);
937 fn parse_panic_strategy(slot: &mut Option<PanicStrategy>, v: Option<&str>) -> bool {
939 Some("unwind") => *slot = Some(PanicStrategy::Unwind),
940 Some("abort") => *slot = Some(PanicStrategy::Abort),
946 fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
949 match s.parse::<RelroLevel>() {
950 Ok(level) => *slot = Some(level),
959 fn parse_sanitizer(slote: &mut Option<Sanitizer>, v: Option<&str>) -> bool {
961 Some("address") => *slote = Some(Sanitizer::Address),
962 Some("leak") => *slote = Some(Sanitizer::Leak),
963 Some("memory") => *slote = Some(Sanitizer::Memory),
964 Some("thread") => *slote = Some(Sanitizer::Thread),
970 fn parse_linker_flavor(slote: &mut Option<LinkerFlavor>, v: Option<&str>) -> bool {
971 match v.and_then(LinkerFlavor::from_str) {
972 Some(lf) => *slote = Some(lf),
978 fn parse_optimization_fuel(slot: &mut Option<(String, u64)>, v: Option<&str>) -> bool {
982 let parts = s.split('=').collect::<Vec<_>>();
983 if parts.len() != 2 { return false; }
984 let crate_name = parts[0].to_string();
985 let fuel = parts[1].parse::<u64>();
986 if fuel.is_err() { return false; }
987 *slot = Some((crate_name, fuel.unwrap()));
993 fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
996 Some(s) if s.split('=').count() <= 2 => {
997 *slot = Some(s.to_string());
1004 fn parse_lto(slot: &mut Lto, v: Option<&str>) -> bool {
1007 Some("thin") => Lto::Thin,
1008 Some("fat") => Lto::Fat,
1009 Some(_) => return false,
1016 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
1017 build_codegen_options, "C", "codegen",
1018 CG_OPTIONS, cg_type_desc, cgsetters,
1019 ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
1020 "this option is deprecated and does nothing"),
1021 linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
1022 "system linker to link outputs with"),
1023 link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1024 "a single extra argument to append to the linker invocation (can be used several times)"),
1025 link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1026 "extra arguments to append to the linker invocation (space separated)"),
1027 link_dead_code: bool = (false, parse_bool, [UNTRACKED],
1028 "don't let linker strip dead code (turning it on can be used for code coverage)"),
1029 lto: Lto = (Lto::No, parse_lto, [TRACKED],
1030 "perform LLVM link-time optimizations"),
1031 target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
1032 "select target processor (rustc --print target-cpus for details)"),
1033 target_feature: String = ("".to_string(), parse_string, [TRACKED],
1034 "target specific attributes (rustc --print target-features for details)"),
1035 passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1036 "a list of extra LLVM passes to run (space separated)"),
1037 llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1038 "a list of arguments to pass to llvm (space separated)"),
1039 save_temps: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1040 "`-C save-temps` might not produce all requested temporary products \
1041 when incremental compilation is enabled.")],
1042 "save all temporary output files during compilation"),
1043 rpath: bool = (false, parse_bool, [UNTRACKED],
1044 "set rpath values in libs/exes"),
1045 overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1046 "use overflow checks for integer arithmetic"),
1047 no_prepopulate_passes: bool = (false, parse_bool, [TRACKED],
1048 "don't pre-populate the pass manager with a list of passes"),
1049 no_vectorize_loops: bool = (false, parse_bool, [TRACKED],
1050 "don't run the loop vectorization optimization passes"),
1051 no_vectorize_slp: bool = (false, parse_bool, [TRACKED],
1052 "don't run LLVM's SLP vectorization pass"),
1053 soft_float: bool = (false, parse_bool, [TRACKED],
1054 "use soft float ABI (*eabihf targets only)"),
1055 prefer_dynamic: bool = (false, parse_bool, [TRACKED],
1056 "prefer dynamic linking to static linking"),
1057 no_integrated_as: bool = (false, parse_bool, [TRACKED],
1058 "use an external assembler rather than LLVM's integrated one"),
1059 no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
1060 "disable the use of the redzone"),
1061 relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
1062 "choose the relocation model to use (rustc --print relocation-models for details)"),
1063 code_model: Option<String> = (None, parse_opt_string, [TRACKED],
1064 "choose the code model to use (rustc --print code-models for details)"),
1065 metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1066 "metadata to mangle symbol names with"),
1067 extra_filename: String = ("".to_string(), parse_string, [UNTRACKED],
1068 "extra data to put in each output filename"),
1069 codegen_units: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1070 "divide crate into N units to optimize in parallel"),
1071 remark: Passes = (SomePasses(Vec::new()), parse_passes, [UNTRACKED],
1072 "print remarks for these optimization passes (space separated, or \"all\")"),
1073 no_stack_check: bool = (false, parse_bool, [UNTRACKED],
1074 "the --no-stack-check flag is deprecated and does nothing"),
1075 debuginfo: Option<usize> = (None, parse_opt_uint, [TRACKED],
1076 "debug info emission level, 0 = no debug info, 1 = line tables only, \
1077 2 = full debug info with variable and type information"),
1078 opt_level: Option<String> = (None, parse_opt_string, [TRACKED],
1079 "optimize with possible levels 0-3, s, or z"),
1080 debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
1081 "explicitly enable the cfg(debug_assertions) directive"),
1082 inline_threshold: Option<usize> = (None, parse_opt_uint, [TRACKED],
1083 "set the threshold for inlining a function (default: 225)"),
1084 panic: Option<PanicStrategy> = (None, parse_panic_strategy,
1085 [TRACKED], "panic strategy to compile crate with"),
1086 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1087 "enable incremental compilation"),
1090 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
1091 build_debugging_options, "Z", "debugging",
1092 DB_OPTIONS, db_type_desc, dbsetters,
1093 codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
1094 "the backend to use"),
1095 verbose: bool = (false, parse_bool, [UNTRACKED],
1096 "in general, enable more debug printouts"),
1097 span_free_formats: bool = (false, parse_bool, [UNTRACKED],
1098 "when debug-printing compiler state, do not include spans"), // o/w tests have closure@path
1099 identify_regions: bool = (false, parse_bool, [UNTRACKED],
1100 "make unnamed regions display as '# (where # is some non-ident unique id)"),
1101 emit_end_regions: bool = (false, parse_bool, [UNTRACKED],
1102 "emit EndRegion as part of MIR; enable transforms that solely process EndRegion"),
1103 borrowck: Option<String> = (None, parse_opt_string, [UNTRACKED],
1104 "select which borrowck is used (`ast`, `mir`, or `compare`)"),
1105 two_phase_borrows: bool = (false, parse_bool, [UNTRACKED],
1106 "use two-phase reserved/active distinction for `&mut` borrows in MIR borrowck"),
1107 time_passes: bool = (false, parse_bool, [UNTRACKED],
1108 "measure time of each rustc pass"),
1109 count_llvm_insns: bool = (false, parse_bool,
1110 [UNTRACKED_WITH_WARNING(true,
1111 "The output generated by `-Z count_llvm_insns` might not be reliable \
1112 when used with incremental compilation")],
1113 "count where LLVM instrs originate"),
1114 time_llvm_passes: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1115 "The output of `-Z time-llvm-passes` will only reflect timings of \
1116 re-translated modules when used with incremental compilation" )],
1117 "measure time of each LLVM pass"),
1118 input_stats: bool = (false, parse_bool, [UNTRACKED],
1119 "gather statistics about the input"),
1120 trans_stats: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1121 "The output of `-Z trans-stats` might not be accurate when incremental \
1122 compilation is enabled")],
1123 "gather trans statistics"),
1124 asm_comments: bool = (false, parse_bool, [TRACKED],
1125 "generate comments into the assembly (may change behavior)"),
1126 no_verify: bool = (false, parse_bool, [TRACKED],
1127 "skip LLVM verification"),
1128 borrowck_stats: bool = (false, parse_bool, [UNTRACKED],
1129 "gather borrowck statistics"),
1130 no_landing_pads: bool = (false, parse_bool, [TRACKED],
1131 "omit landing pads for unwinding"),
1132 fewer_names: bool = (false, parse_bool, [TRACKED],
1133 "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR)"),
1134 meta_stats: bool = (false, parse_bool, [UNTRACKED],
1135 "gather metadata statistics"),
1136 print_link_args: bool = (false, parse_bool, [UNTRACKED],
1137 "print the arguments passed to the linker"),
1138 print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1139 "prints the llvm optimization passes being run"),
1140 ast_json: bool = (false, parse_bool, [UNTRACKED],
1141 "print the AST as JSON and halt"),
1142 query_threads: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1143 "execute queries on a thread pool with N threads"),
1144 ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
1145 "print the pre-expansion AST as JSON and halt"),
1146 ls: bool = (false, parse_bool, [UNTRACKED],
1147 "list the symbols defined by a library crate"),
1148 save_analysis: bool = (false, parse_bool, [UNTRACKED],
1149 "write syntax and type analysis (in JSON format) information, in \
1150 addition to normal output"),
1151 flowgraph_print_loans: bool = (false, parse_bool, [UNTRACKED],
1152 "include loan analysis data in -Z unpretty flowgraph output"),
1153 flowgraph_print_moves: bool = (false, parse_bool, [UNTRACKED],
1154 "include move analysis data in -Z unpretty flowgraph output"),
1155 flowgraph_print_assigns: bool = (false, parse_bool, [UNTRACKED],
1156 "include assignment analysis data in -Z unpretty flowgraph output"),
1157 flowgraph_print_all: bool = (false, parse_bool, [UNTRACKED],
1158 "include all dataflow analysis data in -Z unpretty flowgraph output"),
1159 print_region_graph: bool = (false, parse_bool, [UNTRACKED],
1160 "prints region inference graph. \
1161 Use with RUST_REGION_GRAPH=help for more info"),
1162 parse_only: bool = (false, parse_bool, [UNTRACKED],
1163 "parse only; do not compile, assemble, or link"),
1164 no_trans: bool = (false, parse_bool, [TRACKED],
1165 "run all passes except translation; no output"),
1166 treat_err_as_bug: bool = (false, parse_bool, [TRACKED],
1167 "treat all errors that occur as bugs"),
1168 external_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1169 "show macro backtraces even for non-local macros"),
1170 continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
1171 "attempt to recover from parse errors (experimental)"),
1172 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1173 "enable incremental compilation (experimental)"),
1174 incremental_queries: bool = (true, parse_bool, [UNTRACKED],
1175 "enable incremental compilation support for queries (experimental)"),
1176 incremental_info: bool = (false, parse_bool, [UNTRACKED],
1177 "print high-level information about incremental reuse (or the lack thereof)"),
1178 incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
1179 "dump hash information in textual format to stdout"),
1180 incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
1181 "verify incr. comp. hashes of green query instances"),
1182 incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
1183 "ignore spans during ICH computation -- used for testing"),
1184 dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1185 "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
1186 query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1187 "enable queries of the dependency graph for regression testing"),
1188 profile_queries: bool = (false, parse_bool, [UNTRACKED],
1189 "trace and profile the queries of the incremental compilation framework"),
1190 profile_queries_and_keys: bool = (false, parse_bool, [UNTRACKED],
1191 "trace and profile the queries and keys of the incremental compilation framework"),
1192 no_analysis: bool = (false, parse_bool, [UNTRACKED],
1193 "parse and expand the source, but run no analysis"),
1194 extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1195 "load extra plugins"),
1196 unstable_options: bool = (false, parse_bool, [UNTRACKED],
1197 "adds unstable command line options to rustc interface"),
1198 force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1199 "force overflow checks on or off"),
1200 trace_macros: bool = (false, parse_bool, [UNTRACKED],
1201 "for every macro invocation, print its name and arguments"),
1202 debug_macros: bool = (false, parse_bool, [TRACKED],
1203 "emit line numbers debug info inside macros"),
1204 enable_nonzeroing_move_hints: bool = (false, parse_bool, [TRACKED],
1205 "force nonzeroing move optimization on"),
1206 keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
1207 "don't clear the hygiene data after analysis"),
1208 keep_ast: bool = (false, parse_bool, [UNTRACKED],
1209 "keep the AST after lowering it to HIR"),
1210 show_span: Option<String> = (None, parse_opt_string, [TRACKED],
1211 "show spans for compiler debugging (expr|pat|ty)"),
1212 print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
1213 "print layout information for each type encountered"),
1214 print_trans_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
1215 "print the result of the translation item collection pass"),
1216 mir_opt_level: usize = (1, parse_uint, [TRACKED],
1217 "set the MIR optimization level (0-3, default: 1)"),
1218 mutable_noalias: bool = (false, parse_bool, [UNTRACKED],
1219 "emit noalias metadata for mutable references"),
1220 dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1221 "dump MIR state at various points in translation"),
1222 dump_mir_dir: String = (String::from("mir_dump"), parse_string, [UNTRACKED],
1223 "the directory the MIR is dumped into"),
1224 dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
1225 "in addition to `.mir` files, create graphviz `.dot` files"),
1226 dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
1227 "if set, exclude the pass number when dumping MIR (used in tests)"),
1228 mir_emit_validate: usize = (0, parse_uint, [TRACKED],
1229 "emit Validate MIR statements, interpreted e.g. by miri (0: do not emit; 1: if function \
1230 contains unsafe block, only validate arguments; 2: always emit full validation)"),
1231 perf_stats: bool = (false, parse_bool, [UNTRACKED],
1232 "print some performance-related statistics"),
1233 hir_stats: bool = (false, parse_bool, [UNTRACKED],
1234 "print some statistics about AST and HIR"),
1235 mir_stats: bool = (false, parse_bool, [UNTRACKED],
1236 "print some statistics about MIR"),
1237 always_encode_mir: bool = (false, parse_bool, [TRACKED],
1238 "encode MIR of all functions into the crate metadata"),
1239 miri: bool = (false, parse_bool, [TRACKED],
1240 "check the miri const evaluator against the old ctfe"),
1241 osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
1242 "pass `-install_name @rpath/...` to the macOS linker"),
1243 sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
1245 linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
1247 fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
1248 "set the optimization fuel quota for a crate"),
1249 print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
1250 "make Rustc print the total optimization fuel used by a crate"),
1251 remap_path_prefix_from: Vec<PathBuf> = (vec![], parse_pathbuf_push, [TRACKED],
1252 "add a source pattern to the file path remapping config"),
1253 remap_path_prefix_to: Vec<PathBuf> = (vec![], parse_pathbuf_push, [TRACKED],
1254 "add a mapping target to the file path remapping config"),
1255 force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
1256 "force all crates to be `rustc_private` unstable"),
1257 pre_link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1258 "a single extra argument to prepend the linker invocation (can be used several times)"),
1259 pre_link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1260 "extra arguments to prepend to the linker invocation (space separated)"),
1261 profile: bool = (false, parse_bool, [TRACKED],
1262 "insert profiling code"),
1263 relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
1264 "choose which RELRO level to use"),
1265 nll: bool = (false, parse_bool, [UNTRACKED],
1266 "run the non-lexical lifetimes MIR pass"),
1267 nll_dump_cause: bool = (false, parse_bool, [UNTRACKED],
1268 "dump cause information when reporting errors from NLL"),
1269 trans_time_graph: bool = (false, parse_bool, [UNTRACKED],
1270 "generate a graphical HTML report of time spent in trans and LLVM"),
1271 thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
1272 "enable ThinLTO when possible"),
1273 inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
1274 "control whether #[inline] functions are in all cgus"),
1275 tls_model: Option<String> = (None, parse_opt_string, [TRACKED],
1276 "choose the TLS model to use (rustc --print tls-models for details)"),
1277 saturating_float_casts: bool = (false, parse_bool, [TRACKED],
1278 "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
1279 the max/min integer respectively, and NaN is mapped to 0"),
1280 lower_128bit_ops: Option<bool> = (None, parse_opt_bool, [TRACKED],
1281 "rewrite operators on i128 and u128 into lang item calls (typically provided \
1282 by compiler-builtins) so translation doesn't need to support them,
1283 overriding the default for the current target"),
1284 human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
1285 "generate human-readable, predictable names for codegen units"),
1286 dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
1287 "in dep-info output, omit targets for tracking dependencies of the dep-info files \
1289 unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
1290 "Present the input source, unstable (and less-pretty) variants;
1291 valid types are any of the types for `--pretty`, as well as:
1292 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
1293 `everybody_loops` (all function bodies replaced with `loop {}`),
1294 `hir` (the HIR), `hir,identified`, or
1295 `hir,typed` (HIR with types for each node)."),
1298 pub fn default_lib_output() -> CrateType {
1302 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
1303 let end = &sess.target.target.target_endian;
1304 let arch = &sess.target.target.arch;
1305 let wordsz = &sess.target.target.target_pointer_width;
1306 let os = &sess.target.target.target_os;
1307 let env = &sess.target.target.target_env;
1308 let vendor = &sess.target.target.target_vendor;
1309 let min_atomic_width = sess.target.target.min_atomic_width();
1310 let max_atomic_width = sess.target.target.max_atomic_width();
1312 let mut ret = HashSet::new();
1314 ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
1315 if let Some(ref fam) = sess.target.target.options.target_family {
1316 ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam))));
1317 if fam == "windows" || fam == "unix" {
1318 ret.insert((Symbol::intern(fam), None));
1321 ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
1322 ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
1323 ret.insert((Symbol::intern("target_pointer_width"), Some(Symbol::intern(wordsz))));
1324 ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
1325 ret.insert((Symbol::intern("target_vendor"), Some(Symbol::intern(vendor))));
1326 if sess.target.target.options.has_elf_tls {
1327 ret.insert((Symbol::intern("target_thread_local"), None));
1329 for &i in &[8, 16, 32, 64, 128] {
1330 if i >= min_atomic_width && i <= max_atomic_width {
1331 let s = i.to_string();
1332 ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern(&s))));
1334 ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern("ptr"))));
1338 if sess.opts.debug_assertions {
1339 ret.insert((Symbol::intern("debug_assertions"), None));
1341 if sess.opts.crate_types.contains(&CrateTypeProcMacro) {
1342 ret.insert((Symbol::intern("proc_macro"), None));
1347 pub fn build_configuration(sess: &Session,
1348 mut user_cfg: ast::CrateConfig)
1349 -> ast::CrateConfig {
1350 // Combine the configuration requested by the session (command line) with
1351 // some default and generated configuration items
1352 let default_cfg = default_configuration(sess);
1353 // If the user wants a test runner, then add the test cfg
1355 user_cfg.insert((Symbol::intern("test"), None));
1357 user_cfg.extend(default_cfg.iter().cloned());
1361 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
1362 let target = match Target::search(&opts.target_triple) {
1365 sp.struct_fatal(&format!("Error loading target specification: {}", e))
1366 .help("Use `--print target-list` for a list of built-in targets")
1372 let (isize_ty, usize_ty) = match &target.target_pointer_width[..] {
1373 "16" => (ast::IntTy::I16, ast::UintTy::U16),
1374 "32" => (ast::IntTy::I32, ast::UintTy::U32),
1375 "64" => (ast::IntTy::I64, ast::UintTy::U64),
1376 w => sp.fatal(&format!("target specification was invalid: \
1377 unrecognized target-pointer-width {}", w)).raise(),
1387 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1388 pub enum OptionStability {
1394 pub struct RustcOptGroup {
1395 pub apply: Box<Fn(&mut getopts::Options) -> &mut getopts::Options>,
1396 pub name: &'static str,
1397 pub stability: OptionStability,
1400 impl RustcOptGroup {
1401 pub fn is_stable(&self) -> bool {
1402 self.stability == OptionStability::Stable
1405 pub fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
1406 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1411 stability: OptionStability::Stable,
1415 pub fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
1416 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1421 stability: OptionStability::Unstable,
1426 // The `opt` local module holds wrappers around the `getopts` API that
1427 // adds extra rustc-specific metadata to each option; such metadata
1428 // is exposed by . The public
1429 // functions below ending with `_u` are the functions that return
1430 // *unstable* options, i.e. options that are only enabled when the
1431 // user also passes the `-Z unstable-options` debugging flag.
1433 // The `fn opt_u` etc below are written so that we can use them
1434 // in the future; do not warn about them not being used right now.
1435 #![allow(dead_code)]
1438 use super::RustcOptGroup;
1440 pub type R = RustcOptGroup;
1441 pub type S = &'static str;
1443 fn stable<F>(name: S, f: F) -> R
1444 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
1446 RustcOptGroup::stable(name, f)
1449 fn unstable<F>(name: S, f: F) -> R
1450 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
1452 RustcOptGroup::unstable(name, f)
1455 fn longer(a: S, b: S) -> S {
1456 if a.len() > b.len() {
1463 pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
1464 stable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1466 pub fn multi_s(a: S, b: S, c: S, d: S) -> R {
1467 stable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1469 pub fn flag_s(a: S, b: S, c: S) -> R {
1470 stable(longer(a, b), move |opts| opts.optflag(a, b, c))
1472 pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R {
1473 stable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1475 pub fn flagmulti_s(a: S, b: S, c: S) -> R {
1476 stable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1479 pub fn opt(a: S, b: S, c: S, d: S) -> R {
1480 unstable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1482 pub fn multi(a: S, b: S, c: S, d: S) -> R {
1483 unstable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1485 pub fn flag(a: S, b: S, c: S) -> R {
1486 unstable(longer(a, b), move |opts| opts.optflag(a, b, c))
1488 pub fn flagopt(a: S, b: S, c: S, d: S) -> R {
1489 unstable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1491 pub fn flagmulti(a: S, b: S, c: S) -> R {
1492 unstable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1496 /// Returns the "short" subset of the rustc command line options,
1497 /// including metadata for each option, such as whether the option is
1498 /// part of the stable long-term interface for rustc.
1499 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
1501 opt::flag_s("h", "help", "Display this message"),
1502 opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
1503 opt::multi_s("L", "", "Add a directory to the library search path. The
1504 optional KIND can be one of dependency, crate, native,
1505 framework or all (the default).", "[KIND=]PATH"),
1506 opt::multi_s("l", "", "Link the generated crate(s) to the specified native
1507 library NAME. The optional KIND can be one of
1508 static, dylib, or framework. If omitted, dylib is
1509 assumed.", "[KIND=]NAME"),
1510 opt::multi_s("", "crate-type", "Comma separated list of types of crates
1511 for the compiler to emit",
1512 "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]"),
1513 opt::opt_s("", "crate-name", "Specify the name of the crate being built",
1515 opt::multi_s("", "emit", "Comma separated list of types of output for \
1516 the compiler to emit",
1517 "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]"),
1518 opt::multi_s("", "print", "Comma separated list of compiler information to \
1520 "[crate-name|file-names|sysroot|cfg|target-list|\
1521 target-cpus|target-features|relocation-models|\
1522 code-models|tls-models|target-spec-json|native-static-libs]"),
1523 opt::flagmulti_s("g", "", "Equivalent to -C debuginfo=2"),
1524 opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
1525 opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
1526 opt::opt_s("", "out-dir", "Write output to compiler-chosen filename \
1528 opt::opt_s("", "explain", "Provide a detailed explanation of an error \
1530 opt::flag_s("", "test", "Build a test harness"),
1531 opt::opt_s("", "target", "Target triple for which the code is compiled", "TARGET"),
1532 opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
1533 opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
1534 opt::multi_s("D", "deny", "Set lint denied", "OPT"),
1535 opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
1536 opt::multi_s("", "cap-lints", "Set the most restrictive lint level. \
1537 More restrictive lints are capped at this \
1539 opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
1540 opt::flag_s("V", "version", "Print version info and exit"),
1541 opt::flag_s("v", "verbose", "Use verbose output"),
1545 /// Returns all rustc command line options, including metadata for
1546 /// each option, such as whether the option is part of the stable
1547 /// long-term interface for rustc.
1548 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
1549 let mut opts = rustc_short_optgroups();
1551 opt::multi_s("", "extern", "Specify where an external rust library is located",
1553 opt::opt_s("", "sysroot", "Override the system root", "PATH"),
1554 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
1555 opt::opt_s("", "error-format",
1556 "How errors and other messages are produced",
1557 "human|json|short"),
1558 opt::opt_s("", "color", "Configure coloring of output:
1559 auto = colorize, if output goes to a tty (default);
1560 always = always colorize output;
1561 never = never colorize output", "auto|always|never"),
1563 opt::opt("", "pretty",
1564 "Pretty-print the input instead of compiling;
1565 valid types are: `normal` (un-annotated source),
1566 `expanded` (crates expanded), or
1567 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
1573 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
1574 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
1575 cfgspecs.into_iter().map(|s| {
1576 let sess = parse::ParseSess::new(FilePathMapping::empty());
1578 parse::new_parser_from_source_str(&sess, FileName::CfgSpec, s.to_string());
1580 let meta_item = panictry!(parser.parse_meta_item());
1582 if parser.token != token::Eof {
1583 early_error(ErrorOutputType::default(), &format!("invalid --cfg argument: {}", s))
1584 } else if meta_item.is_meta_item_list() {
1586 format!("invalid predicate in --cfg command line argument: `{}`", meta_item.name());
1587 early_error(ErrorOutputType::default(), &msg)
1590 (meta_item.name(), meta_item.value_str())
1591 }).collect::<ast::CrateConfig>()
1594 pub fn build_session_options_and_crate_config(matches: &getopts::Matches)
1595 -> (Options, ast::CrateConfig) {
1596 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
1597 Some("auto") => ColorConfig::Auto,
1598 Some("always") => ColorConfig::Always,
1599 Some("never") => ColorConfig::Never,
1601 None => ColorConfig::Auto,
1604 early_error(ErrorOutputType::default(), &format!("argument for --color must be auto, \
1605 always or never (instead was `{}`)",
1610 // We need the opts_present check because the driver will send us Matches
1611 // with only stable options if no unstable options are used. Since error-format
1612 // is unstable, it will not be present. We have to use opts_present not
1613 // opt_present because the latter will panic.
1614 let error_format = if matches.opts_present(&["error-format".to_owned()]) {
1615 match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
1616 Some("human") => ErrorOutputType::HumanReadable(color),
1617 Some("json") => ErrorOutputType::Json(false),
1618 Some("pretty-json") => ErrorOutputType::Json(true),
1620 if nightly_options::is_unstable_enabled(matches) {
1621 ErrorOutputType::Short(color)
1623 early_error(ErrorOutputType::default(),
1624 &format!("the `-Z unstable-options` flag must also be passed to \
1625 enable the short error message option"));
1628 None => ErrorOutputType::HumanReadable(color),
1631 early_error(ErrorOutputType::HumanReadable(color),
1632 &format!("argument for --error-format must be `human`, `json` or \
1633 `short` (instead was `{}`)",
1638 ErrorOutputType::HumanReadable(color)
1641 let unparsed_crate_types = matches.opt_strs("crate-type");
1642 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
1643 .unwrap_or_else(|e| early_error(error_format, &e[..]));
1645 let mut lint_opts = vec![];
1646 let mut describe_lints = false;
1648 for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
1649 for lint_name in matches.opt_strs(level.as_str()) {
1650 if lint_name == "help" {
1651 describe_lints = true;
1653 lint_opts.push((lint_name.replace("-", "_"), level));
1658 let lint_cap = matches.opt_str("cap-lints").map(|cap| {
1659 lint::Level::from_str(&cap).unwrap_or_else(|| {
1660 early_error(error_format, &format!("unknown lint level: `{}`", cap))
1664 let mut debugging_opts = build_debugging_options(matches, error_format);
1666 if !debugging_opts.unstable_options && error_format == ErrorOutputType::Json(true) {
1667 early_error(ErrorOutputType::Json(false),
1668 "--error-format=pretty-json is unstable");
1671 let mut output_types = BTreeMap::new();
1672 if !debugging_opts.parse_only {
1673 for list in matches.opt_strs("emit") {
1674 for output_type in list.split(',') {
1675 let mut parts = output_type.splitn(2, '=');
1676 let shorthand = parts.next().unwrap();
1677 let output_type = match OutputType::from_shorthand(shorthand) {
1678 Some(output_type) => output_type,
1679 None => early_error(error_format, &format!(
1680 "unknown emission type: `{}` - expected one of: {}",
1681 shorthand, OutputType::shorthands_display(),
1684 let path = parts.next().map(PathBuf::from);
1685 output_types.insert(output_type, path);
1689 if output_types.is_empty() {
1690 output_types.insert(OutputType::Exe, None);
1693 let remap_path_prefix_sources = debugging_opts.remap_path_prefix_from.len();
1694 let remap_path_prefix_targets = debugging_opts.remap_path_prefix_from.len();
1696 if remap_path_prefix_targets < remap_path_prefix_sources {
1697 for source in &debugging_opts.remap_path_prefix_from[remap_path_prefix_targets..] {
1698 early_error(error_format,
1699 &format!("option `-Zremap-path-prefix-from='{}'` does not have \
1700 a corresponding `-Zremap-path-prefix-to`", source.display()))
1702 } else if remap_path_prefix_targets > remap_path_prefix_sources {
1703 for target in &debugging_opts.remap_path_prefix_to[remap_path_prefix_sources..] {
1704 early_error(error_format,
1705 &format!("option `-Zremap-path-prefix-to='{}'` does not have \
1706 a corresponding `-Zremap-path-prefix-from`", target.display()))
1710 let mut cg = build_codegen_options(matches, error_format);
1711 let mut codegen_units = cg.codegen_units;
1712 let mut disable_thinlto = false;
1714 // Issue #30063: if user requests llvm-related output to one
1715 // particular path, disable codegen-units.
1716 let incompatible: Vec<_> = output_types.iter()
1717 .map(|ot_path| ot_path.0)
1719 !ot.is_compatible_with_codegen_units_and_single_output_file()
1721 .map(|ot| ot.shorthand())
1723 if !incompatible.is_empty() {
1724 match codegen_units {
1725 Some(n) if n > 1 => {
1726 if matches.opt_present("o") {
1727 for ot in &incompatible {
1728 early_warn(error_format, &format!("--emit={} with -o incompatible with \
1729 -C codegen-units=N for N > 1",
1732 early_warn(error_format, "resetting to default -C codegen-units=1");
1733 codegen_units = Some(1);
1734 disable_thinlto = true;
1738 codegen_units = Some(1);
1739 disable_thinlto = true;
1744 if debugging_opts.query_threads == Some(0) {
1745 early_error(error_format, "Value for query threads must be a positive nonzero integer");
1748 if codegen_units == Some(0) {
1749 early_error(error_format, "Value for codegen units must be a positive nonzero integer");
1752 let incremental = match (&debugging_opts.incremental, &cg.incremental) {
1753 (&Some(ref path1), &Some(ref path2)) => {
1755 early_error(error_format,
1756 &format!("conflicting paths for `-Z incremental` and \
1757 `-C incremental` specified: {} versus {}",
1764 (&Some(ref path), &None) => Some(path),
1765 (&None, &Some(ref path)) => Some(path),
1766 (&None, &None) => None,
1767 }.map(|m| PathBuf::from(m));
1769 if cg.lto != Lto::No && incremental.is_some() {
1770 early_error(error_format, "can't perform LTO when compiling incrementally");
1773 let mut prints = Vec::<PrintRequest>::new();
1774 if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
1775 prints.push(PrintRequest::TargetCPUs);
1776 cg.target_cpu = None;
1778 if cg.target_feature == "help" {
1779 prints.push(PrintRequest::TargetFeatures);
1780 cg.target_feature = "".to_string();
1782 if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
1783 prints.push(PrintRequest::RelocationModels);
1784 cg.relocation_model = None;
1786 if cg.code_model.as_ref().map_or(false, |s| s == "help") {
1787 prints.push(PrintRequest::CodeModels);
1788 cg.code_model = None;
1790 if debugging_opts.tls_model.as_ref().map_or(false, |s| s == "help") {
1791 prints.push(PrintRequest::TlsModels);
1792 debugging_opts.tls_model = None;
1797 let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
1798 let target = matches.opt_str("target").unwrap_or(
1799 host_triple().to_string());
1801 if matches.opt_present("O") {
1802 if cg.opt_level.is_some() {
1803 early_error(error_format, "-O and -C opt-level both provided");
1807 match (cg.opt_level.as_ref().map(String::as_ref),
1808 nightly_options::is_nightly_build()) {
1809 (None, _) => OptLevel::No,
1810 (Some("0"), _) => OptLevel::No,
1811 (Some("1"), _) => OptLevel::Less,
1812 (Some("2"), _) => OptLevel::Default,
1813 (Some("3"), _) => OptLevel::Aggressive,
1814 (Some("s"), true) => OptLevel::Size,
1815 (Some("z"), true) => OptLevel::SizeMin,
1816 (Some("s"), false) | (Some("z"), false) => {
1817 early_error(error_format, &format!("the optimizations s or z are only \
1818 accepted on the nightly compiler"));
1821 early_error(error_format, &format!("optimization level needs to be \
1822 between 0-3 (instead was `{}`)",
1828 let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
1829 let debuginfo = if matches.opt_present("g") {
1830 if cg.debuginfo.is_some() {
1831 early_error(error_format, "-g and -C debuginfo both provided");
1835 match cg.debuginfo {
1836 None | Some(0) => NoDebugInfo,
1837 Some(1) => LimitedDebugInfo,
1838 Some(2) => FullDebugInfo,
1840 early_error(error_format, &format!("debug info level needs to be between \
1841 0-2 (instead was `{}`)",
1847 let mut search_paths = SearchPaths::new();
1848 for s in &matches.opt_strs("L") {
1849 search_paths.add_path(&s[..], error_format);
1852 let libs = matches.opt_strs("l").into_iter().map(|s| {
1853 // Parse string of the form "[KIND=]lib[:new_name]",
1854 // where KIND is one of "dylib", "framework", "static".
1855 let mut parts = s.splitn(2, '=');
1856 let kind = parts.next().unwrap();
1857 let (name, kind) = match (parts.next(), kind) {
1858 (None, name) => (name, None),
1859 (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
1860 (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
1861 (Some(name), "static") => (name, Some(cstore::NativeStatic)),
1862 (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
1864 early_error(error_format, &format!("unknown library kind `{}`, expected \
1865 one of dylib, framework, or static",
1869 if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
1870 early_error(error_format, &format!("the library kind 'static-nobundle' is only \
1871 accepted on the nightly compiler"));
1873 let mut name_parts = name.splitn(2, ':');
1874 let name = name_parts.next().unwrap();
1875 let new_name = name_parts.next();
1876 (name.to_string(), new_name.map(|n| n.to_string()), kind)
1879 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
1880 let test = matches.opt_present("test");
1882 prints.extend(matches.opt_strs("print").into_iter().map(|s| {
1884 "crate-name" => PrintRequest::CrateName,
1885 "file-names" => PrintRequest::FileNames,
1886 "sysroot" => PrintRequest::Sysroot,
1887 "cfg" => PrintRequest::Cfg,
1888 "target-list" => PrintRequest::TargetList,
1889 "target-cpus" => PrintRequest::TargetCPUs,
1890 "target-features" => PrintRequest::TargetFeatures,
1891 "relocation-models" => PrintRequest::RelocationModels,
1892 "code-models" => PrintRequest::CodeModels,
1893 "tls-models" => PrintRequest::TlsModels,
1894 "native-static-libs" => PrintRequest::NativeStaticLibs,
1895 "target-spec-json" => {
1896 if nightly_options::is_unstable_enabled(matches) {
1897 PrintRequest::TargetSpec
1899 early_error(error_format,
1900 &format!("the `-Z unstable-options` flag must also be passed to \
1901 enable the target-spec-json print option"));
1905 early_error(error_format, &format!("unknown print request `{}`", req))
1910 let borrowck_mode = match debugging_opts.borrowck.as_ref().map(|s| &s[..]) {
1911 None | Some("ast") => BorrowckMode::Ast,
1912 Some("mir") => BorrowckMode::Mir,
1913 Some("compare") => BorrowckMode::Compare,
1915 early_error(error_format, &format!("unknown borrowck mode `{}`", m))
1919 if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
1920 early_warn(error_format, "-C remark will not show source locations without \
1924 let mut externs = BTreeMap::new();
1925 for arg in &matches.opt_strs("extern") {
1926 let mut parts = arg.splitn(2, '=');
1927 let name = match parts.next() {
1929 None => early_error(error_format, "--extern value must not be empty"),
1931 let location = match parts.next() {
1933 None => early_error(error_format, "--extern value must be of the format `foo=bar`"),
1936 externs.entry(name.to_string())
1937 .or_insert_with(BTreeSet::new)
1938 .insert(location.to_string());
1941 let crate_name = matches.opt_str("crate-name");
1945 optimize: opt_level,
1950 output_types: OutputTypes(output_types),
1952 maybe_sysroot: sysroot_opt,
1953 target_triple: target,
1961 externs: Externs(externs),
1965 unstable_features: UnstableFeatures::from_environment(),
1967 actually_rustdoc: false,
1968 cli_forced_codegen_units: codegen_units,
1969 cli_forced_thinlto_off: disable_thinlto,
1974 pub fn parse_crate_types_from_list(list_list: Vec<String>)
1975 -> Result<Vec<CrateType>, String> {
1976 let mut crate_types: Vec<CrateType> = Vec::new();
1977 for unparsed_crate_type in &list_list {
1978 for part in unparsed_crate_type.split(',') {
1979 let new_part = match part {
1980 "lib" => default_lib_output(),
1981 "rlib" => CrateTypeRlib,
1982 "staticlib" => CrateTypeStaticlib,
1983 "dylib" => CrateTypeDylib,
1984 "cdylib" => CrateTypeCdylib,
1985 "bin" => CrateTypeExecutable,
1986 "proc-macro" => CrateTypeProcMacro,
1988 return Err(format!("unknown crate type: `{}`",
1992 if !crate_types.contains(&new_part) {
1993 crate_types.push(new_part)
2001 pub mod nightly_options {
2003 use syntax::feature_gate::UnstableFeatures;
2004 use super::{ErrorOutputType, OptionStability, RustcOptGroup};
2005 use session::early_error;
2007 pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
2008 is_nightly_build() && matches.opt_strs("Z").iter().any(|x| *x == "unstable-options")
2011 pub fn is_nightly_build() -> bool {
2012 UnstableFeatures::from_environment().is_nightly_build()
2015 pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
2016 let has_z_unstable_option = matches.opt_strs("Z").iter().any(|x| *x == "unstable-options");
2017 let really_allows_unstable_options = UnstableFeatures::from_environment()
2018 .is_nightly_build();
2020 for opt in flags.iter() {
2021 if opt.stability == OptionStability::Stable {
2024 if !matches.opt_present(opt.name) {
2027 if opt.name != "Z" && !has_z_unstable_option {
2028 early_error(ErrorOutputType::default(),
2029 &format!("the `-Z unstable-options` flag must also be passed to enable \
2033 if really_allows_unstable_options {
2036 match opt.stability {
2037 OptionStability::Unstable => {
2038 let msg = format!("the option `{}` is only accepted on the \
2039 nightly compiler", opt.name);
2040 early_error(ErrorOutputType::default(), &msg);
2042 OptionStability::Stable => {}
2048 impl fmt::Display for CrateType {
2049 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2051 CrateTypeExecutable => "bin".fmt(f),
2052 CrateTypeDylib => "dylib".fmt(f),
2053 CrateTypeRlib => "rlib".fmt(f),
2054 CrateTypeStaticlib => "staticlib".fmt(f),
2055 CrateTypeCdylib => "cdylib".fmt(f),
2056 CrateTypeProcMacro => "proc-macro".fmt(f),
2061 /// Commandline arguments passed to the compiler have to be incorporated with
2062 /// the dependency tracking system for incremental compilation. This module
2063 /// provides some utilities to make this more convenient.
2065 /// The values of all commandline arguments that are relevant for dependency
2066 /// tracking are hashed into a single value that determines whether the
2067 /// incremental compilation cache can be re-used or not. This hashing is done
2068 /// via the DepTrackingHash trait defined below, since the standard Hash
2069 /// implementation might not be suitable (e.g. arguments are stored in a Vec,
2070 /// the hash of which is order dependent, but we might not want the order of
2071 /// arguments to make a difference for the hash).
2073 /// However, since the value provided by Hash::hash often *is* suitable,
2074 /// especially for primitive types, there is the
2075 /// impl_dep_tracking_hash_via_hash!() macro that allows to simply reuse the
2076 /// Hash implementation for DepTrackingHash. It's important though that
2077 /// we have an opt-in scheme here, so one is hopefully forced to think about
2078 /// how the hash should be calculated when adding a new commandline argument.
2082 use session::search_paths::{PathKind, SearchPaths};
2083 use std::collections::BTreeMap;
2084 use std::hash::Hash;
2085 use std::path::PathBuf;
2086 use std::collections::hash_map::DefaultHasher;
2087 use super::{Passes, CrateType, OptLevel, DebugInfoLevel, Lto,
2088 OutputTypes, Externs, ErrorOutputType, Sanitizer};
2089 use syntax::feature_gate::UnstableFeatures;
2090 use rustc_back::{PanicStrategy, RelroLevel};
2092 pub trait DepTrackingHash {
2093 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);
2096 macro_rules! impl_dep_tracking_hash_via_hash {
2098 impl DepTrackingHash for $t {
2099 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
2100 Hash::hash(self, hasher);
2106 macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
2108 impl DepTrackingHash for Vec<$t> {
2109 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2110 let mut elems: Vec<&$t> = self.iter().collect();
2112 Hash::hash(&elems.len(), hasher);
2113 for (index, elem) in elems.iter().enumerate() {
2114 Hash::hash(&index, hasher);
2115 DepTrackingHash::hash(*elem, hasher, error_format);
2122 impl_dep_tracking_hash_via_hash!(bool);
2123 impl_dep_tracking_hash_via_hash!(usize);
2124 impl_dep_tracking_hash_via_hash!(u64);
2125 impl_dep_tracking_hash_via_hash!(String);
2126 impl_dep_tracking_hash_via_hash!(PathBuf);
2127 impl_dep_tracking_hash_via_hash!(lint::Level);
2128 impl_dep_tracking_hash_via_hash!(Option<bool>);
2129 impl_dep_tracking_hash_via_hash!(Option<usize>);
2130 impl_dep_tracking_hash_via_hash!(Option<String>);
2131 impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
2132 impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
2133 impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
2134 impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
2135 impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
2136 impl_dep_tracking_hash_via_hash!(Option<cstore::NativeLibraryKind>);
2137 impl_dep_tracking_hash_via_hash!(CrateType);
2138 impl_dep_tracking_hash_via_hash!(PanicStrategy);
2139 impl_dep_tracking_hash_via_hash!(RelroLevel);
2140 impl_dep_tracking_hash_via_hash!(Passes);
2141 impl_dep_tracking_hash_via_hash!(OptLevel);
2142 impl_dep_tracking_hash_via_hash!(Lto);
2143 impl_dep_tracking_hash_via_hash!(DebugInfoLevel);
2144 impl_dep_tracking_hash_via_hash!(UnstableFeatures);
2145 impl_dep_tracking_hash_via_hash!(Externs);
2146 impl_dep_tracking_hash_via_hash!(OutputTypes);
2147 impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
2148 impl_dep_tracking_hash_via_hash!(Sanitizer);
2149 impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
2151 impl_dep_tracking_hash_for_sortable_vec_of!(String);
2152 impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
2153 impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
2154 impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
2155 impl_dep_tracking_hash_for_sortable_vec_of!((String, Option<String>,
2156 Option<cstore::NativeLibraryKind>));
2157 impl_dep_tracking_hash_for_sortable_vec_of!((String, u64));
2158 impl DepTrackingHash for SearchPaths {
2159 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
2160 let mut elems: Vec<_> = self
2161 .iter(PathKind::All)
2164 Hash::hash(&elems, hasher);
2168 impl<T1, T2> DepTrackingHash for (T1, T2)
2169 where T1: DepTrackingHash,
2172 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2173 Hash::hash(&0, hasher);
2174 DepTrackingHash::hash(&self.0, hasher, error_format);
2175 Hash::hash(&1, hasher);
2176 DepTrackingHash::hash(&self.1, hasher, error_format);
2180 impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
2181 where T1: DepTrackingHash,
2182 T2: DepTrackingHash,
2185 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2186 Hash::hash(&0, hasher);
2187 DepTrackingHash::hash(&self.0, hasher, error_format);
2188 Hash::hash(&1, hasher);
2189 DepTrackingHash::hash(&self.1, hasher, error_format);
2190 Hash::hash(&2, hasher);
2191 DepTrackingHash::hash(&self.2, hasher, error_format);
2195 // This is a stable hash because BTreeMap is a sorted container
2196 pub fn stable_hash(sub_hashes: BTreeMap<&'static str, &DepTrackingHash>,
2197 hasher: &mut DefaultHasher,
2198 error_format: ErrorOutputType) {
2199 for (key, sub_hash) in sub_hashes {
2200 // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
2201 // the keys, as they are just plain strings
2202 Hash::hash(&key.len(), hasher);
2203 Hash::hash(key, hasher);
2204 sub_hash.hash(hasher, error_format);
2215 use session::config::{build_configuration, build_session_options_and_crate_config};
2216 use session::config::Lto;
2217 use session::build_session;
2218 use std::collections::{BTreeMap, BTreeSet};
2219 use std::iter::FromIterator;
2220 use std::path::PathBuf;
2221 use super::{OutputType, OutputTypes, Externs};
2222 use rustc_back::{PanicStrategy, RelroLevel};
2223 use syntax::symbol::Symbol;
2225 fn optgroups() -> getopts::Options {
2226 let mut opts = getopts::Options::new();
2227 for group in super::rustc_optgroups() {
2228 (group.apply)(&mut opts);
2233 fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
2234 BTreeMap::from_iter(entries.into_iter())
2237 fn mk_set<V: Ord>(entries: Vec<V>) -> BTreeSet<V> {
2238 BTreeSet::from_iter(entries.into_iter())
2241 // When the user supplies --test we should implicitly supply --cfg test
2243 fn test_switch_implies_cfg_test() {
2245 &match optgroups().parse(&["--test".to_string()]) {
2247 Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
2249 let registry = errors::registry::Registry::new(&[]);
2250 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2251 let sess = build_session(sessopts, None, registry);
2252 let cfg = build_configuration(&sess, cfg);
2253 assert!(cfg.contains(&(Symbol::intern("test"), None)));
2256 // When the user supplies --test and --cfg test, don't implicitly add
2257 // another --cfg test
2259 fn test_switch_implies_cfg_test_unless_cfg_test() {
2261 &match optgroups().parse(&["--test".to_string(), "--cfg=test".to_string()]) {
2264 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
2267 let registry = errors::registry::Registry::new(&[]);
2268 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2269 let sess = build_session(sessopts, None, registry);
2270 let cfg = build_configuration(&sess, cfg);
2271 let mut test_items = cfg.iter().filter(|&&(name, _)| name == "test");
2272 assert!(test_items.next().is_some());
2273 assert!(test_items.next().is_none());
2277 fn test_can_print_warnings() {
2279 let matches = optgroups().parse(&[
2280 "-Awarnings".to_string()
2282 let registry = errors::registry::Registry::new(&[]);
2283 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2284 let sess = build_session(sessopts, None, registry);
2285 assert!(!sess.diagnostic().flags.can_emit_warnings);
2289 let matches = optgroups().parse(&[
2290 "-Awarnings".to_string(),
2291 "-Dwarnings".to_string()
2293 let registry = errors::registry::Registry::new(&[]);
2294 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2295 let sess = build_session(sessopts, None, registry);
2296 assert!(sess.diagnostic().flags.can_emit_warnings);
2300 let matches = optgroups().parse(&[
2301 "-Adead_code".to_string()
2303 let registry = errors::registry::Registry::new(&[]);
2304 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2305 let sess = build_session(sessopts, None, registry);
2306 assert!(sess.diagnostic().flags.can_emit_warnings);
2311 fn test_output_types_tracking_hash_different_paths() {
2312 let mut v1 = super::basic_options();
2313 let mut v2 = super::basic_options();
2314 let mut v3 = super::basic_options();
2316 v1.output_types = OutputTypes::new(&[(OutputType::Exe,
2317 Some(PathBuf::from("./some/thing")))]);
2318 v2.output_types = OutputTypes::new(&[(OutputType::Exe,
2319 Some(PathBuf::from("/some/thing")))]);
2320 v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
2322 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2323 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2324 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2327 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2328 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2329 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2333 fn test_output_types_tracking_hash_different_construction_order() {
2334 let mut v1 = super::basic_options();
2335 let mut v2 = super::basic_options();
2337 v1.output_types = OutputTypes::new(&[
2338 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2339 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2342 v2.output_types = OutputTypes::new(&[
2343 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2344 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2347 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2350 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2354 fn test_externs_tracking_hash_different_values() {
2355 let mut v1 = super::basic_options();
2356 let mut v2 = super::basic_options();
2357 let mut v3 = super::basic_options();
2359 v1.externs = Externs::new(mk_map(vec![
2360 (String::from("a"), mk_set(vec![String::from("b"),
2361 String::from("c")])),
2362 (String::from("d"), mk_set(vec![String::from("e"),
2363 String::from("f")])),
2366 v2.externs = Externs::new(mk_map(vec![
2367 (String::from("a"), mk_set(vec![String::from("b"),
2368 String::from("c")])),
2369 (String::from("X"), mk_set(vec![String::from("e"),
2370 String::from("f")])),
2373 v3.externs = Externs::new(mk_map(vec![
2374 (String::from("a"), mk_set(vec![String::from("b"),
2375 String::from("c")])),
2376 (String::from("d"), mk_set(vec![String::from("X"),
2377 String::from("f")])),
2380 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2381 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2382 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2385 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2386 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2387 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2391 fn test_externs_tracking_hash_different_construction_order() {
2392 let mut v1 = super::basic_options();
2393 let mut v2 = super::basic_options();
2394 let mut v3 = super::basic_options();
2396 v1.externs = Externs::new(mk_map(vec![
2397 (String::from("a"), mk_set(vec![String::from("b"),
2398 String::from("c")])),
2399 (String::from("d"), mk_set(vec![String::from("e"),
2400 String::from("f")])),
2403 v2.externs = Externs::new(mk_map(vec![
2404 (String::from("d"), mk_set(vec![String::from("e"),
2405 String::from("f")])),
2406 (String::from("a"), mk_set(vec![String::from("b"),
2407 String::from("c")])),
2410 v3.externs = Externs::new(mk_map(vec![
2411 (String::from("a"), mk_set(vec![String::from("b"),
2412 String::from("c")])),
2413 (String::from("d"), mk_set(vec![String::from("f"),
2414 String::from("e")])),
2417 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2418 assert_eq!(v1.dep_tracking_hash(), v3.dep_tracking_hash());
2419 assert_eq!(v2.dep_tracking_hash(), v3.dep_tracking_hash());
2422 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2423 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2424 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2428 fn test_lints_tracking_hash_different_values() {
2429 let mut v1 = super::basic_options();
2430 let mut v2 = super::basic_options();
2431 let mut v3 = super::basic_options();
2433 v1.lint_opts = vec![(String::from("a"), lint::Allow),
2434 (String::from("b"), lint::Warn),
2435 (String::from("c"), lint::Deny),
2436 (String::from("d"), lint::Forbid)];
2438 v2.lint_opts = vec![(String::from("a"), lint::Allow),
2439 (String::from("b"), lint::Warn),
2440 (String::from("X"), lint::Deny),
2441 (String::from("d"), lint::Forbid)];
2443 v3.lint_opts = vec![(String::from("a"), lint::Allow),
2444 (String::from("b"), lint::Warn),
2445 (String::from("c"), lint::Forbid),
2446 (String::from("d"), lint::Deny)];
2448 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2449 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2450 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2453 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2454 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2455 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2459 fn test_lints_tracking_hash_different_construction_order() {
2460 let mut v1 = super::basic_options();
2461 let mut v2 = super::basic_options();
2463 v1.lint_opts = vec![(String::from("a"), lint::Allow),
2464 (String::from("b"), lint::Warn),
2465 (String::from("c"), lint::Deny),
2466 (String::from("d"), lint::Forbid)];
2468 v2.lint_opts = vec![(String::from("a"), lint::Allow),
2469 (String::from("c"), lint::Deny),
2470 (String::from("b"), lint::Warn),
2471 (String::from("d"), lint::Forbid)];
2473 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2476 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2477 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2481 fn test_search_paths_tracking_hash_different_values() {
2482 let mut v1 = super::basic_options();
2483 let mut v2 = super::basic_options();
2484 let mut v3 = super::basic_options();
2485 let mut v4 = super::basic_options();
2486 let mut v5 = super::basic_options();
2489 v1.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2490 v1.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2491 v1.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2492 v1.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2493 v1.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2496 v2.search_paths.add_path("native=XXX", super::ErrorOutputType::Json(false));
2497 v2.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2498 v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2499 v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2500 v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2503 v2.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2504 v2.search_paths.add_path("crate=XXX", super::ErrorOutputType::Json(false));
2505 v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2506 v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2507 v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2509 // Dependency changed
2510 v3.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2511 v3.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2512 v3.search_paths.add_path("dependency=XXX", super::ErrorOutputType::Json(false));
2513 v3.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2514 v3.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2516 // Framework changed
2517 v4.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2518 v4.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2519 v4.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2520 v4.search_paths.add_path("framework=XXX", super::ErrorOutputType::Json(false));
2521 v4.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2524 v5.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2525 v5.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2526 v5.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2527 v5.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2528 v5.search_paths.add_path("all=XXX", 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());
2533 assert!(v1.dep_tracking_hash() != v5.dep_tracking_hash());
2536 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2537 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2538 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2539 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2540 assert_eq!(v5.dep_tracking_hash(), v5.clone().dep_tracking_hash());
2544 fn test_search_paths_tracking_hash_different_order() {
2545 let mut v1 = super::basic_options();
2546 let mut v2 = super::basic_options();
2547 let mut v3 = super::basic_options();
2548 let mut v4 = super::basic_options();
2551 v1.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2552 v1.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2553 v1.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2554 v1.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2555 v1.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2557 v2.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2558 v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2559 v2.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2560 v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2561 v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2563 v3.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2564 v3.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2565 v3.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2566 v3.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2567 v3.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2569 v4.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2570 v4.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2571 v4.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2572 v4.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2573 v4.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2575 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2576 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2577 assert!(v1.dep_tracking_hash() == v4.dep_tracking_hash());
2580 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2581 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2582 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2583 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2587 fn test_native_libs_tracking_hash_different_values() {
2588 let mut v1 = super::basic_options();
2589 let mut v2 = super::basic_options();
2590 let mut v3 = super::basic_options();
2591 let mut v4 = super::basic_options();
2594 v1.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2595 (String::from("b"), None, Some(cstore::NativeFramework)),
2596 (String::from("c"), None, Some(cstore::NativeUnknown))];
2599 v2.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2600 (String::from("X"), None, Some(cstore::NativeFramework)),
2601 (String::from("c"), None, Some(cstore::NativeUnknown))];
2604 v3.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2605 (String::from("b"), None, Some(cstore::NativeStatic)),
2606 (String::from("c"), None, Some(cstore::NativeUnknown))];
2609 v4.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2610 (String::from("b"), Some(String::from("X")), Some(cstore::NativeFramework)),
2611 (String::from("c"), None, Some(cstore::NativeUnknown))];
2613 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2614 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2615 assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
2618 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2619 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2620 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2621 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2625 fn test_native_libs_tracking_hash_different_order() {
2626 let mut v1 = super::basic_options();
2627 let mut v2 = super::basic_options();
2628 let mut v3 = super::basic_options();
2631 v1.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2632 (String::from("b"), None, Some(cstore::NativeFramework)),
2633 (String::from("c"), None, Some(cstore::NativeUnknown))];
2635 v2.libs = vec![(String::from("b"), None, Some(cstore::NativeFramework)),
2636 (String::from("a"), None, Some(cstore::NativeStatic)),
2637 (String::from("c"), None, Some(cstore::NativeUnknown))];
2639 v3.libs = vec![(String::from("c"), None, Some(cstore::NativeUnknown)),
2640 (String::from("a"), None, Some(cstore::NativeStatic)),
2641 (String::from("b"), None, Some(cstore::NativeFramework))];
2643 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2644 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2645 assert!(v2.dep_tracking_hash() == v3.dep_tracking_hash());
2648 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2649 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2650 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2654 fn test_codegen_options_tracking_hash() {
2655 let reference = super::basic_options();
2656 let mut opts = super::basic_options();
2658 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2659 opts.cg.ar = Some(String::from("abc"));
2660 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2662 opts.cg.linker = Some(PathBuf::from("linker"));
2663 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2665 opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
2666 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2668 opts.cg.link_dead_code = true;
2669 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2671 opts.cg.rpath = true;
2672 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2674 opts.cg.extra_filename = String::from("extra-filename");
2675 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2677 opts.cg.codegen_units = Some(42);
2678 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2680 opts.cg.remark = super::SomePasses(vec![String::from("pass1"),
2681 String::from("pass2")]);
2682 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2684 opts.cg.save_temps = true;
2685 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2687 opts.cg.incremental = Some(String::from("abc"));
2688 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2691 // Make sure changing a [TRACKED] option changes the hash
2692 opts = reference.clone();
2693 opts.cg.lto = Lto::Fat;
2694 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2696 opts = reference.clone();
2697 opts.cg.target_cpu = Some(String::from("abc"));
2698 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2700 opts = reference.clone();
2701 opts.cg.target_feature = String::from("all the features, all of them");
2702 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2704 opts = reference.clone();
2705 opts.cg.passes = vec![String::from("1"), String::from("2")];
2706 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2708 opts = reference.clone();
2709 opts.cg.llvm_args = vec![String::from("1"), String::from("2")];
2710 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2712 opts = reference.clone();
2713 opts.cg.overflow_checks = Some(true);
2714 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2716 opts = reference.clone();
2717 opts.cg.no_prepopulate_passes = true;
2718 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2720 opts = reference.clone();
2721 opts.cg.no_vectorize_loops = true;
2722 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2724 opts = reference.clone();
2725 opts.cg.no_vectorize_slp = true;
2726 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2728 opts = reference.clone();
2729 opts.cg.soft_float = true;
2730 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2732 opts = reference.clone();
2733 opts.cg.prefer_dynamic = true;
2734 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2736 opts = reference.clone();
2737 opts.cg.no_integrated_as = true;
2738 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2740 opts = reference.clone();
2741 opts.cg.no_redzone = Some(true);
2742 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2744 opts = reference.clone();
2745 opts.cg.relocation_model = Some(String::from("relocation model"));
2746 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2748 opts = reference.clone();
2749 opts.cg.code_model = Some(String::from("code model"));
2750 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2752 opts = reference.clone();
2753 opts.debugging_opts.tls_model = Some(String::from("tls model"));
2754 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2756 opts = reference.clone();
2757 opts.cg.metadata = vec![String::from("A"), String::from("B")];
2758 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2760 opts = reference.clone();
2761 opts.cg.debuginfo = Some(0xdeadbeef);
2762 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2764 opts = reference.clone();
2765 opts.cg.debuginfo = Some(0xba5eba11);
2766 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2768 opts = reference.clone();
2769 opts.cg.debug_assertions = Some(true);
2770 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2772 opts = reference.clone();
2773 opts.cg.inline_threshold = Some(0xf007ba11);
2774 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2776 opts = reference.clone();
2777 opts.cg.panic = Some(PanicStrategy::Abort);
2778 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2782 fn test_debugging_options_tracking_hash() {
2783 let reference = super::basic_options();
2784 let mut opts = super::basic_options();
2786 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2787 opts.debugging_opts.verbose = true;
2788 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2789 opts.debugging_opts.time_passes = true;
2790 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2791 opts.debugging_opts.count_llvm_insns = true;
2792 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2793 opts.debugging_opts.time_llvm_passes = true;
2794 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2795 opts.debugging_opts.input_stats = true;
2796 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2797 opts.debugging_opts.trans_stats = true;
2798 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2799 opts.debugging_opts.borrowck_stats = true;
2800 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2801 opts.debugging_opts.meta_stats = true;
2802 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2803 opts.debugging_opts.print_link_args = true;
2804 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2805 opts.debugging_opts.print_llvm_passes = true;
2806 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2807 opts.debugging_opts.ast_json = true;
2808 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2809 opts.debugging_opts.ast_json_noexpand = true;
2810 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2811 opts.debugging_opts.ls = true;
2812 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2813 opts.debugging_opts.save_analysis = true;
2814 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2815 opts.debugging_opts.flowgraph_print_loans = true;
2816 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2817 opts.debugging_opts.flowgraph_print_moves = true;
2818 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2819 opts.debugging_opts.flowgraph_print_assigns = true;
2820 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2821 opts.debugging_opts.flowgraph_print_all = true;
2822 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2823 opts.debugging_opts.print_region_graph = true;
2824 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2825 opts.debugging_opts.parse_only = true;
2826 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2827 opts.debugging_opts.incremental = Some(String::from("abc"));
2828 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2829 opts.debugging_opts.dump_dep_graph = true;
2830 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2831 opts.debugging_opts.query_dep_graph = true;
2832 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2833 opts.debugging_opts.no_analysis = true;
2834 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2835 opts.debugging_opts.unstable_options = true;
2836 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2837 opts.debugging_opts.trace_macros = true;
2838 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2839 opts.debugging_opts.keep_hygiene_data = true;
2840 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2841 opts.debugging_opts.keep_ast = true;
2842 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2843 opts.debugging_opts.print_trans_items = Some(String::from("abc"));
2844 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2845 opts.debugging_opts.dump_mir = Some(String::from("abc"));
2846 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2847 opts.debugging_opts.dump_mir_dir = String::from("abc");
2848 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2849 opts.debugging_opts.dump_mir_graphviz = true;
2850 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2852 // Make sure changing a [TRACKED] option changes the hash
2853 opts = reference.clone();
2854 opts.debugging_opts.asm_comments = true;
2855 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2857 opts = reference.clone();
2858 opts.debugging_opts.no_verify = true;
2859 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2861 opts = reference.clone();
2862 opts.debugging_opts.no_landing_pads = true;
2863 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2865 opts = reference.clone();
2866 opts.debugging_opts.fewer_names = true;
2867 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2869 opts = reference.clone();
2870 opts.debugging_opts.no_trans = true;
2871 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2873 opts = reference.clone();
2874 opts.debugging_opts.treat_err_as_bug = true;
2875 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2877 opts = reference.clone();
2878 opts.debugging_opts.continue_parse_after_error = true;
2879 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2881 opts = reference.clone();
2882 opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
2883 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2885 opts = reference.clone();
2886 opts.debugging_opts.force_overflow_checks = Some(true);
2887 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2889 opts = reference.clone();
2890 opts.debugging_opts.enable_nonzeroing_move_hints = true;
2891 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2893 opts = reference.clone();
2894 opts.debugging_opts.show_span = Some(String::from("abc"));
2895 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2897 opts = reference.clone();
2898 opts.debugging_opts.mir_opt_level = 3;
2899 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2901 opts = reference.clone();
2902 opts.debugging_opts.relro_level = Some(RelroLevel::Full);
2903 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());