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 teach: bool = (false, parse_bool, [TRACKED],
1171 "show extended diagnostic help"),
1172 continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
1173 "attempt to recover from parse errors (experimental)"),
1174 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1175 "enable incremental compilation (experimental)"),
1176 incremental_queries: bool = (true, parse_bool, [UNTRACKED],
1177 "enable incremental compilation support for queries (experimental)"),
1178 incremental_info: bool = (false, parse_bool, [UNTRACKED],
1179 "print high-level information about incremental reuse (or the lack thereof)"),
1180 incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
1181 "dump hash information in textual format to stdout"),
1182 incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
1183 "verify incr. comp. hashes of green query instances"),
1184 incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
1185 "ignore spans during ICH computation -- used for testing"),
1186 dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1187 "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
1188 query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1189 "enable queries of the dependency graph for regression testing"),
1190 profile_queries: bool = (false, parse_bool, [UNTRACKED],
1191 "trace and profile the queries of the incremental compilation framework"),
1192 profile_queries_and_keys: bool = (false, parse_bool, [UNTRACKED],
1193 "trace and profile the queries and keys of the incremental compilation framework"),
1194 no_analysis: bool = (false, parse_bool, [UNTRACKED],
1195 "parse and expand the source, but run no analysis"),
1196 extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1197 "load extra plugins"),
1198 unstable_options: bool = (false, parse_bool, [UNTRACKED],
1199 "adds unstable command line options to rustc interface"),
1200 force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1201 "force overflow checks on or off"),
1202 trace_macros: bool = (false, parse_bool, [UNTRACKED],
1203 "for every macro invocation, print its name and arguments"),
1204 debug_macros: bool = (false, parse_bool, [TRACKED],
1205 "emit line numbers debug info inside macros"),
1206 enable_nonzeroing_move_hints: bool = (false, parse_bool, [TRACKED],
1207 "force nonzeroing move optimization on"),
1208 keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
1209 "don't clear the hygiene data after analysis"),
1210 keep_ast: bool = (false, parse_bool, [UNTRACKED],
1211 "keep the AST after lowering it to HIR"),
1212 show_span: Option<String> = (None, parse_opt_string, [TRACKED],
1213 "show spans for compiler debugging (expr|pat|ty)"),
1214 print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
1215 "print layout information for each type encountered"),
1216 print_trans_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
1217 "print the result of the translation item collection pass"),
1218 mir_opt_level: usize = (1, parse_uint, [TRACKED],
1219 "set the MIR optimization level (0-3, default: 1)"),
1220 mutable_noalias: bool = (false, parse_bool, [UNTRACKED],
1221 "emit noalias metadata for mutable references"),
1222 dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1223 "dump MIR state at various points in translation"),
1224 dump_mir_dir: String = (String::from("mir_dump"), parse_string, [UNTRACKED],
1225 "the directory the MIR is dumped into"),
1226 dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
1227 "in addition to `.mir` files, create graphviz `.dot` files"),
1228 dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
1229 "if set, exclude the pass number when dumping MIR (used in tests)"),
1230 mir_emit_validate: usize = (0, parse_uint, [TRACKED],
1231 "emit Validate MIR statements, interpreted e.g. by miri (0: do not emit; 1: if function \
1232 contains unsafe block, only validate arguments; 2: always emit full validation)"),
1233 perf_stats: bool = (false, parse_bool, [UNTRACKED],
1234 "print some performance-related statistics"),
1235 hir_stats: bool = (false, parse_bool, [UNTRACKED],
1236 "print some statistics about AST and HIR"),
1237 mir_stats: bool = (false, parse_bool, [UNTRACKED],
1238 "print some statistics about MIR"),
1239 always_encode_mir: bool = (false, parse_bool, [TRACKED],
1240 "encode MIR of all functions into the crate metadata"),
1241 miri: bool = (false, parse_bool, [TRACKED],
1242 "check the miri const evaluator against the old ctfe"),
1243 osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
1244 "pass `-install_name @rpath/...` to the macOS linker"),
1245 sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
1247 linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
1249 fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
1250 "set the optimization fuel quota for a crate"),
1251 print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
1252 "make Rustc print the total optimization fuel used by a crate"),
1253 remap_path_prefix_from: Vec<PathBuf> = (vec![], parse_pathbuf_push, [TRACKED],
1254 "add a source pattern to the file path remapping config"),
1255 remap_path_prefix_to: Vec<PathBuf> = (vec![], parse_pathbuf_push, [TRACKED],
1256 "add a mapping target to the file path remapping config"),
1257 force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
1258 "force all crates to be `rustc_private` unstable"),
1259 pre_link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1260 "a single extra argument to prepend the linker invocation (can be used several times)"),
1261 pre_link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1262 "extra arguments to prepend to the linker invocation (space separated)"),
1263 profile: bool = (false, parse_bool, [TRACKED],
1264 "insert profiling code"),
1265 relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
1266 "choose which RELRO level to use"),
1267 nll: bool = (false, parse_bool, [UNTRACKED],
1268 "run the non-lexical lifetimes MIR pass"),
1269 nll_dump_cause: bool = (false, parse_bool, [UNTRACKED],
1270 "dump cause information when reporting errors from NLL"),
1271 trans_time_graph: bool = (false, parse_bool, [UNTRACKED],
1272 "generate a graphical HTML report of time spent in trans and LLVM"),
1273 thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
1274 "enable ThinLTO when possible"),
1275 inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
1276 "control whether #[inline] functions are in all cgus"),
1277 tls_model: Option<String> = (None, parse_opt_string, [TRACKED],
1278 "choose the TLS model to use (rustc --print tls-models for details)"),
1279 saturating_float_casts: bool = (false, parse_bool, [TRACKED],
1280 "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
1281 the max/min integer respectively, and NaN is mapped to 0"),
1282 lower_128bit_ops: Option<bool> = (None, parse_opt_bool, [TRACKED],
1283 "rewrite operators on i128 and u128 into lang item calls (typically provided \
1284 by compiler-builtins) so translation doesn't need to support them,
1285 overriding the default for the current target"),
1286 human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
1287 "generate human-readable, predictable names for codegen units"),
1288 dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
1289 "in dep-info output, omit targets for tracking dependencies of the dep-info files \
1291 approximate_suggestions: bool = (false, parse_bool, [UNTRACKED],
1292 "include machine-applicability of suggestions in JSON output"),
1293 unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
1294 "Present the input source, unstable (and less-pretty) variants;
1295 valid types are any of the types for `--pretty`, as well as:
1296 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
1297 `everybody_loops` (all function bodies replaced with `loop {}`),
1298 `hir` (the HIR), `hir,identified`, or
1299 `hir,typed` (HIR with types for each node)."),
1302 pub fn default_lib_output() -> CrateType {
1306 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
1307 let end = &sess.target.target.target_endian;
1308 let arch = &sess.target.target.arch;
1309 let wordsz = &sess.target.target.target_pointer_width;
1310 let os = &sess.target.target.target_os;
1311 let env = &sess.target.target.target_env;
1312 let vendor = &sess.target.target.target_vendor;
1313 let min_atomic_width = sess.target.target.min_atomic_width();
1314 let max_atomic_width = sess.target.target.max_atomic_width();
1316 let mut ret = HashSet::new();
1318 ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
1319 if let Some(ref fam) = sess.target.target.options.target_family {
1320 ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam))));
1321 if fam == "windows" || fam == "unix" {
1322 ret.insert((Symbol::intern(fam), None));
1325 ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
1326 ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
1327 ret.insert((Symbol::intern("target_pointer_width"), Some(Symbol::intern(wordsz))));
1328 ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
1329 ret.insert((Symbol::intern("target_vendor"), Some(Symbol::intern(vendor))));
1330 if sess.target.target.options.has_elf_tls {
1331 ret.insert((Symbol::intern("target_thread_local"), None));
1333 for &i in &[8, 16, 32, 64, 128] {
1334 if i >= min_atomic_width && i <= max_atomic_width {
1335 let s = i.to_string();
1336 ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern(&s))));
1338 ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern("ptr"))));
1342 if sess.opts.debug_assertions {
1343 ret.insert((Symbol::intern("debug_assertions"), None));
1345 if sess.opts.crate_types.contains(&CrateTypeProcMacro) {
1346 ret.insert((Symbol::intern("proc_macro"), None));
1351 pub fn build_configuration(sess: &Session,
1352 mut user_cfg: ast::CrateConfig)
1353 -> ast::CrateConfig {
1354 // Combine the configuration requested by the session (command line) with
1355 // some default and generated configuration items
1356 let default_cfg = default_configuration(sess);
1357 // If the user wants a test runner, then add the test cfg
1359 user_cfg.insert((Symbol::intern("test"), None));
1361 user_cfg.extend(default_cfg.iter().cloned());
1365 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
1366 let target = match Target::search(&opts.target_triple) {
1369 sp.struct_fatal(&format!("Error loading target specification: {}", e))
1370 .help("Use `--print target-list` for a list of built-in targets")
1376 let (isize_ty, usize_ty) = match &target.target_pointer_width[..] {
1377 "16" => (ast::IntTy::I16, ast::UintTy::U16),
1378 "32" => (ast::IntTy::I32, ast::UintTy::U32),
1379 "64" => (ast::IntTy::I64, ast::UintTy::U64),
1380 w => sp.fatal(&format!("target specification was invalid: \
1381 unrecognized target-pointer-width {}", w)).raise(),
1391 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1392 pub enum OptionStability {
1398 pub struct RustcOptGroup {
1399 pub apply: Box<Fn(&mut getopts::Options) -> &mut getopts::Options>,
1400 pub name: &'static str,
1401 pub stability: OptionStability,
1404 impl RustcOptGroup {
1405 pub fn is_stable(&self) -> bool {
1406 self.stability == OptionStability::Stable
1409 pub fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
1410 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1415 stability: OptionStability::Stable,
1419 pub fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
1420 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1425 stability: OptionStability::Unstable,
1430 // The `opt` local module holds wrappers around the `getopts` API that
1431 // adds extra rustc-specific metadata to each option; such metadata
1432 // is exposed by . The public
1433 // functions below ending with `_u` are the functions that return
1434 // *unstable* options, i.e. options that are only enabled when the
1435 // user also passes the `-Z unstable-options` debugging flag.
1437 // The `fn opt_u` etc below are written so that we can use them
1438 // in the future; do not warn about them not being used right now.
1439 #![allow(dead_code)]
1442 use super::RustcOptGroup;
1444 pub type R = RustcOptGroup;
1445 pub type S = &'static str;
1447 fn stable<F>(name: S, f: F) -> R
1448 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
1450 RustcOptGroup::stable(name, f)
1453 fn unstable<F>(name: S, f: F) -> R
1454 where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
1456 RustcOptGroup::unstable(name, f)
1459 fn longer(a: S, b: S) -> S {
1460 if a.len() > b.len() {
1467 pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
1468 stable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1470 pub fn multi_s(a: S, b: S, c: S, d: S) -> R {
1471 stable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1473 pub fn flag_s(a: S, b: S, c: S) -> R {
1474 stable(longer(a, b), move |opts| opts.optflag(a, b, c))
1476 pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R {
1477 stable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1479 pub fn flagmulti_s(a: S, b: S, c: S) -> R {
1480 stable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1483 pub fn opt(a: S, b: S, c: S, d: S) -> R {
1484 unstable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1486 pub fn multi(a: S, b: S, c: S, d: S) -> R {
1487 unstable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1489 pub fn flag(a: S, b: S, c: S) -> R {
1490 unstable(longer(a, b), move |opts| opts.optflag(a, b, c))
1492 pub fn flagopt(a: S, b: S, c: S, d: S) -> R {
1493 unstable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1495 pub fn flagmulti(a: S, b: S, c: S) -> R {
1496 unstable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1500 /// Returns the "short" subset of the rustc command line options,
1501 /// including metadata for each option, such as whether the option is
1502 /// part of the stable long-term interface for rustc.
1503 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
1505 opt::flag_s("h", "help", "Display this message"),
1506 opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
1507 opt::multi_s("L", "", "Add a directory to the library search path. The
1508 optional KIND can be one of dependency, crate, native,
1509 framework or all (the default).", "[KIND=]PATH"),
1510 opt::multi_s("l", "", "Link the generated crate(s) to the specified native
1511 library NAME. The optional KIND can be one of
1512 static, dylib, or framework. If omitted, dylib is
1513 assumed.", "[KIND=]NAME"),
1514 opt::multi_s("", "crate-type", "Comma separated list of types of crates
1515 for the compiler to emit",
1516 "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]"),
1517 opt::opt_s("", "crate-name", "Specify the name of the crate being built",
1519 opt::multi_s("", "emit", "Comma separated list of types of output for \
1520 the compiler to emit",
1521 "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]"),
1522 opt::multi_s("", "print", "Comma separated list of compiler information to \
1524 "[crate-name|file-names|sysroot|cfg|target-list|\
1525 target-cpus|target-features|relocation-models|\
1526 code-models|tls-models|target-spec-json|native-static-libs]"),
1527 opt::flagmulti_s("g", "", "Equivalent to -C debuginfo=2"),
1528 opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
1529 opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
1530 opt::opt_s("", "out-dir", "Write output to compiler-chosen filename \
1532 opt::opt_s("", "explain", "Provide a detailed explanation of an error \
1534 opt::flag_s("", "test", "Build a test harness"),
1535 opt::opt_s("", "target", "Target triple for which the code is compiled", "TARGET"),
1536 opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
1537 opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
1538 opt::multi_s("D", "deny", "Set lint denied", "OPT"),
1539 opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
1540 opt::multi_s("", "cap-lints", "Set the most restrictive lint level. \
1541 More restrictive lints are capped at this \
1543 opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
1544 opt::flag_s("V", "version", "Print version info and exit"),
1545 opt::flag_s("v", "verbose", "Use verbose output"),
1549 /// Returns all rustc command line options, including metadata for
1550 /// each option, such as whether the option is part of the stable
1551 /// long-term interface for rustc.
1552 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
1553 let mut opts = rustc_short_optgroups();
1555 opt::multi_s("", "extern", "Specify where an external rust library is located",
1557 opt::opt_s("", "sysroot", "Override the system root", "PATH"),
1558 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
1559 opt::opt_s("", "error-format",
1560 "How errors and other messages are produced",
1561 "human|json|short"),
1562 opt::opt_s("", "color", "Configure coloring of output:
1563 auto = colorize, if output goes to a tty (default);
1564 always = always colorize output;
1565 never = never colorize output", "auto|always|never"),
1567 opt::opt("", "pretty",
1568 "Pretty-print the input instead of compiling;
1569 valid types are: `normal` (un-annotated source),
1570 `expanded` (crates expanded), or
1571 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
1577 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
1578 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
1579 cfgspecs.into_iter().map(|s| {
1580 let sess = parse::ParseSess::new(FilePathMapping::empty());
1582 parse::new_parser_from_source_str(&sess, FileName::CfgSpec, s.to_string());
1584 let meta_item = panictry!(parser.parse_meta_item());
1586 if parser.token != token::Eof {
1587 early_error(ErrorOutputType::default(), &format!("invalid --cfg argument: {}", s))
1588 } else if meta_item.is_meta_item_list() {
1590 format!("invalid predicate in --cfg command line argument: `{}`", meta_item.name());
1591 early_error(ErrorOutputType::default(), &msg)
1594 (meta_item.name(), meta_item.value_str())
1595 }).collect::<ast::CrateConfig>()
1598 pub fn build_session_options_and_crate_config(matches: &getopts::Matches)
1599 -> (Options, ast::CrateConfig) {
1600 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
1601 Some("auto") => ColorConfig::Auto,
1602 Some("always") => ColorConfig::Always,
1603 Some("never") => ColorConfig::Never,
1605 None => ColorConfig::Auto,
1608 early_error(ErrorOutputType::default(), &format!("argument for --color must be auto, \
1609 always or never (instead was `{}`)",
1614 // We need the opts_present check because the driver will send us Matches
1615 // with only stable options if no unstable options are used. Since error-format
1616 // is unstable, it will not be present. We have to use opts_present not
1617 // opt_present because the latter will panic.
1618 let error_format = if matches.opts_present(&["error-format".to_owned()]) {
1619 match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
1620 Some("human") => ErrorOutputType::HumanReadable(color),
1621 Some("json") => ErrorOutputType::Json(false),
1622 Some("pretty-json") => ErrorOutputType::Json(true),
1624 if nightly_options::is_unstable_enabled(matches) {
1625 ErrorOutputType::Short(color)
1627 early_error(ErrorOutputType::default(),
1628 &format!("the `-Z unstable-options` flag must also be passed to \
1629 enable the short error message option"));
1632 None => ErrorOutputType::HumanReadable(color),
1635 early_error(ErrorOutputType::HumanReadable(color),
1636 &format!("argument for --error-format must be `human`, `json` or \
1637 `short` (instead was `{}`)",
1642 ErrorOutputType::HumanReadable(color)
1645 let unparsed_crate_types = matches.opt_strs("crate-type");
1646 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
1647 .unwrap_or_else(|e| early_error(error_format, &e[..]));
1649 let mut lint_opts = vec![];
1650 let mut describe_lints = false;
1652 for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
1653 for lint_name in matches.opt_strs(level.as_str()) {
1654 if lint_name == "help" {
1655 describe_lints = true;
1657 lint_opts.push((lint_name.replace("-", "_"), level));
1662 let lint_cap = matches.opt_str("cap-lints").map(|cap| {
1663 lint::Level::from_str(&cap).unwrap_or_else(|| {
1664 early_error(error_format, &format!("unknown lint level: `{}`", cap))
1668 let mut debugging_opts = build_debugging_options(matches, error_format);
1670 if !debugging_opts.unstable_options && error_format == ErrorOutputType::Json(true) {
1671 early_error(ErrorOutputType::Json(false), "--error-format=pretty-json is unstable");
1674 let mut output_types = BTreeMap::new();
1675 if !debugging_opts.parse_only {
1676 for list in matches.opt_strs("emit") {
1677 for output_type in list.split(',') {
1678 let mut parts = output_type.splitn(2, '=');
1679 let shorthand = parts.next().unwrap();
1680 let output_type = match OutputType::from_shorthand(shorthand) {
1681 Some(output_type) => output_type,
1682 None => early_error(error_format, &format!(
1683 "unknown emission type: `{}` - expected one of: {}",
1684 shorthand, OutputType::shorthands_display(),
1687 let path = parts.next().map(PathBuf::from);
1688 output_types.insert(output_type, path);
1692 if output_types.is_empty() {
1693 output_types.insert(OutputType::Exe, None);
1696 let remap_path_prefix_sources = debugging_opts.remap_path_prefix_from.len();
1697 let remap_path_prefix_targets = debugging_opts.remap_path_prefix_from.len();
1699 if remap_path_prefix_targets < remap_path_prefix_sources {
1700 for source in &debugging_opts.remap_path_prefix_from[remap_path_prefix_targets..] {
1701 early_error(error_format,
1702 &format!("option `-Zremap-path-prefix-from='{}'` does not have \
1703 a corresponding `-Zremap-path-prefix-to`", source.display()))
1705 } else if remap_path_prefix_targets > remap_path_prefix_sources {
1706 for target in &debugging_opts.remap_path_prefix_to[remap_path_prefix_sources..] {
1707 early_error(error_format,
1708 &format!("option `-Zremap-path-prefix-to='{}'` does not have \
1709 a corresponding `-Zremap-path-prefix-from`", target.display()))
1713 let mut cg = build_codegen_options(matches, error_format);
1714 let mut codegen_units = cg.codegen_units;
1715 let mut disable_thinlto = false;
1717 // Issue #30063: if user requests llvm-related output to one
1718 // particular path, disable codegen-units.
1719 let incompatible: Vec<_> = output_types.iter()
1720 .map(|ot_path| ot_path.0)
1722 !ot.is_compatible_with_codegen_units_and_single_output_file()
1724 .map(|ot| ot.shorthand())
1726 if !incompatible.is_empty() {
1727 match codegen_units {
1728 Some(n) if n > 1 => {
1729 if matches.opt_present("o") {
1730 for ot in &incompatible {
1731 early_warn(error_format, &format!("--emit={} with -o incompatible with \
1732 -C codegen-units=N for N > 1",
1735 early_warn(error_format, "resetting to default -C codegen-units=1");
1736 codegen_units = Some(1);
1737 disable_thinlto = true;
1741 codegen_units = Some(1);
1742 disable_thinlto = true;
1747 if debugging_opts.query_threads == Some(0) {
1748 early_error(error_format, "Value for query threads must be a positive nonzero integer");
1751 if codegen_units == Some(0) {
1752 early_error(error_format, "Value for codegen units must be a positive nonzero integer");
1755 let incremental = match (&debugging_opts.incremental, &cg.incremental) {
1756 (&Some(ref path1), &Some(ref path2)) => {
1758 early_error(error_format,
1759 &format!("conflicting paths for `-Z incremental` and \
1760 `-C incremental` specified: {} versus {}",
1767 (&Some(ref path), &None) => Some(path),
1768 (&None, &Some(ref path)) => Some(path),
1769 (&None, &None) => None,
1770 }.map(|m| PathBuf::from(m));
1772 if cg.lto != Lto::No && incremental.is_some() {
1773 early_error(error_format, "can't perform LTO when compiling incrementally");
1776 let mut prints = Vec::<PrintRequest>::new();
1777 if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
1778 prints.push(PrintRequest::TargetCPUs);
1779 cg.target_cpu = None;
1781 if cg.target_feature == "help" {
1782 prints.push(PrintRequest::TargetFeatures);
1783 cg.target_feature = "".to_string();
1785 if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
1786 prints.push(PrintRequest::RelocationModels);
1787 cg.relocation_model = None;
1789 if cg.code_model.as_ref().map_or(false, |s| s == "help") {
1790 prints.push(PrintRequest::CodeModels);
1791 cg.code_model = None;
1793 if debugging_opts.tls_model.as_ref().map_or(false, |s| s == "help") {
1794 prints.push(PrintRequest::TlsModels);
1795 debugging_opts.tls_model = None;
1800 let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
1801 let target = matches.opt_str("target").unwrap_or(
1802 host_triple().to_string());
1804 if matches.opt_present("O") {
1805 if cg.opt_level.is_some() {
1806 early_error(error_format, "-O and -C opt-level both provided");
1810 match (cg.opt_level.as_ref().map(String::as_ref),
1811 nightly_options::is_nightly_build()) {
1812 (None, _) => OptLevel::No,
1813 (Some("0"), _) => OptLevel::No,
1814 (Some("1"), _) => OptLevel::Less,
1815 (Some("2"), _) => OptLevel::Default,
1816 (Some("3"), _) => OptLevel::Aggressive,
1817 (Some("s"), true) => OptLevel::Size,
1818 (Some("z"), true) => OptLevel::SizeMin,
1819 (Some("s"), false) | (Some("z"), false) => {
1820 early_error(error_format, &format!("the optimizations s or z are only \
1821 accepted on the nightly compiler"));
1824 early_error(error_format, &format!("optimization level needs to be \
1825 between 0-3 (instead was `{}`)",
1831 let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
1832 let debuginfo = if matches.opt_present("g") {
1833 if cg.debuginfo.is_some() {
1834 early_error(error_format, "-g and -C debuginfo both provided");
1838 match cg.debuginfo {
1839 None | Some(0) => NoDebugInfo,
1840 Some(1) => LimitedDebugInfo,
1841 Some(2) => FullDebugInfo,
1843 early_error(error_format, &format!("debug info level needs to be between \
1844 0-2 (instead was `{}`)",
1850 let mut search_paths = SearchPaths::new();
1851 for s in &matches.opt_strs("L") {
1852 search_paths.add_path(&s[..], error_format);
1855 let libs = matches.opt_strs("l").into_iter().map(|s| {
1856 // Parse string of the form "[KIND=]lib[:new_name]",
1857 // where KIND is one of "dylib", "framework", "static".
1858 let mut parts = s.splitn(2, '=');
1859 let kind = parts.next().unwrap();
1860 let (name, kind) = match (parts.next(), kind) {
1861 (None, name) => (name, None),
1862 (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
1863 (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
1864 (Some(name), "static") => (name, Some(cstore::NativeStatic)),
1865 (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
1867 early_error(error_format, &format!("unknown library kind `{}`, expected \
1868 one of dylib, framework, or static",
1872 if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
1873 early_error(error_format, &format!("the library kind 'static-nobundle' is only \
1874 accepted on the nightly compiler"));
1876 let mut name_parts = name.splitn(2, ':');
1877 let name = name_parts.next().unwrap();
1878 let new_name = name_parts.next();
1879 (name.to_string(), new_name.map(|n| n.to_string()), kind)
1882 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
1883 let test = matches.opt_present("test");
1885 prints.extend(matches.opt_strs("print").into_iter().map(|s| {
1887 "crate-name" => PrintRequest::CrateName,
1888 "file-names" => PrintRequest::FileNames,
1889 "sysroot" => PrintRequest::Sysroot,
1890 "cfg" => PrintRequest::Cfg,
1891 "target-list" => PrintRequest::TargetList,
1892 "target-cpus" => PrintRequest::TargetCPUs,
1893 "target-features" => PrintRequest::TargetFeatures,
1894 "relocation-models" => PrintRequest::RelocationModels,
1895 "code-models" => PrintRequest::CodeModels,
1896 "tls-models" => PrintRequest::TlsModels,
1897 "native-static-libs" => PrintRequest::NativeStaticLibs,
1898 "target-spec-json" => {
1899 if nightly_options::is_unstable_enabled(matches) {
1900 PrintRequest::TargetSpec
1902 early_error(error_format,
1903 &format!("the `-Z unstable-options` flag must also be passed to \
1904 enable the target-spec-json print option"));
1908 early_error(error_format, &format!("unknown print request `{}`", req))
1913 let borrowck_mode = match debugging_opts.borrowck.as_ref().map(|s| &s[..]) {
1914 None | Some("ast") => BorrowckMode::Ast,
1915 Some("mir") => BorrowckMode::Mir,
1916 Some("compare") => BorrowckMode::Compare,
1918 early_error(error_format, &format!("unknown borrowck mode `{}`", m))
1922 if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
1923 early_warn(error_format, "-C remark will not show source locations without \
1927 let mut externs = BTreeMap::new();
1928 for arg in &matches.opt_strs("extern") {
1929 let mut parts = arg.splitn(2, '=');
1930 let name = match parts.next() {
1932 None => early_error(error_format, "--extern value must not be empty"),
1934 let location = match parts.next() {
1936 None => early_error(error_format, "--extern value must be of the format `foo=bar`"),
1939 externs.entry(name.to_string())
1940 .or_insert_with(BTreeSet::new)
1941 .insert(location.to_string());
1944 let crate_name = matches.opt_str("crate-name");
1948 optimize: opt_level,
1953 output_types: OutputTypes(output_types),
1955 maybe_sysroot: sysroot_opt,
1956 target_triple: target,
1964 externs: Externs(externs),
1968 unstable_features: UnstableFeatures::from_environment(),
1970 actually_rustdoc: false,
1971 cli_forced_codegen_units: codegen_units,
1972 cli_forced_thinlto_off: disable_thinlto,
1977 pub fn parse_crate_types_from_list(list_list: Vec<String>)
1978 -> Result<Vec<CrateType>, String> {
1979 let mut crate_types: Vec<CrateType> = Vec::new();
1980 for unparsed_crate_type in &list_list {
1981 for part in unparsed_crate_type.split(',') {
1982 let new_part = match part {
1983 "lib" => default_lib_output(),
1984 "rlib" => CrateTypeRlib,
1985 "staticlib" => CrateTypeStaticlib,
1986 "dylib" => CrateTypeDylib,
1987 "cdylib" => CrateTypeCdylib,
1988 "bin" => CrateTypeExecutable,
1989 "proc-macro" => CrateTypeProcMacro,
1991 return Err(format!("unknown crate type: `{}`",
1995 if !crate_types.contains(&new_part) {
1996 crate_types.push(new_part)
2004 pub mod nightly_options {
2006 use syntax::feature_gate::UnstableFeatures;
2007 use super::{ErrorOutputType, OptionStability, RustcOptGroup};
2008 use session::early_error;
2010 pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
2011 is_nightly_build() && matches.opt_strs("Z").iter().any(|x| *x == "unstable-options")
2014 pub fn is_nightly_build() -> bool {
2015 UnstableFeatures::from_environment().is_nightly_build()
2018 pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
2019 let has_z_unstable_option = matches.opt_strs("Z").iter().any(|x| *x == "unstable-options");
2020 let really_allows_unstable_options = UnstableFeatures::from_environment()
2021 .is_nightly_build();
2023 for opt in flags.iter() {
2024 if opt.stability == OptionStability::Stable {
2027 if !matches.opt_present(opt.name) {
2030 if opt.name != "Z" && !has_z_unstable_option {
2031 early_error(ErrorOutputType::default(),
2032 &format!("the `-Z unstable-options` flag must also be passed to enable \
2036 if really_allows_unstable_options {
2039 match opt.stability {
2040 OptionStability::Unstable => {
2041 let msg = format!("the option `{}` is only accepted on the \
2042 nightly compiler", opt.name);
2043 early_error(ErrorOutputType::default(), &msg);
2045 OptionStability::Stable => {}
2051 impl fmt::Display for CrateType {
2052 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2054 CrateTypeExecutable => "bin".fmt(f),
2055 CrateTypeDylib => "dylib".fmt(f),
2056 CrateTypeRlib => "rlib".fmt(f),
2057 CrateTypeStaticlib => "staticlib".fmt(f),
2058 CrateTypeCdylib => "cdylib".fmt(f),
2059 CrateTypeProcMacro => "proc-macro".fmt(f),
2064 /// Commandline arguments passed to the compiler have to be incorporated with
2065 /// the dependency tracking system for incremental compilation. This module
2066 /// provides some utilities to make this more convenient.
2068 /// The values of all commandline arguments that are relevant for dependency
2069 /// tracking are hashed into a single value that determines whether the
2070 /// incremental compilation cache can be re-used or not. This hashing is done
2071 /// via the DepTrackingHash trait defined below, since the standard Hash
2072 /// implementation might not be suitable (e.g. arguments are stored in a Vec,
2073 /// the hash of which is order dependent, but we might not want the order of
2074 /// arguments to make a difference for the hash).
2076 /// However, since the value provided by Hash::hash often *is* suitable,
2077 /// especially for primitive types, there is the
2078 /// impl_dep_tracking_hash_via_hash!() macro that allows to simply reuse the
2079 /// Hash implementation for DepTrackingHash. It's important though that
2080 /// we have an opt-in scheme here, so one is hopefully forced to think about
2081 /// how the hash should be calculated when adding a new commandline argument.
2085 use session::search_paths::{PathKind, SearchPaths};
2086 use std::collections::BTreeMap;
2087 use std::hash::Hash;
2088 use std::path::PathBuf;
2089 use std::collections::hash_map::DefaultHasher;
2090 use super::{Passes, CrateType, OptLevel, DebugInfoLevel, Lto,
2091 OutputTypes, Externs, ErrorOutputType, Sanitizer};
2092 use syntax::feature_gate::UnstableFeatures;
2093 use rustc_back::{PanicStrategy, RelroLevel};
2095 pub trait DepTrackingHash {
2096 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);
2099 macro_rules! impl_dep_tracking_hash_via_hash {
2101 impl DepTrackingHash for $t {
2102 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
2103 Hash::hash(self, hasher);
2109 macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
2111 impl DepTrackingHash for Vec<$t> {
2112 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2113 let mut elems: Vec<&$t> = self.iter().collect();
2115 Hash::hash(&elems.len(), hasher);
2116 for (index, elem) in elems.iter().enumerate() {
2117 Hash::hash(&index, hasher);
2118 DepTrackingHash::hash(*elem, hasher, error_format);
2125 impl_dep_tracking_hash_via_hash!(bool);
2126 impl_dep_tracking_hash_via_hash!(usize);
2127 impl_dep_tracking_hash_via_hash!(u64);
2128 impl_dep_tracking_hash_via_hash!(String);
2129 impl_dep_tracking_hash_via_hash!(PathBuf);
2130 impl_dep_tracking_hash_via_hash!(lint::Level);
2131 impl_dep_tracking_hash_via_hash!(Option<bool>);
2132 impl_dep_tracking_hash_via_hash!(Option<usize>);
2133 impl_dep_tracking_hash_via_hash!(Option<String>);
2134 impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
2135 impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
2136 impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
2137 impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
2138 impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
2139 impl_dep_tracking_hash_via_hash!(Option<cstore::NativeLibraryKind>);
2140 impl_dep_tracking_hash_via_hash!(CrateType);
2141 impl_dep_tracking_hash_via_hash!(PanicStrategy);
2142 impl_dep_tracking_hash_via_hash!(RelroLevel);
2143 impl_dep_tracking_hash_via_hash!(Passes);
2144 impl_dep_tracking_hash_via_hash!(OptLevel);
2145 impl_dep_tracking_hash_via_hash!(Lto);
2146 impl_dep_tracking_hash_via_hash!(DebugInfoLevel);
2147 impl_dep_tracking_hash_via_hash!(UnstableFeatures);
2148 impl_dep_tracking_hash_via_hash!(Externs);
2149 impl_dep_tracking_hash_via_hash!(OutputTypes);
2150 impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
2151 impl_dep_tracking_hash_via_hash!(Sanitizer);
2152 impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
2154 impl_dep_tracking_hash_for_sortable_vec_of!(String);
2155 impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
2156 impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
2157 impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
2158 impl_dep_tracking_hash_for_sortable_vec_of!((String, Option<String>,
2159 Option<cstore::NativeLibraryKind>));
2160 impl_dep_tracking_hash_for_sortable_vec_of!((String, u64));
2161 impl DepTrackingHash for SearchPaths {
2162 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
2163 let mut elems: Vec<_> = self
2164 .iter(PathKind::All)
2167 Hash::hash(&elems, hasher);
2171 impl<T1, T2> DepTrackingHash for (T1, T2)
2172 where T1: DepTrackingHash,
2175 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2176 Hash::hash(&0, hasher);
2177 DepTrackingHash::hash(&self.0, hasher, error_format);
2178 Hash::hash(&1, hasher);
2179 DepTrackingHash::hash(&self.1, hasher, error_format);
2183 impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
2184 where T1: DepTrackingHash,
2185 T2: DepTrackingHash,
2188 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2189 Hash::hash(&0, hasher);
2190 DepTrackingHash::hash(&self.0, hasher, error_format);
2191 Hash::hash(&1, hasher);
2192 DepTrackingHash::hash(&self.1, hasher, error_format);
2193 Hash::hash(&2, hasher);
2194 DepTrackingHash::hash(&self.2, hasher, error_format);
2198 // This is a stable hash because BTreeMap is a sorted container
2199 pub fn stable_hash(sub_hashes: BTreeMap<&'static str, &DepTrackingHash>,
2200 hasher: &mut DefaultHasher,
2201 error_format: ErrorOutputType) {
2202 for (key, sub_hash) in sub_hashes {
2203 // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
2204 // the keys, as they are just plain strings
2205 Hash::hash(&key.len(), hasher);
2206 Hash::hash(key, hasher);
2207 sub_hash.hash(hasher, error_format);
2218 use session::config::{build_configuration, build_session_options_and_crate_config};
2219 use session::config::Lto;
2220 use session::build_session;
2221 use std::collections::{BTreeMap, BTreeSet};
2222 use std::iter::FromIterator;
2223 use std::path::PathBuf;
2224 use super::{OutputType, OutputTypes, Externs};
2225 use rustc_back::{PanicStrategy, RelroLevel};
2226 use syntax::symbol::Symbol;
2228 fn optgroups() -> getopts::Options {
2229 let mut opts = getopts::Options::new();
2230 for group in super::rustc_optgroups() {
2231 (group.apply)(&mut opts);
2236 fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
2237 BTreeMap::from_iter(entries.into_iter())
2240 fn mk_set<V: Ord>(entries: Vec<V>) -> BTreeSet<V> {
2241 BTreeSet::from_iter(entries.into_iter())
2244 // When the user supplies --test we should implicitly supply --cfg test
2246 fn test_switch_implies_cfg_test() {
2248 &match optgroups().parse(&["--test".to_string()]) {
2250 Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
2252 let registry = errors::registry::Registry::new(&[]);
2253 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2254 let sess = build_session(sessopts, None, registry);
2255 let cfg = build_configuration(&sess, cfg);
2256 assert!(cfg.contains(&(Symbol::intern("test"), None)));
2259 // When the user supplies --test and --cfg test, don't implicitly add
2260 // another --cfg test
2262 fn test_switch_implies_cfg_test_unless_cfg_test() {
2264 &match optgroups().parse(&["--test".to_string(), "--cfg=test".to_string()]) {
2267 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
2270 let registry = errors::registry::Registry::new(&[]);
2271 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2272 let sess = build_session(sessopts, None, registry);
2273 let cfg = build_configuration(&sess, cfg);
2274 let mut test_items = cfg.iter().filter(|&&(name, _)| name == "test");
2275 assert!(test_items.next().is_some());
2276 assert!(test_items.next().is_none());
2280 fn test_can_print_warnings() {
2282 let matches = optgroups().parse(&[
2283 "-Awarnings".to_string()
2285 let registry = errors::registry::Registry::new(&[]);
2286 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2287 let sess = build_session(sessopts, None, registry);
2288 assert!(!sess.diagnostic().flags.can_emit_warnings);
2292 let matches = optgroups().parse(&[
2293 "-Awarnings".to_string(),
2294 "-Dwarnings".to_string()
2296 let registry = errors::registry::Registry::new(&[]);
2297 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2298 let sess = build_session(sessopts, None, registry);
2299 assert!(sess.diagnostic().flags.can_emit_warnings);
2303 let matches = optgroups().parse(&[
2304 "-Adead_code".to_string()
2306 let registry = errors::registry::Registry::new(&[]);
2307 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2308 let sess = build_session(sessopts, None, registry);
2309 assert!(sess.diagnostic().flags.can_emit_warnings);
2314 fn test_output_types_tracking_hash_different_paths() {
2315 let mut v1 = super::basic_options();
2316 let mut v2 = super::basic_options();
2317 let mut v3 = super::basic_options();
2319 v1.output_types = OutputTypes::new(&[(OutputType::Exe,
2320 Some(PathBuf::from("./some/thing")))]);
2321 v2.output_types = OutputTypes::new(&[(OutputType::Exe,
2322 Some(PathBuf::from("/some/thing")))]);
2323 v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
2325 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2326 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2327 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2330 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2331 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2332 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2336 fn test_output_types_tracking_hash_different_construction_order() {
2337 let mut v1 = super::basic_options();
2338 let mut v2 = super::basic_options();
2340 v1.output_types = OutputTypes::new(&[
2341 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2342 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2345 v2.output_types = OutputTypes::new(&[
2346 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2347 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2350 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2353 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2357 fn test_externs_tracking_hash_different_values() {
2358 let mut v1 = super::basic_options();
2359 let mut v2 = super::basic_options();
2360 let mut v3 = super::basic_options();
2362 v1.externs = Externs::new(mk_map(vec![
2363 (String::from("a"), mk_set(vec![String::from("b"),
2364 String::from("c")])),
2365 (String::from("d"), mk_set(vec![String::from("e"),
2366 String::from("f")])),
2369 v2.externs = Externs::new(mk_map(vec![
2370 (String::from("a"), mk_set(vec![String::from("b"),
2371 String::from("c")])),
2372 (String::from("X"), mk_set(vec![String::from("e"),
2373 String::from("f")])),
2376 v3.externs = Externs::new(mk_map(vec![
2377 (String::from("a"), mk_set(vec![String::from("b"),
2378 String::from("c")])),
2379 (String::from("d"), mk_set(vec![String::from("X"),
2380 String::from("f")])),
2383 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2384 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2385 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2388 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2389 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2390 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2394 fn test_externs_tracking_hash_different_construction_order() {
2395 let mut v1 = super::basic_options();
2396 let mut v2 = super::basic_options();
2397 let mut v3 = super::basic_options();
2399 v1.externs = Externs::new(mk_map(vec![
2400 (String::from("a"), mk_set(vec![String::from("b"),
2401 String::from("c")])),
2402 (String::from("d"), mk_set(vec![String::from("e"),
2403 String::from("f")])),
2406 v2.externs = Externs::new(mk_map(vec![
2407 (String::from("d"), mk_set(vec![String::from("e"),
2408 String::from("f")])),
2409 (String::from("a"), mk_set(vec![String::from("b"),
2410 String::from("c")])),
2413 v3.externs = Externs::new(mk_map(vec![
2414 (String::from("a"), mk_set(vec![String::from("b"),
2415 String::from("c")])),
2416 (String::from("d"), mk_set(vec![String::from("f"),
2417 String::from("e")])),
2420 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2421 assert_eq!(v1.dep_tracking_hash(), v3.dep_tracking_hash());
2422 assert_eq!(v2.dep_tracking_hash(), v3.dep_tracking_hash());
2425 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2426 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2427 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2431 fn test_lints_tracking_hash_different_values() {
2432 let mut v1 = super::basic_options();
2433 let mut v2 = super::basic_options();
2434 let mut v3 = super::basic_options();
2436 v1.lint_opts = vec![(String::from("a"), lint::Allow),
2437 (String::from("b"), lint::Warn),
2438 (String::from("c"), lint::Deny),
2439 (String::from("d"), lint::Forbid)];
2441 v2.lint_opts = vec![(String::from("a"), lint::Allow),
2442 (String::from("b"), lint::Warn),
2443 (String::from("X"), lint::Deny),
2444 (String::from("d"), lint::Forbid)];
2446 v3.lint_opts = vec![(String::from("a"), lint::Allow),
2447 (String::from("b"), lint::Warn),
2448 (String::from("c"), lint::Forbid),
2449 (String::from("d"), lint::Deny)];
2451 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2452 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2453 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2456 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2457 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2458 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2462 fn test_lints_tracking_hash_different_construction_order() {
2463 let mut v1 = super::basic_options();
2464 let mut v2 = super::basic_options();
2466 v1.lint_opts = vec![(String::from("a"), lint::Allow),
2467 (String::from("b"), lint::Warn),
2468 (String::from("c"), lint::Deny),
2469 (String::from("d"), lint::Forbid)];
2471 v2.lint_opts = vec![(String::from("a"), lint::Allow),
2472 (String::from("c"), lint::Deny),
2473 (String::from("b"), lint::Warn),
2474 (String::from("d"), lint::Forbid)];
2476 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2479 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2480 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2484 fn test_search_paths_tracking_hash_different_values() {
2485 let mut v1 = super::basic_options();
2486 let mut v2 = super::basic_options();
2487 let mut v3 = super::basic_options();
2488 let mut v4 = super::basic_options();
2489 let mut v5 = super::basic_options();
2492 v1.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2493 v1.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2494 v1.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2495 v1.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2496 v1.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2499 v2.search_paths.add_path("native=XXX", super::ErrorOutputType::Json(false));
2500 v2.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2501 v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2502 v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2503 v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2506 v2.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2507 v2.search_paths.add_path("crate=XXX", super::ErrorOutputType::Json(false));
2508 v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2509 v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2510 v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2512 // Dependency changed
2513 v3.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2514 v3.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2515 v3.search_paths.add_path("dependency=XXX", super::ErrorOutputType::Json(false));
2516 v3.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2517 v3.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2519 // Framework changed
2520 v4.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2521 v4.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2522 v4.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2523 v4.search_paths.add_path("framework=XXX", super::ErrorOutputType::Json(false));
2524 v4.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2527 v5.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2528 v5.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2529 v5.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2530 v5.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2531 v5.search_paths.add_path("all=XXX", super::ErrorOutputType::Json(false));
2533 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2534 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2535 assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
2536 assert!(v1.dep_tracking_hash() != v5.dep_tracking_hash());
2539 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2540 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2541 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2542 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2543 assert_eq!(v5.dep_tracking_hash(), v5.clone().dep_tracking_hash());
2547 fn test_search_paths_tracking_hash_different_order() {
2548 let mut v1 = super::basic_options();
2549 let mut v2 = super::basic_options();
2550 let mut v3 = super::basic_options();
2551 let mut v4 = super::basic_options();
2554 v1.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2555 v1.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2556 v1.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2557 v1.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2558 v1.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2560 v2.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2561 v2.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2562 v2.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2563 v2.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2564 v2.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2566 v3.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2567 v3.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2568 v3.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2569 v3.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2570 v3.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2572 v4.search_paths.add_path("all=mno", super::ErrorOutputType::Json(false));
2573 v4.search_paths.add_path("native=abc", super::ErrorOutputType::Json(false));
2574 v4.search_paths.add_path("crate=def", super::ErrorOutputType::Json(false));
2575 v4.search_paths.add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2576 v4.search_paths.add_path("framework=jkl", super::ErrorOutputType::Json(false));
2578 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2579 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2580 assert!(v1.dep_tracking_hash() == v4.dep_tracking_hash());
2583 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2584 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2585 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2586 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2590 fn test_native_libs_tracking_hash_different_values() {
2591 let mut v1 = super::basic_options();
2592 let mut v2 = super::basic_options();
2593 let mut v3 = super::basic_options();
2594 let mut v4 = super::basic_options();
2597 v1.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2598 (String::from("b"), None, Some(cstore::NativeFramework)),
2599 (String::from("c"), None, Some(cstore::NativeUnknown))];
2602 v2.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2603 (String::from("X"), None, Some(cstore::NativeFramework)),
2604 (String::from("c"), None, Some(cstore::NativeUnknown))];
2607 v3.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2608 (String::from("b"), None, Some(cstore::NativeStatic)),
2609 (String::from("c"), None, Some(cstore::NativeUnknown))];
2612 v4.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2613 (String::from("b"), Some(String::from("X")), Some(cstore::NativeFramework)),
2614 (String::from("c"), None, Some(cstore::NativeUnknown))];
2616 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2617 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2618 assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
2621 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2622 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2623 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2624 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2628 fn test_native_libs_tracking_hash_different_order() {
2629 let mut v1 = super::basic_options();
2630 let mut v2 = super::basic_options();
2631 let mut v3 = super::basic_options();
2634 v1.libs = vec![(String::from("a"), None, Some(cstore::NativeStatic)),
2635 (String::from("b"), None, Some(cstore::NativeFramework)),
2636 (String::from("c"), None, Some(cstore::NativeUnknown))];
2638 v2.libs = vec![(String::from("b"), None, Some(cstore::NativeFramework)),
2639 (String::from("a"), None, Some(cstore::NativeStatic)),
2640 (String::from("c"), None, Some(cstore::NativeUnknown))];
2642 v3.libs = vec![(String::from("c"), None, Some(cstore::NativeUnknown)),
2643 (String::from("a"), None, Some(cstore::NativeStatic)),
2644 (String::from("b"), None, Some(cstore::NativeFramework))];
2646 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2647 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2648 assert!(v2.dep_tracking_hash() == v3.dep_tracking_hash());
2651 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2652 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2653 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2657 fn test_codegen_options_tracking_hash() {
2658 let reference = super::basic_options();
2659 let mut opts = super::basic_options();
2661 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2662 opts.cg.ar = Some(String::from("abc"));
2663 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2665 opts.cg.linker = Some(PathBuf::from("linker"));
2666 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2668 opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
2669 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2671 opts.cg.link_dead_code = true;
2672 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2674 opts.cg.rpath = true;
2675 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2677 opts.cg.extra_filename = String::from("extra-filename");
2678 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2680 opts.cg.codegen_units = Some(42);
2681 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2683 opts.cg.remark = super::SomePasses(vec![String::from("pass1"),
2684 String::from("pass2")]);
2685 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2687 opts.cg.save_temps = true;
2688 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2690 opts.cg.incremental = Some(String::from("abc"));
2691 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2694 // Make sure changing a [TRACKED] option changes the hash
2695 opts = reference.clone();
2696 opts.cg.lto = Lto::Fat;
2697 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2699 opts = reference.clone();
2700 opts.cg.target_cpu = Some(String::from("abc"));
2701 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2703 opts = reference.clone();
2704 opts.cg.target_feature = String::from("all the features, all of them");
2705 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2707 opts = reference.clone();
2708 opts.cg.passes = vec![String::from("1"), String::from("2")];
2709 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2711 opts = reference.clone();
2712 opts.cg.llvm_args = vec![String::from("1"), String::from("2")];
2713 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2715 opts = reference.clone();
2716 opts.cg.overflow_checks = Some(true);
2717 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2719 opts = reference.clone();
2720 opts.cg.no_prepopulate_passes = true;
2721 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2723 opts = reference.clone();
2724 opts.cg.no_vectorize_loops = true;
2725 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2727 opts = reference.clone();
2728 opts.cg.no_vectorize_slp = true;
2729 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2731 opts = reference.clone();
2732 opts.cg.soft_float = true;
2733 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2735 opts = reference.clone();
2736 opts.cg.prefer_dynamic = true;
2737 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2739 opts = reference.clone();
2740 opts.cg.no_integrated_as = true;
2741 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2743 opts = reference.clone();
2744 opts.cg.no_redzone = Some(true);
2745 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2747 opts = reference.clone();
2748 opts.cg.relocation_model = Some(String::from("relocation model"));
2749 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2751 opts = reference.clone();
2752 opts.cg.code_model = Some(String::from("code model"));
2753 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2755 opts = reference.clone();
2756 opts.debugging_opts.tls_model = Some(String::from("tls model"));
2757 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2759 opts = reference.clone();
2760 opts.cg.metadata = vec![String::from("A"), String::from("B")];
2761 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2763 opts = reference.clone();
2764 opts.cg.debuginfo = Some(0xdeadbeef);
2765 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2767 opts = reference.clone();
2768 opts.cg.debuginfo = Some(0xba5eba11);
2769 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2771 opts = reference.clone();
2772 opts.cg.debug_assertions = Some(true);
2773 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2775 opts = reference.clone();
2776 opts.cg.inline_threshold = Some(0xf007ba11);
2777 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2779 opts = reference.clone();
2780 opts.cg.panic = Some(PanicStrategy::Abort);
2781 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2785 fn test_debugging_options_tracking_hash() {
2786 let reference = super::basic_options();
2787 let mut opts = super::basic_options();
2789 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2790 opts.debugging_opts.verbose = true;
2791 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2792 opts.debugging_opts.time_passes = true;
2793 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2794 opts.debugging_opts.count_llvm_insns = true;
2795 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2796 opts.debugging_opts.time_llvm_passes = true;
2797 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2798 opts.debugging_opts.input_stats = true;
2799 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2800 opts.debugging_opts.trans_stats = true;
2801 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2802 opts.debugging_opts.borrowck_stats = true;
2803 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2804 opts.debugging_opts.meta_stats = true;
2805 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2806 opts.debugging_opts.print_link_args = true;
2807 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2808 opts.debugging_opts.print_llvm_passes = true;
2809 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2810 opts.debugging_opts.ast_json = true;
2811 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2812 opts.debugging_opts.ast_json_noexpand = true;
2813 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2814 opts.debugging_opts.ls = true;
2815 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2816 opts.debugging_opts.save_analysis = true;
2817 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2818 opts.debugging_opts.flowgraph_print_loans = true;
2819 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2820 opts.debugging_opts.flowgraph_print_moves = true;
2821 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2822 opts.debugging_opts.flowgraph_print_assigns = true;
2823 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2824 opts.debugging_opts.flowgraph_print_all = true;
2825 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2826 opts.debugging_opts.print_region_graph = true;
2827 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2828 opts.debugging_opts.parse_only = true;
2829 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2830 opts.debugging_opts.incremental = Some(String::from("abc"));
2831 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2832 opts.debugging_opts.dump_dep_graph = true;
2833 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2834 opts.debugging_opts.query_dep_graph = true;
2835 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2836 opts.debugging_opts.no_analysis = true;
2837 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2838 opts.debugging_opts.unstable_options = true;
2839 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2840 opts.debugging_opts.trace_macros = true;
2841 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2842 opts.debugging_opts.keep_hygiene_data = true;
2843 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2844 opts.debugging_opts.keep_ast = true;
2845 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2846 opts.debugging_opts.print_trans_items = Some(String::from("abc"));
2847 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2848 opts.debugging_opts.dump_mir = Some(String::from("abc"));
2849 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2850 opts.debugging_opts.dump_mir_dir = String::from("abc");
2851 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2852 opts.debugging_opts.dump_mir_graphviz = true;
2853 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2855 // Make sure changing a [TRACKED] option changes the hash
2856 opts = reference.clone();
2857 opts.debugging_opts.asm_comments = true;
2858 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2860 opts = reference.clone();
2861 opts.debugging_opts.no_verify = true;
2862 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2864 opts = reference.clone();
2865 opts.debugging_opts.no_landing_pads = true;
2866 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2868 opts = reference.clone();
2869 opts.debugging_opts.fewer_names = true;
2870 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2872 opts = reference.clone();
2873 opts.debugging_opts.no_trans = true;
2874 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2876 opts = reference.clone();
2877 opts.debugging_opts.treat_err_as_bug = true;
2878 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2880 opts = reference.clone();
2881 opts.debugging_opts.continue_parse_after_error = true;
2882 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2884 opts = reference.clone();
2885 opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
2886 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2888 opts = reference.clone();
2889 opts.debugging_opts.force_overflow_checks = Some(true);
2890 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2892 opts = reference.clone();
2893 opts.debugging_opts.enable_nonzeroing_move_hints = true;
2894 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2896 opts = reference.clone();
2897 opts.debugging_opts.show_span = Some(String::from("abc"));
2898 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2900 opts = reference.clone();
2901 opts.debugging_opts.mir_opt_level = 3;
2902 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2904 opts = reference.clone();
2905 opts.debugging_opts.relro_level = Some(RelroLevel::Full);
2906 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());