1 //! Contains infrastructure for configuring the compiler, including parsing
2 //! command line options.
6 use crate::session::{early_error, early_warn, Session};
7 use crate::session::search_paths::SearchPath;
9 use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
10 use rustc_target::spec::{Target, TargetTriple};
12 use crate::middle::cstore;
14 use syntax::ast::{self, IntTy, UintTy, MetaItemKind};
15 use syntax::source_map::{FileName, FilePathMapping};
16 use syntax::edition::{Edition, EDITION_NAME_LIST, DEFAULT_EDITION};
17 use syntax::parse::token;
19 use syntax::symbol::Symbol;
20 use syntax::feature_gate::UnstableFeatures;
22 use errors::{ColorConfig, FatalError, Handler};
25 use std::collections::{BTreeMap, BTreeSet};
26 use std::collections::btree_map::Iter as BTreeMapIter;
27 use std::collections::btree_map::Keys as BTreeMapKeysIter;
28 use std::collections::btree_map::Values as BTreeMapValuesIter;
30 use rustc_data_structures::fx::FxHashSet;
32 use std::hash::Hasher;
33 use std::collections::hash_map::DefaultHasher;
34 use std::iter::FromIterator;
35 use std::path::{Path, PathBuf};
43 #[derive(Clone, Hash, Debug)]
51 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
61 impl_stable_hash_via_hash!(OptLevel);
63 /// This is what the `LtoCli` values get mapped to after resolving defaults and
64 /// and taking other command line options into account.
65 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
67 /// Don't do any LTO whatsoever
70 /// Do a full crate graph LTO with ThinLTO
73 /// Do a local graph LTO with ThinLTO (only relevant for multiple codegen
77 /// Do a full crate graph LTO with "fat" LTO
81 /// The different settings that the `-C lto` flag can have.
82 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
94 /// No `-C lto` flag passed
98 #[derive(Clone, PartialEq, Hash)]
99 pub enum LinkerPluginLto {
100 LinkerPlugin(PathBuf),
105 impl LinkerPluginLto {
106 pub fn enabled(&self) -> bool {
108 LinkerPluginLto::LinkerPlugin(_) |
109 LinkerPluginLto::LinkerPluginAuto => true,
110 LinkerPluginLto::Disabled => false,
115 #[derive(Clone, Copy, PartialEq, Hash)]
122 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
123 pub enum OutputType {
134 impl_stable_hash_via_hash!(OutputType);
137 fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
139 OutputType::Exe | OutputType::DepInfo => true,
141 | OutputType::Assembly
142 | OutputType::LlvmAssembly
145 | OutputType::Metadata => false,
149 fn shorthand(&self) -> &'static str {
151 OutputType::Bitcode => "llvm-bc",
152 OutputType::Assembly => "asm",
153 OutputType::LlvmAssembly => "llvm-ir",
154 OutputType::Mir => "mir",
155 OutputType::Object => "obj",
156 OutputType::Metadata => "metadata",
157 OutputType::Exe => "link",
158 OutputType::DepInfo => "dep-info",
162 fn from_shorthand(shorthand: &str) -> Option<Self> {
163 Some(match shorthand {
164 "asm" => OutputType::Assembly,
165 "llvm-ir" => OutputType::LlvmAssembly,
166 "mir" => OutputType::Mir,
167 "llvm-bc" => OutputType::Bitcode,
168 "obj" => OutputType::Object,
169 "metadata" => OutputType::Metadata,
170 "link" => OutputType::Exe,
171 "dep-info" => OutputType::DepInfo,
176 fn shorthands_display() -> String {
178 "`{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`",
179 OutputType::Bitcode.shorthand(),
180 OutputType::Assembly.shorthand(),
181 OutputType::LlvmAssembly.shorthand(),
182 OutputType::Mir.shorthand(),
183 OutputType::Object.shorthand(),
184 OutputType::Metadata.shorthand(),
185 OutputType::Exe.shorthand(),
186 OutputType::DepInfo.shorthand(),
190 pub fn extension(&self) -> &'static str {
192 OutputType::Bitcode => "bc",
193 OutputType::Assembly => "s",
194 OutputType::LlvmAssembly => "ll",
195 OutputType::Mir => "mir",
196 OutputType::Object => "o",
197 OutputType::Metadata => "rmeta",
198 OutputType::DepInfo => "d",
199 OutputType::Exe => "",
204 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
205 pub enum ErrorOutputType {
206 HumanReadable(ColorConfig),
211 impl Default for ErrorOutputType {
212 fn default() -> ErrorOutputType {
213 ErrorOutputType::HumanReadable(ColorConfig::Auto)
217 // Use tree-based collections to cheaply get a deterministic Hash implementation.
218 // DO NOT switch BTreeMap out for an unsorted container type! That would break
219 // dependency tracking for command-line arguments.
220 #[derive(Clone, Hash)]
221 pub struct OutputTypes(BTreeMap<OutputType, Option<PathBuf>>);
223 impl_stable_hash_via_hash!(OutputTypes);
226 pub fn new(entries: &[(OutputType, Option<PathBuf>)]) -> OutputTypes {
227 OutputTypes(BTreeMap::from_iter(
228 entries.iter().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 pub fn len(&self) -> usize {
252 // True if any of the output types require codegen or linking.
253 pub fn should_codegen(&self) -> bool {
254 self.0.keys().any(|k| match *k {
256 | OutputType::Assembly
257 | OutputType::LlvmAssembly
260 | OutputType::Exe => true,
261 OutputType::Metadata | OutputType::DepInfo => false,
266 // Use tree-based collections to cheaply get a deterministic Hash implementation.
267 // DO NOT switch BTreeMap or BTreeSet out for an unsorted container type! That
268 // would break dependency tracking for command-line arguments.
269 #[derive(Clone, Hash)]
270 pub struct Externs(BTreeMap<String, BTreeSet<Option<String>>>);
273 pub fn new(data: BTreeMap<String, BTreeSet<Option<String>>>) -> Externs {
277 pub fn get(&self, key: &str) -> Option<&BTreeSet<Option<String>>> {
281 pub fn iter<'a>(&'a self) -> BTreeMapIter<'a, String, BTreeSet<Option<String>>> {
286 macro_rules! hash_option {
287 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [UNTRACKED]) => ({});
288 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({
289 if $sub_hashes.insert(stringify!($opt_name),
290 $opt_expr as &dyn dep_tracking::DepTrackingHash).is_some() {
291 bug!("Duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
297 [UNTRACKED_WITH_WARNING $warn_val:expr, $warn_text:expr, $error_format:expr]) => ({
298 if *$opt_expr == $warn_val {
299 early_warn($error_format, $warn_text)
304 macro_rules! top_level_options {
305 (pub struct Options { $(
306 $opt:ident : $t:ty [$dep_tracking_marker:ident $($warn_val:expr, $warn_text:expr)*],
314 pub fn dep_tracking_hash(&self) -> u64 {
315 let mut sub_hashes = BTreeMap::new();
320 [$dep_tracking_marker $($warn_val,
322 self.error_format)*]);
324 let mut hasher = DefaultHasher::new();
325 dep_tracking::stable_hash(sub_hashes,
334 // The top-level command-line options struct
336 // For each option, one has to specify how it behaves with regard to the
337 // dependency tracking system of incremental compilation. This is done via the
338 // square-bracketed directive after the field type. The options are:
341 // A change in the given field will cause the compiler to completely clear the
342 // incremental compilation cache before proceeding.
345 // Incremental compilation is not influenced by this option.
347 // [UNTRACKED_WITH_WARNING(val, warning)]
348 // The option is incompatible with incremental compilation in some way. If it
349 // has the value `val`, the string `warning` is emitted as a warning.
351 // If you add a new option to this struct or one of the sub-structs like
352 // CodegenOptions, think about how it influences incremental compilation. If in
353 // doubt, specify [TRACKED], which is always "correct" but might lead to
354 // unnecessary re-compilation.
357 // The crate config requested for the session, which may be combined
358 // with additional crate configurations during the compile process
359 crate_types: Vec<CrateType> [TRACKED],
360 optimize: OptLevel [TRACKED],
361 // Include the debug_assertions flag into dependency tracking, since it
362 // can influence whether overflow checks are done or not.
363 debug_assertions: bool [TRACKED],
364 debuginfo: DebugInfo [TRACKED],
365 lint_opts: Vec<(String, lint::Level)> [TRACKED],
366 lint_cap: Option<lint::Level> [TRACKED],
367 describe_lints: bool [UNTRACKED],
368 output_types: OutputTypes [TRACKED],
369 search_paths: Vec<SearchPath> [UNTRACKED],
370 libs: Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> [TRACKED],
371 maybe_sysroot: Option<PathBuf> [TRACKED],
373 target_triple: TargetTriple [TRACKED],
375 test: bool [TRACKED],
376 error_format: ErrorOutputType [UNTRACKED],
378 // if Some, enable incremental compilation, using the given
379 // directory to store intermediate results
380 incremental: Option<PathBuf> [UNTRACKED],
382 debugging_opts: DebuggingOptions [TRACKED],
383 prints: Vec<PrintRequest> [UNTRACKED],
384 // Determines which borrow checker(s) to run. This is the parsed, sanitized
385 // version of `debugging_opts.borrowck`, which is just a plain string.
386 borrowck_mode: BorrowckMode [UNTRACKED],
387 cg: CodegenOptions [TRACKED],
388 externs: Externs [UNTRACKED],
389 crate_name: Option<String> [TRACKED],
390 // An optional name to use as the crate for std during std injection,
391 // written `extern crate name as std`. Defaults to `std`. Used by
392 // out-of-tree drivers.
393 alt_std_name: Option<String> [TRACKED],
394 // Indicates how the compiler should treat unstable features
395 unstable_features: UnstableFeatures [TRACKED],
397 // Indicates whether this run of the compiler is actually rustdoc. This
398 // is currently just a hack and will be removed eventually, so please
399 // try to not rely on this too much.
400 actually_rustdoc: bool [TRACKED],
402 // Specifications of codegen units / ThinLTO which are forced as a
403 // result of parsing command line options. These are not necessarily
404 // what rustc was invoked with, but massaged a bit to agree with
405 // commands like `--emit llvm-ir` which they're often incompatible with
406 // if we otherwise use the defaults of rustc.
407 cli_forced_codegen_units: Option<usize> [UNTRACKED],
408 cli_forced_thinlto_off: bool [UNTRACKED],
410 // Remap source path prefixes in all output (messages, object files, debug, etc)
411 remap_path_prefix: Vec<(PathBuf, PathBuf)> [UNTRACKED],
413 edition: Edition [TRACKED],
415 // The list of crates to consider private when
416 // checking leaked private dependency types in public interfaces
417 extern_private: Vec<String> [TRACKED],
421 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
422 pub enum PrintRequest {
437 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
438 pub enum BorrowckMode {
446 /// Should we run the MIR-based borrow check, but also fall back
447 /// on the AST borrow check if the MIR-based one errors.
448 pub fn migrate(self) -> bool {
450 BorrowckMode::Ast => false,
451 BorrowckMode::Compare => false,
452 BorrowckMode::Mir => false,
453 BorrowckMode::Migrate => true,
457 /// Should we emit the AST-based borrow checker errors?
458 pub fn use_ast(self) -> bool {
460 BorrowckMode::Ast => true,
461 BorrowckMode::Compare => true,
462 BorrowckMode::Mir => false,
463 BorrowckMode::Migrate => false,
466 /// Should we emit the MIR-based borrow checker errors?
467 pub fn use_mir(self) -> bool {
469 BorrowckMode::Ast => false,
470 BorrowckMode::Compare => true,
471 BorrowckMode::Mir => true,
472 BorrowckMode::Migrate => true,
478 /// Loads source from file
481 /// String that is shown in place of a filename
483 /// Anonymous source string
489 pub fn filestem(&self) -> &str {
491 Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap(),
492 Input::Str { .. } => "rust_out",
496 pub fn get_input(&mut self) -> Option<&mut String> {
498 Input::File(_) => None,
499 Input::Str { ref mut input, .. } => Some(input),
504 #[derive(Clone, Hash)]
505 pub struct OutputFilenames {
506 pub out_directory: PathBuf,
507 pub out_filestem: String,
508 pub single_output_file: Option<PathBuf>,
510 pub outputs: OutputTypes,
513 impl_stable_hash_via_hash!(OutputFilenames);
515 pub const RUST_CGU_EXT: &str = "rcgu";
517 impl OutputFilenames {
518 pub fn path(&self, flavor: OutputType) -> PathBuf {
521 .and_then(|p| p.to_owned())
522 .or_else(|| self.single_output_file.clone())
523 .unwrap_or_else(|| self.temp_path(flavor, None))
526 /// Gets the path where a compilation artifact of the given type for the
527 /// given codegen unit should be placed on disk. If codegen_unit_name is
528 /// None, a path distinct from those of any codegen unit will be generated.
529 pub fn temp_path(&self, flavor: OutputType, codegen_unit_name: Option<&str>) -> PathBuf {
530 let extension = flavor.extension();
531 self.temp_path_ext(extension, codegen_unit_name)
534 /// Like temp_path, but also supports things where there is no corresponding
535 /// OutputType, like noopt-bitcode or lto-bitcode.
536 pub fn temp_path_ext(&self, ext: &str, codegen_unit_name: Option<&str>) -> PathBuf {
537 let base = self.out_directory.join(&self.filestem());
539 let mut extension = String::new();
541 if let Some(codegen_unit_name) = codegen_unit_name {
542 extension.push_str(codegen_unit_name);
546 if !extension.is_empty() {
547 extension.push_str(".");
548 extension.push_str(RUST_CGU_EXT);
549 extension.push_str(".");
552 extension.push_str(ext);
555 let path = base.with_extension(&extension[..]);
559 pub fn with_extension(&self, extension: &str) -> PathBuf {
561 .join(&self.filestem())
562 .with_extension(extension)
565 pub fn filestem(&self) -> String {
566 format!("{}{}", self.out_filestem, self.extra)
570 pub fn host_triple() -> &'static str {
571 // Get the host triple out of the build environment. This ensures that our
572 // idea of the host triple is the same as for the set of libraries we've
573 // actually built. We can't just take LLVM's host triple because they
574 // normalize all ix86 architectures to i386.
576 // Instead of grabbing the host triple (for the current host), we grab (at
577 // compile time) the target triple that this rustc is built with and
578 // calling that (at runtime) the host triple.
579 (option_env!("CFG_COMPILER_HOST_TRIPLE")).expect("CFG_COMPILER_HOST_TRIPLE")
582 impl Default for Options {
583 fn default() -> Options {
585 crate_types: Vec::new(),
586 optimize: OptLevel::No,
587 debuginfo: DebugInfo::None,
588 lint_opts: Vec::new(),
590 describe_lints: false,
591 output_types: OutputTypes(BTreeMap::new()),
592 search_paths: vec![],
594 target_triple: TargetTriple::from_triple(host_triple()),
597 debugging_opts: basic_debugging_options(),
599 borrowck_mode: BorrowckMode::Ast,
600 cg: basic_codegen_options(),
601 error_format: ErrorOutputType::default(),
602 externs: Externs(BTreeMap::new()),
606 unstable_features: UnstableFeatures::Disallow,
607 debug_assertions: true,
608 actually_rustdoc: false,
609 cli_forced_codegen_units: None,
610 cli_forced_thinlto_off: false,
611 remap_path_prefix: Vec::new(),
612 edition: DEFAULT_EDITION,
613 extern_private: Vec::new()
619 /// Returns `true` if there is a reason to build the dep graph.
620 pub fn build_dep_graph(&self) -> bool {
621 self.incremental.is_some() || 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(self.remap_path_prefix.clone())
635 /// Returns `true` if there will be an output file generated
636 pub fn will_create_output_file(&self) -> bool {
637 !self.debugging_opts.parse_only && // The file is just being parsed
638 !self.debugging_opts.ls // The file is just being queried
642 pub fn share_generics(&self) -> bool {
643 match self.debugging_opts.share_generics {
644 Some(setting) => setting,
646 match self.optimize {
650 OptLevel::SizeMin => true,
652 OptLevel::Aggressive => false,
659 // The type of entry function, so users can have their own entry functions
660 #[derive(Copy, Clone, PartialEq, Hash, Debug)]
661 pub enum EntryFnType {
666 impl_stable_hash_via_hash!(EntryFnType);
668 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
678 #[derive(Clone, Hash)]
685 pub fn is_empty(&self) -> bool {
687 Passes::Some(ref v) => v.is_empty(),
688 Passes::All => false,
693 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
694 /// at once. The goal of this macro is to define an interface that can be
695 /// programmatically used by the option parser in order to initialize the struct
696 /// without hardcoding field names all over the place.
698 /// The goal is to invoke this macro once with the correct fields, and then this
699 /// macro generates all necessary code. The main gotcha of this macro is the
700 /// cgsetters module which is a bunch of generated code to parse an option into
701 /// its respective field in the struct. There are a few hand-written parsers for
702 /// parsing specific types of values in this module.
703 macro_rules! options {
704 ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
705 $buildfn:ident, $prefix:expr, $outputname:expr,
706 $stat:ident, $mod_desc:ident, $mod_set:ident,
707 $($opt:ident : $t:ty = (
710 [$dep_tracking_marker:ident $(($dep_warn_val:expr, $dep_warn_text:expr))*],
715 pub struct $struct_name { $(pub $opt: $t),* }
717 pub fn $defaultfn() -> $struct_name {
718 $struct_name { $($opt: $init),* }
721 pub fn $buildfn(matches: &getopts::Matches, error_format: ErrorOutputType) -> $struct_name
723 let mut op = $defaultfn();
724 for option in matches.opt_strs($prefix) {
725 let mut iter = option.splitn(2, '=');
726 let key = iter.next().unwrap();
727 let value = iter.next();
728 let option_to_lookup = key.replace("-", "_");
729 let mut found = false;
730 for &(candidate, setter, opt_type_desc, _) in $stat {
731 if option_to_lookup != candidate { continue }
732 if !setter(&mut op, value) {
733 match (value, opt_type_desc) {
734 (Some(..), None) => {
735 early_error(error_format, &format!("{} option `{}` takes no \
736 value", $outputname, key))
738 (None, Some(type_desc)) => {
739 early_error(error_format, &format!("{0} option `{1}` requires \
740 {2} ({3} {1}=<value>)",
744 (Some(value), Some(type_desc)) => {
745 early_error(error_format, &format!("incorrect value `{}` for {} \
746 option `{}` - {} was expected",
750 (None, None) => bug!()
757 early_error(error_format, &format!("unknown {} option: `{}`",
764 impl<'a> dep_tracking::DepTrackingHash for $struct_name {
765 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
766 let mut sub_hashes = BTreeMap::new();
771 [$dep_tracking_marker $($dep_warn_val,
775 dep_tracking::stable_hash(sub_hashes, hasher, error_format);
779 pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
780 pub const $stat: &[(&str, $setter_name, Option<&str>, &str)] =
781 &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
783 #[allow(non_upper_case_globals, dead_code)]
785 pub const parse_bool: Option<&str> = None;
786 pub const parse_opt_bool: Option<&str> =
787 Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
788 pub const parse_string: Option<&str> = Some("a string");
789 pub const parse_string_push: Option<&str> = Some("a string");
790 pub const parse_pathbuf_push: Option<&str> = Some("a path");
791 pub const parse_opt_string: Option<&str> = Some("a string");
792 pub const parse_opt_pathbuf: Option<&str> = Some("a path");
793 pub const parse_list: Option<&str> = Some("a space-separated list of strings");
794 pub const parse_opt_list: Option<&str> = Some("a space-separated list of strings");
795 pub const parse_uint: Option<&str> = Some("a number");
796 pub const parse_passes: Option<&str> =
797 Some("a space-separated list of passes, or `all`");
798 pub const parse_opt_uint: Option<&str> =
800 pub const parse_panic_strategy: Option<&str> =
801 Some("either `unwind` or `abort`");
802 pub const parse_relro_level: Option<&str> =
803 Some("one of: `full`, `partial`, or `off`");
804 pub const parse_sanitizer: Option<&str> =
805 Some("one of: `address`, `leak`, `memory` or `thread`");
806 pub const parse_linker_flavor: Option<&str> =
807 Some(::rustc_target::spec::LinkerFlavor::one_of());
808 pub const parse_optimization_fuel: Option<&str> =
809 Some("crate=integer");
810 pub const parse_unpretty: Option<&str> =
811 Some("`string` or `string=string`");
812 pub const parse_lto: Option<&str> =
813 Some("either a boolean (`yes`, `no`, `on`, `off`, etc), `thin`, \
815 pub const parse_linker_plugin_lto: Option<&str> =
816 Some("either a boolean (`yes`, `no`, `on`, `off`, etc), \
817 or the path to the linker plugin");
818 pub const parse_merge_functions: Option<&str> =
819 Some("one of: `disabled`, `trampolines`, or `aliases`");
824 use super::{$struct_name, Passes, Sanitizer, LtoCli, LinkerPluginLto};
825 use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
826 use std::path::PathBuf;
827 use std::str::FromStr;
830 pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
831 $parse(&mut cg.$opt, v)
835 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
838 None => { *slot = true; true }
842 fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
846 "n" | "no" | "off" => {
849 "y" | "yes" | "on" => {
852 _ => { return false; }
857 None => { *slot = Some(true); true }
861 fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
863 Some(s) => { *slot = Some(s.to_string()); true },
868 fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
870 Some(s) => { *slot = Some(PathBuf::from(s)); true },
875 fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
877 Some(s) => { *slot = s.to_string(); true },
882 fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
884 Some(s) => { slot.push(s.to_string()); true },
889 fn parse_pathbuf_push(slot: &mut Vec<PathBuf>, v: Option<&str>) -> bool {
891 Some(s) => { slot.push(PathBuf::from(s)); true },
896 fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
900 slot.extend(s.split_whitespace().map(|s| s.to_string()));
907 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
911 let v = s.split_whitespace().map(|s| s.to_string()).collect();
919 fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
920 match v.and_then(|s| s.parse().ok()) {
921 Some(i) => { *slot = i; true },
926 fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
928 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
929 None => { *slot = None; false }
933 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
940 let mut passes = vec![];
941 if parse_list(&mut passes, v) {
942 *slot = Passes::Some(passes);
951 fn parse_panic_strategy(slot: &mut Option<PanicStrategy>, v: Option<&str>) -> bool {
953 Some("unwind") => *slot = Some(PanicStrategy::Unwind),
954 Some("abort") => *slot = Some(PanicStrategy::Abort),
960 fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
963 match s.parse::<RelroLevel>() {
964 Ok(level) => *slot = Some(level),
973 fn parse_sanitizer(slote: &mut Option<Sanitizer>, v: Option<&str>) -> bool {
975 Some("address") => *slote = Some(Sanitizer::Address),
976 Some("leak") => *slote = Some(Sanitizer::Leak),
977 Some("memory") => *slote = Some(Sanitizer::Memory),
978 Some("thread") => *slote = Some(Sanitizer::Thread),
984 fn parse_linker_flavor(slote: &mut Option<LinkerFlavor>, v: Option<&str>) -> bool {
985 match v.and_then(LinkerFlavor::from_str) {
986 Some(lf) => *slote = Some(lf),
992 fn parse_optimization_fuel(slot: &mut Option<(String, u64)>, v: Option<&str>) -> bool {
996 let parts = s.split('=').collect::<Vec<_>>();
997 if parts.len() != 2 { return false; }
998 let crate_name = parts[0].to_string();
999 let fuel = parts[1].parse::<u64>();
1000 if fuel.is_err() { return false; }
1001 *slot = Some((crate_name, fuel.unwrap()));
1007 fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
1010 Some(s) if s.split('=').count() <= 2 => {
1011 *slot = Some(s.to_string());
1018 fn parse_lto(slot: &mut LtoCli, v: Option<&str>) -> bool {
1020 let mut bool_arg = None;
1021 if parse_opt_bool(&mut bool_arg, v) {
1022 *slot = if bool_arg.unwrap() {
1032 None => LtoCli::NoParam,
1033 Some("thin") => LtoCli::Thin,
1034 Some("fat") => LtoCli::Fat,
1035 Some(_) => return false,
1040 fn parse_linker_plugin_lto(slot: &mut LinkerPluginLto, v: Option<&str>) -> bool {
1042 let mut bool_arg = None;
1043 if parse_opt_bool(&mut bool_arg, v) {
1044 *slot = if bool_arg.unwrap() {
1045 LinkerPluginLto::LinkerPluginAuto
1047 LinkerPluginLto::Disabled
1054 None => LinkerPluginLto::LinkerPluginAuto,
1055 Some(path) => LinkerPluginLto::LinkerPlugin(PathBuf::from(path)),
1060 fn parse_merge_functions(slot: &mut Option<MergeFunctions>, v: Option<&str>) -> bool {
1061 match v.and_then(|s| MergeFunctions::from_str(s).ok()) {
1062 Some(mergefunc) => *slot = Some(mergefunc),
1070 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
1071 build_codegen_options, "C", "codegen",
1072 CG_OPTIONS, cg_type_desc, cgsetters,
1073 ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
1074 "this option is deprecated and does nothing"),
1075 linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
1076 "system linker to link outputs with"),
1077 link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1078 "a single extra argument to append to the linker invocation (can be used several times)"),
1079 link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1080 "extra arguments to append to the linker invocation (space separated)"),
1081 link_dead_code: bool = (false, parse_bool, [UNTRACKED],
1082 "don't let linker strip dead code (turning it on can be used for code coverage)"),
1083 lto: LtoCli = (LtoCli::Unspecified, parse_lto, [TRACKED],
1084 "perform LLVM link-time optimizations"),
1085 target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
1086 "select target processor (rustc --print target-cpus for details)"),
1087 target_feature: String = (String::new(), parse_string, [TRACKED],
1088 "target specific attributes (rustc --print target-features for details)"),
1089 passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1090 "a list of extra LLVM passes to run (space separated)"),
1091 llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1092 "a list of arguments to pass to llvm (space separated)"),
1093 save_temps: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1094 "`-C save-temps` might not produce all requested temporary products \
1095 when incremental compilation is enabled.")],
1096 "save all temporary output files during compilation"),
1097 rpath: bool = (false, parse_bool, [UNTRACKED],
1098 "set rpath values in libs/exes"),
1099 overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1100 "use overflow checks for integer arithmetic"),
1101 no_prepopulate_passes: bool = (false, parse_bool, [TRACKED],
1102 "don't pre-populate the pass manager with a list of passes"),
1103 no_vectorize_loops: bool = (false, parse_bool, [TRACKED],
1104 "don't run the loop vectorization optimization passes"),
1105 no_vectorize_slp: bool = (false, parse_bool, [TRACKED],
1106 "don't run LLVM's SLP vectorization pass"),
1107 soft_float: bool = (false, parse_bool, [TRACKED],
1108 "use soft float ABI (*eabihf targets only)"),
1109 prefer_dynamic: bool = (false, parse_bool, [TRACKED],
1110 "prefer dynamic linking to static linking"),
1111 no_integrated_as: bool = (false, parse_bool, [TRACKED],
1112 "use an external assembler rather than LLVM's integrated one"),
1113 no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
1114 "disable the use of the redzone"),
1115 relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
1116 "choose the relocation model to use (rustc --print relocation-models for details)"),
1117 code_model: Option<String> = (None, parse_opt_string, [TRACKED],
1118 "choose the code model to use (rustc --print code-models for details)"),
1119 metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1120 "metadata to mangle symbol names with"),
1121 extra_filename: String = (String::new(), parse_string, [UNTRACKED],
1122 "extra data to put in each output filename"),
1123 codegen_units: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1124 "divide crate into N units to optimize in parallel"),
1125 remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
1126 "print remarks for these optimization passes (space separated, or \"all\")"),
1127 no_stack_check: bool = (false, parse_bool, [UNTRACKED],
1128 "the --no-stack-check flag is deprecated and does nothing"),
1129 debuginfo: Option<usize> = (None, parse_opt_uint, [TRACKED],
1130 "debug info emission level, 0 = no debug info, 1 = line tables only, \
1131 2 = full debug info with variable and type information"),
1132 opt_level: Option<String> = (None, parse_opt_string, [TRACKED],
1133 "optimize with possible levels 0-3, s, or z"),
1134 force_frame_pointers: Option<bool> = (None, parse_opt_bool, [TRACKED],
1135 "force use of the frame pointers"),
1136 debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
1137 "explicitly enable the cfg(debug_assertions) directive"),
1138 inline_threshold: Option<usize> = (None, parse_opt_uint, [TRACKED],
1139 "set the threshold for inlining a function (default: 225)"),
1140 panic: Option<PanicStrategy> = (None, parse_panic_strategy,
1141 [TRACKED], "panic strategy to compile crate with"),
1142 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1143 "enable incremental compilation"),
1144 default_linker_libraries: Option<bool> = (None, parse_opt_bool, [UNTRACKED],
1145 "allow the linker to link its default libraries"),
1146 linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
1148 linker_plugin_lto: LinkerPluginLto = (LinkerPluginLto::Disabled,
1149 parse_linker_plugin_lto, [TRACKED],
1150 "generate build artifacts that are compatible with linker-based LTO."),
1154 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
1155 build_debugging_options, "Z", "debugging",
1156 DB_OPTIONS, db_type_desc, dbsetters,
1157 codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
1158 "the backend to use"),
1159 verbose: bool = (false, parse_bool, [UNTRACKED],
1160 "in general, enable more debug printouts"),
1161 span_free_formats: bool = (false, parse_bool, [UNTRACKED],
1162 "when debug-printing compiler state, do not include spans"), // o/w tests have closure@path
1163 identify_regions: bool = (false, parse_bool, [UNTRACKED],
1164 "make unnamed regions display as '# (where # is some non-ident unique id)"),
1165 borrowck: Option<String> = (None, parse_opt_string, [UNTRACKED],
1166 "select which borrowck is used (`ast`, `mir`, `migrate`, or `compare`)"),
1167 two_phase_borrows: bool = (false, parse_bool, [UNTRACKED],
1168 "use two-phase reserved/active distinction for `&mut` borrows in MIR borrowck"),
1169 two_phase_beyond_autoref: bool = (false, parse_bool, [UNTRACKED],
1170 "when using two-phase-borrows, allow two phases even for non-autoref `&mut` borrows"),
1171 time_passes: bool = (false, parse_bool, [UNTRACKED],
1172 "measure time of each rustc pass"),
1173 count_llvm_insns: bool = (false, parse_bool,
1174 [UNTRACKED_WITH_WARNING(true,
1175 "The output generated by `-Z count_llvm_insns` might not be reliable \
1176 when used with incremental compilation")],
1177 "count where LLVM instrs originate"),
1178 time_llvm_passes: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1179 "The output of `-Z time-llvm-passes` will only reflect timings of \
1180 re-codegened modules when used with incremental compilation" )],
1181 "measure time of each LLVM pass"),
1182 input_stats: bool = (false, parse_bool, [UNTRACKED],
1183 "gather statistics about the input"),
1184 codegen_stats: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1185 "The output of `-Z codegen-stats` might not be accurate when incremental \
1186 compilation is enabled")],
1187 "gather codegen statistics"),
1188 asm_comments: bool = (false, parse_bool, [TRACKED],
1189 "generate comments into the assembly (may change behavior)"),
1190 verify_llvm_ir: bool = (false, parse_bool, [TRACKED],
1192 borrowck_stats: bool = (false, parse_bool, [UNTRACKED],
1193 "gather borrowck statistics"),
1194 no_landing_pads: bool = (false, parse_bool, [TRACKED],
1195 "omit landing pads for unwinding"),
1196 fewer_names: bool = (false, parse_bool, [TRACKED],
1197 "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR)"),
1198 meta_stats: bool = (false, parse_bool, [UNTRACKED],
1199 "gather metadata statistics"),
1200 print_link_args: bool = (false, parse_bool, [UNTRACKED],
1201 "print the arguments passed to the linker"),
1202 print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1203 "prints the llvm optimization passes being run"),
1204 ast_json: bool = (false, parse_bool, [UNTRACKED],
1205 "print the AST as JSON and halt"),
1206 threads: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1207 "use a thread pool with N threads"),
1208 ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
1209 "print the pre-expansion AST as JSON and halt"),
1210 ls: bool = (false, parse_bool, [UNTRACKED],
1211 "list the symbols defined by a library crate"),
1212 save_analysis: bool = (false, parse_bool, [UNTRACKED],
1213 "write syntax and type analysis (in JSON format) information, in \
1214 addition to normal output"),
1215 flowgraph_print_loans: bool = (false, parse_bool, [UNTRACKED],
1216 "include loan analysis data in -Z unpretty flowgraph output"),
1217 flowgraph_print_moves: bool = (false, parse_bool, [UNTRACKED],
1218 "include move analysis data in -Z unpretty flowgraph output"),
1219 flowgraph_print_assigns: bool = (false, parse_bool, [UNTRACKED],
1220 "include assignment analysis data in -Z unpretty flowgraph output"),
1221 flowgraph_print_all: bool = (false, parse_bool, [UNTRACKED],
1222 "include all dataflow analysis data in -Z unpretty flowgraph output"),
1223 print_region_graph: bool = (false, parse_bool, [UNTRACKED],
1224 "prints region inference graph. \
1225 Use with RUST_REGION_GRAPH=help for more info"),
1226 parse_only: bool = (false, parse_bool, [UNTRACKED],
1227 "parse only; do not compile, assemble, or link"),
1228 no_codegen: bool = (false, parse_bool, [TRACKED],
1229 "run all passes except codegen; no output"),
1230 treat_err_as_bug: bool = (false, parse_bool, [TRACKED],
1231 "treat all errors that occur as bugs"),
1232 report_delayed_bugs: bool = (false, parse_bool, [TRACKED],
1233 "immediately print bugs registered with `delay_span_bug`"),
1234 external_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1235 "show macro backtraces even for non-local macros"),
1236 teach: bool = (false, parse_bool, [TRACKED],
1237 "show extended diagnostic help"),
1238 continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
1239 "attempt to recover from parse errors (experimental)"),
1240 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1241 "enable incremental compilation (experimental)"),
1242 incremental_queries: bool = (true, parse_bool, [UNTRACKED],
1243 "enable incremental compilation support for queries (experimental)"),
1244 incremental_info: bool = (false, parse_bool, [UNTRACKED],
1245 "print high-level information about incremental reuse (or the lack thereof)"),
1246 incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
1247 "dump hash information in textual format to stdout"),
1248 incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
1249 "verify incr. comp. hashes of green query instances"),
1250 incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
1251 "ignore spans during ICH computation -- used for testing"),
1252 instrument_mcount: bool = (false, parse_bool, [TRACKED],
1253 "insert function instrument code for mcount-based tracing"),
1254 dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1255 "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
1256 query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1257 "enable queries of the dependency graph for regression testing"),
1258 profile_queries: bool = (false, parse_bool, [UNTRACKED],
1259 "trace and profile the queries of the incremental compilation framework"),
1260 profile_queries_and_keys: bool = (false, parse_bool, [UNTRACKED],
1261 "trace and profile the queries and keys of the incremental compilation framework"),
1262 no_analysis: bool = (false, parse_bool, [UNTRACKED],
1263 "parse and expand the source, but run no analysis"),
1264 extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1265 "load extra plugins"),
1266 unstable_options: bool = (false, parse_bool, [UNTRACKED],
1267 "adds unstable command line options to rustc interface"),
1268 force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1269 "force overflow checks on or off"),
1270 trace_macros: bool = (false, parse_bool, [UNTRACKED],
1271 "for every macro invocation, print its name and arguments"),
1272 debug_macros: bool = (false, parse_bool, [TRACKED],
1273 "emit line numbers debug info inside macros"),
1274 keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
1275 "don't clear the hygiene data after analysis"),
1276 keep_ast: bool = (false, parse_bool, [UNTRACKED],
1277 "keep the AST after lowering it to HIR"),
1278 show_span: Option<String> = (None, parse_opt_string, [TRACKED],
1279 "show spans for compiler debugging (expr|pat|ty)"),
1280 print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
1281 "print layout information for each type encountered"),
1282 print_mono_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
1283 "print the result of the monomorphization collection pass"),
1284 mir_opt_level: usize = (1, parse_uint, [TRACKED],
1285 "set the MIR optimization level (0-3, default: 1)"),
1286 mutable_noalias: Option<bool> = (None, parse_opt_bool, [TRACKED],
1287 "emit noalias metadata for mutable references (default: yes on LLVM >= 6)"),
1288 dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1289 "dump MIR state to file.
1290 `val` is used to select which passes and functions to dump. For example:
1291 `all` matches all passes and functions,
1292 `foo` matches all passes for functions whose name contains 'foo',
1293 `foo & ConstProp` only the 'ConstProp' pass for function names containing 'foo',
1294 `foo | bar` all passes for function names containing 'foo' or 'bar'."),
1296 dump_mir_dir: String = (String::from("mir_dump"), parse_string, [UNTRACKED],
1297 "the directory the MIR is dumped into"),
1298 dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
1299 "in addition to `.mir` files, create graphviz `.dot` files"),
1300 dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
1301 "if set, exclude the pass number when dumping MIR (used in tests)"),
1302 mir_emit_retag: bool = (false, parse_bool, [TRACKED],
1303 "emit Retagging MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0"),
1304 perf_stats: bool = (false, parse_bool, [UNTRACKED],
1305 "print some performance-related statistics"),
1306 query_stats: bool = (false, parse_bool, [UNTRACKED],
1307 "print some statistics about the query system"),
1308 hir_stats: bool = (false, parse_bool, [UNTRACKED],
1309 "print some statistics about AST and HIR"),
1310 always_encode_mir: bool = (false, parse_bool, [TRACKED],
1311 "encode MIR of all functions into the crate metadata"),
1312 unleash_the_miri_inside_of_you: bool = (false, parse_bool, [TRACKED],
1313 "take the breaks off const evaluation. NOTE: this is unsound"),
1314 osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
1315 "pass `-install_name @rpath/...` to the macOS linker"),
1316 sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
1318 fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
1319 "set the optimization fuel quota for a crate"),
1320 print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
1321 "make Rustc print the total optimization fuel used by a crate"),
1322 force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
1323 "force all crates to be `rustc_private` unstable"),
1324 pre_link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1325 "a single extra argument to prepend the linker invocation (can be used several times)"),
1326 pre_link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1327 "extra arguments to prepend to the linker invocation (space separated)"),
1328 profile: bool = (false, parse_bool, [TRACKED],
1329 "insert profiling code"),
1330 pgo_gen: Option<String> = (None, parse_opt_string, [TRACKED],
1331 "Generate PGO profile data, to a given file, or to the default location if it's empty."),
1332 pgo_use: String = (String::new(), parse_string, [TRACKED],
1333 "Use PGO profile data from the given profile file."),
1334 disable_instrumentation_preinliner: bool = (false, parse_bool, [TRACKED],
1335 "Disable the instrumentation pre-inliner, useful for profiling / PGO."),
1336 relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
1337 "choose which RELRO level to use"),
1338 nll_facts: bool = (false, parse_bool, [UNTRACKED],
1339 "dump facts from NLL analysis into side files"),
1340 nll_dont_emit_read_for_match: bool = (false, parse_bool, [UNTRACKED],
1341 "in match codegen, do not include FakeRead statements (used by mir-borrowck)"),
1342 dont_buffer_diagnostics: bool = (false, parse_bool, [UNTRACKED],
1343 "emit diagnostics rather than buffering (breaks NLL error downgrading, sorting)."),
1344 polonius: bool = (false, parse_bool, [UNTRACKED],
1345 "enable polonius-based borrow-checker"),
1346 codegen_time_graph: bool = (false, parse_bool, [UNTRACKED],
1347 "generate a graphical HTML report of time spent in codegen and LLVM"),
1348 thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
1349 "enable ThinLTO when possible"),
1350 inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
1351 "control whether #[inline] functions are in all cgus"),
1352 tls_model: Option<String> = (None, parse_opt_string, [TRACKED],
1353 "choose the TLS model to use (rustc --print tls-models for details)"),
1354 saturating_float_casts: bool = (false, parse_bool, [TRACKED],
1355 "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
1356 the max/min integer respectively, and NaN is mapped to 0"),
1357 lower_128bit_ops: Option<bool> = (None, parse_opt_bool, [TRACKED],
1358 "rewrite operators on i128 and u128 into lang item calls (typically provided \
1359 by compiler-builtins) so codegen doesn't need to support them,
1360 overriding the default for the current target"),
1361 human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
1362 "generate human-readable, predictable names for codegen units"),
1363 dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
1364 "in dep-info output, omit targets for tracking dependencies of the dep-info files \
1366 unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
1367 "Present the input source, unstable (and less-pretty) variants;
1368 valid types are any of the types for `--pretty`, as well as:
1369 `expanded`, `expanded,identified`,
1370 `expanded,hygiene` (with internal representations),
1371 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
1372 `flowgraph,unlabelled=<nodeid>` (unlabelled graphviz formatted flowgraph for node),
1373 `everybody_loops` (all function bodies replaced with `loop {}`),
1374 `hir` (the HIR), `hir,identified`,
1375 `hir,typed` (HIR with types for each node),
1376 `hir-tree` (dump the raw HIR),
1377 `mir` (the MIR), or `mir-cfg` (graphviz formatted MIR)"),
1378 run_dsymutil: Option<bool> = (None, parse_opt_bool, [TRACKED],
1379 "run `dsymutil` and delete intermediate object files"),
1380 ui_testing: bool = (false, parse_bool, [UNTRACKED],
1381 "format compiler diagnostics in a way that's better suitable for UI testing"),
1382 embed_bitcode: bool = (false, parse_bool, [TRACKED],
1383 "embed LLVM bitcode in object files"),
1384 strip_debuginfo_if_disabled: Option<bool> = (None, parse_opt_bool, [TRACKED],
1385 "tell the linker to strip debuginfo when building without debuginfo enabled."),
1386 share_generics: Option<bool> = (None, parse_opt_bool, [TRACKED],
1387 "make the current crate share its generic instantiations"),
1388 chalk: bool = (false, parse_bool, [TRACKED],
1389 "enable the experimental Chalk-based trait solving engine"),
1390 no_parallel_llvm: bool = (false, parse_bool, [UNTRACKED],
1391 "don't run LLVM in parallel (while keeping codegen-units and ThinLTO)"),
1392 no_leak_check: bool = (false, parse_bool, [UNTRACKED],
1393 "disables the 'leak check' for subtyping; unsound, but useful for tests"),
1394 no_interleave_lints: bool = (false, parse_bool, [UNTRACKED],
1395 "don't interleave execution of lints; allows benchmarking individual lints"),
1396 crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],
1397 "inject the given attribute in the crate"),
1398 self_profile: bool = (false, parse_bool, [UNTRACKED],
1399 "run the self profiler"),
1400 profile_json: bool = (false, parse_bool, [UNTRACKED],
1401 "output a json file with profiler results"),
1402 emit_stack_sizes: bool = (false, parse_bool, [UNTRACKED],
1403 "emits a section containing stack size metadata"),
1404 plt: Option<bool> = (None, parse_opt_bool, [TRACKED],
1405 "whether to use the PLT when calling into shared libraries;
1406 only has effect for PIC code on systems with ELF binaries
1407 (default: PLT is disabled if full relro is enabled)"),
1408 merge_functions: Option<MergeFunctions> = (None, parse_merge_functions, [TRACKED],
1409 "control the operation of the MergeFunctions LLVM pass, taking
1410 the same values as the target option of the same name"),
1413 pub fn default_lib_output() -> CrateType {
1417 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
1418 let end = &sess.target.target.target_endian;
1419 let arch = &sess.target.target.arch;
1420 let wordsz = &sess.target.target.target_pointer_width;
1421 let os = &sess.target.target.target_os;
1422 let env = &sess.target.target.target_env;
1423 let vendor = &sess.target.target.target_vendor;
1424 let min_atomic_width = sess.target.target.min_atomic_width();
1425 let max_atomic_width = sess.target.target.max_atomic_width();
1426 let atomic_cas = sess.target.target.options.atomic_cas;
1428 let mut ret = FxHashSet::default();
1429 ret.reserve(6); // the minimum number of insertions
1431 ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
1432 if let Some(ref fam) = sess.target.target.options.target_family {
1433 ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam))));
1434 if fam == "windows" || fam == "unix" {
1435 ret.insert((Symbol::intern(fam), None));
1438 ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
1439 ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
1441 Symbol::intern("target_pointer_width"),
1442 Some(Symbol::intern(wordsz)),
1444 ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
1446 Symbol::intern("target_vendor"),
1447 Some(Symbol::intern(vendor)),
1449 if sess.target.target.options.has_elf_tls {
1450 ret.insert((Symbol::intern("target_thread_local"), None));
1452 for &i in &[8, 16, 32, 64, 128] {
1453 if i >= min_atomic_width && i <= max_atomic_width {
1454 let s = i.to_string();
1456 Symbol::intern("target_has_atomic"),
1457 Some(Symbol::intern(&s)),
1461 Symbol::intern("target_has_atomic"),
1462 Some(Symbol::intern("ptr")),
1468 ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern("cas"))));
1470 if sess.opts.debug_assertions {
1471 ret.insert((Symbol::intern("debug_assertions"), None));
1473 if sess.opts.crate_types.contains(&CrateType::ProcMacro) {
1474 ret.insert((Symbol::intern("proc_macro"), None));
1479 pub fn build_configuration(sess: &Session, mut user_cfg: ast::CrateConfig) -> ast::CrateConfig {
1480 // Combine the configuration requested by the session (command line) with
1481 // some default and generated configuration items
1482 let default_cfg = default_configuration(sess);
1483 // If the user wants a test runner, then add the test cfg
1485 user_cfg.insert((Symbol::intern("test"), None));
1487 user_cfg.extend(default_cfg.iter().cloned());
1491 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
1492 let target = Target::search(&opts.target_triple).unwrap_or_else(|e| {
1493 sp.struct_fatal(&format!("Error loading target specification: {}", e))
1494 .help("Use `--print target-list` for a list of built-in targets")
1499 let (isize_ty, usize_ty) = match &target.target_pointer_width[..] {
1500 "16" => (ast::IntTy::I16, ast::UintTy::U16),
1501 "32" => (ast::IntTy::I32, ast::UintTy::U32),
1502 "64" => (ast::IntTy::I64, ast::UintTy::U64),
1503 w => sp.fatal(&format!(
1504 "target specification was invalid: \
1505 unrecognized target-pointer-width {}",
1517 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1518 pub enum OptionStability {
1523 pub struct RustcOptGroup {
1524 pub apply: Box<dyn Fn(&mut getopts::Options) -> &mut getopts::Options>,
1525 pub name: &'static str,
1526 pub stability: OptionStability,
1529 impl RustcOptGroup {
1530 pub fn is_stable(&self) -> bool {
1531 self.stability == OptionStability::Stable
1534 pub fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
1536 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1541 stability: OptionStability::Stable,
1545 pub fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
1547 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1552 stability: OptionStability::Unstable,
1557 // The `opt` local module holds wrappers around the `getopts` API that
1558 // adds extra rustc-specific metadata to each option; such metadata
1559 // is exposed by . The public
1560 // functions below ending with `_u` are the functions that return
1561 // *unstable* options, i.e., options that are only enabled when the
1562 // user also passes the `-Z unstable-options` debugging flag.
1564 // The `fn opt_u` etc below are written so that we can use them
1565 // in the future; do not warn about them not being used right now.
1566 #![allow(dead_code)]
1569 use super::RustcOptGroup;
1571 pub type R = RustcOptGroup;
1572 pub type S = &'static str;
1574 fn stable<F>(name: S, f: F) -> R
1576 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1578 RustcOptGroup::stable(name, f)
1581 fn unstable<F>(name: S, f: F) -> R
1583 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1585 RustcOptGroup::unstable(name, f)
1588 fn longer(a: S, b: S) -> S {
1589 if a.len() > b.len() {
1596 pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
1597 stable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1599 pub fn multi_s(a: S, b: S, c: S, d: S) -> R {
1600 stable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1602 pub fn flag_s(a: S, b: S, c: S) -> R {
1603 stable(longer(a, b), move |opts| opts.optflag(a, b, c))
1605 pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R {
1606 stable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1608 pub fn flagmulti_s(a: S, b: S, c: S) -> R {
1609 stable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1612 pub fn opt(a: S, b: S, c: S, d: S) -> R {
1613 unstable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1615 pub fn multi(a: S, b: S, c: S, d: S) -> R {
1616 unstable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1618 pub fn flag(a: S, b: S, c: S) -> R {
1619 unstable(longer(a, b), move |opts| opts.optflag(a, b, c))
1621 pub fn flagopt(a: S, b: S, c: S, d: S) -> R {
1622 unstable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1624 pub fn flagmulti(a: S, b: S, c: S) -> R {
1625 unstable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1629 /// Returns the "short" subset of the rustc command line options,
1630 /// including metadata for each option, such as whether the option is
1631 /// part of the stable long-term interface for rustc.
1632 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
1634 opt::flag_s("h", "help", "Display this message"),
1635 opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
1639 "Add a directory to the library search path. The
1640 optional KIND can be one of dependency, crate, native,
1641 framework or all (the default).",
1647 "Link the generated crate(s) to the specified native
1648 library NAME. The optional KIND can be one of
1649 static, dylib, or framework. If omitted, dylib is
1656 "Comma separated list of types of crates
1657 for the compiler to emit",
1658 "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]",
1663 "Specify the name of the crate being built",
1669 "Comma separated list of types of output for \
1670 the compiler to emit",
1671 "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]",
1676 "Comma separated list of compiler information to \
1678 "[crate-name|file-names|sysroot|cfg|target-list|\
1679 target-cpus|target-features|relocation-models|\
1680 code-models|tls-models|target-spec-json|native-static-libs]",
1682 opt::flagmulti_s("g", "", "Equivalent to -C debuginfo=2"),
1683 opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
1684 opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
1688 "Write output to compiler-chosen filename \
1695 "Provide a detailed explanation of an error \
1699 opt::flag_s("", "test", "Build a test harness"),
1703 "Target triple for which the code is compiled",
1706 opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
1707 opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
1708 opt::multi_s("D", "deny", "Set lint denied", "OPT"),
1709 opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
1713 "Set the most restrictive lint level. \
1714 More restrictive lints are capped at this \
1718 opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
1719 opt::flag_s("V", "version", "Print version info and exit"),
1720 opt::flag_s("v", "verbose", "Use verbose output"),
1724 /// Returns all rustc command line options, including metadata for
1725 /// each option, such as whether the option is part of the stable
1726 /// long-term interface for rustc.
1727 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
1728 let mut opts = rustc_short_optgroups();
1733 "Specify where an external rust library is located",
1739 "Specify where an extern rust library is located, marking it as a private dependency",
1742 opt::opt_s("", "sysroot", "Override the system root", "PATH"),
1743 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
1747 "How errors and other messages are produced",
1753 "Configure coloring of output:
1754 auto = colorize, if output goes to a tty (default);
1755 always = always colorize output;
1756 never = never colorize output",
1757 "auto|always|never",
1762 "Pretty-print the input instead of compiling;
1763 valid types are: `normal` (un-annotated source),
1764 `expanded` (crates expanded), or
1765 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
1771 "Specify which edition of the compiler to use when compiling code.",
1776 "remap-path-prefix",
1777 "Remap source names in all output (compiler messages and output files)",
1784 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
1785 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> ast::CrateConfig {
1789 let sess = parse::ParseSess::new(FilePathMapping::empty());
1790 let filename = FileName::cfg_spec_source_code(&s);
1791 let mut parser = parse::new_parser_from_source_str(&sess, filename, s.to_string());
1793 macro_rules! error {($reason: expr) => {
1794 early_error(ErrorOutputType::default(),
1795 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s));
1798 match &mut parser.parse_meta_item() {
1799 Ok(meta_item) if parser.token == token::Eof => {
1800 if meta_item.ident.segments.len() != 1 {
1801 error!("argument key must be an identifier");
1803 match &meta_item.node {
1804 MetaItemKind::List(..) => {
1805 error!(r#"expected `key` or `key="value"`"#);
1807 MetaItemKind::NameValue(lit) if !lit.node.is_str() => {
1808 error!("argument value must be a string");
1810 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
1811 return (meta_item.name(), meta_item.value_str());
1816 Err(err) => err.cancel(),
1819 error!(r#"expected `key` or `key="value"`"#);
1821 .collect::<ast::CrateConfig>()
1824 pub fn get_cmd_lint_options(matches: &getopts::Matches,
1825 error_format: ErrorOutputType)
1826 -> (Vec<(String, lint::Level)>, bool, Option<lint::Level>) {
1827 let mut lint_opts = vec![];
1828 let mut describe_lints = false;
1830 for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
1831 for lint_name in matches.opt_strs(level.as_str()) {
1832 if lint_name == "help" {
1833 describe_lints = true;
1835 lint_opts.push((lint_name.replace("-", "_"), level));
1840 let lint_cap = matches.opt_str("cap-lints").map(|cap| {
1841 lint::Level::from_str(&cap)
1842 .unwrap_or_else(|| early_error(error_format, &format!("unknown lint level: `{}`", cap)))
1844 (lint_opts, describe_lints, lint_cap)
1847 pub fn build_session_options_and_crate_config(
1848 matches: &getopts::Matches,
1849 ) -> (Options, ast::CrateConfig) {
1850 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
1851 Some("auto") => ColorConfig::Auto,
1852 Some("always") => ColorConfig::Always,
1853 Some("never") => ColorConfig::Never,
1855 None => ColorConfig::Auto,
1857 Some(arg) => early_error(
1858 ErrorOutputType::default(),
1860 "argument for --color must be auto, \
1861 always or never (instead was `{}`)",
1867 let edition = match matches.opt_str("edition") {
1868 Some(arg) => Edition::from_str(&arg).unwrap_or_else(|_|
1870 ErrorOutputType::default(),
1872 "argument for --edition must be one of: \
1873 {}. (instead was `{}`)",
1879 None => DEFAULT_EDITION,
1882 if !edition.is_stable() && !nightly_options::is_nightly_build() {
1884 ErrorOutputType::default(),
1886 "Edition {} is unstable and only \
1887 available for nightly builds of rustc.",
1894 // We need the opts_present check because the driver will send us Matches
1895 // with only stable options if no unstable options are used. Since error-format
1896 // is unstable, it will not be present. We have to use opts_present not
1897 // opt_present because the latter will panic.
1898 let error_format = if matches.opts_present(&["error-format".to_owned()]) {
1899 match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
1900 Some("human") => ErrorOutputType::HumanReadable(color),
1901 Some("json") => ErrorOutputType::Json(false),
1902 Some("pretty-json") => ErrorOutputType::Json(true),
1903 Some("short") => ErrorOutputType::Short(color),
1904 None => ErrorOutputType::HumanReadable(color),
1906 Some(arg) => early_error(
1907 ErrorOutputType::HumanReadable(color),
1909 "argument for --error-format must be `human`, `json` or \
1910 `short` (instead was `{}`)",
1916 ErrorOutputType::HumanReadable(color)
1919 let unparsed_crate_types = matches.opt_strs("crate-type");
1920 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
1921 .unwrap_or_else(|e| early_error(error_format, &e[..]));
1924 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
1926 let mut debugging_opts = build_debugging_options(matches, error_format);
1928 if !debugging_opts.unstable_options && error_format == ErrorOutputType::Json(true) {
1930 ErrorOutputType::Json(false),
1931 "--error-format=pretty-json is unstable",
1935 if debugging_opts.pgo_gen.is_some() && !debugging_opts.pgo_use.is_empty() {
1938 "options `-Z pgo-gen` and `-Z pgo-use` are exclusive",
1942 let mut output_types = BTreeMap::new();
1943 if !debugging_opts.parse_only {
1944 for list in matches.opt_strs("emit") {
1945 for output_type in list.split(',') {
1946 let mut parts = output_type.splitn(2, '=');
1947 let shorthand = parts.next().unwrap();
1948 let output_type = OutputType::from_shorthand(shorthand).unwrap_or_else(||
1952 "unknown emission type: `{}` - expected one of: {}",
1954 OutputType::shorthands_display(),
1958 let path = parts.next().map(PathBuf::from);
1959 output_types.insert(output_type, path);
1963 if output_types.is_empty() {
1964 output_types.insert(OutputType::Exe, None);
1967 let mut cg = build_codegen_options(matches, error_format);
1968 let mut codegen_units = cg.codegen_units;
1969 let mut disable_thinlto = false;
1971 // Issue #30063: if user requests llvm-related output to one
1972 // particular path, disable codegen-units.
1973 let incompatible: Vec<_> = output_types
1975 .map(|ot_path| ot_path.0)
1976 .filter(|ot| !ot.is_compatible_with_codegen_units_and_single_output_file())
1977 .map(|ot| ot.shorthand())
1979 if !incompatible.is_empty() {
1980 match codegen_units {
1981 Some(n) if n > 1 => {
1982 if matches.opt_present("o") {
1983 for ot in &incompatible {
1987 "--emit={} with -o incompatible with \
1988 -C codegen-units=N for N > 1",
1993 early_warn(error_format, "resetting to default -C codegen-units=1");
1994 codegen_units = Some(1);
1995 disable_thinlto = true;
1999 codegen_units = Some(1);
2000 disable_thinlto = true;
2005 if debugging_opts.threads == Some(0) {
2008 "Value for threads must be a positive nonzero integer",
2012 if debugging_opts.threads.unwrap_or(1) > 1 && debugging_opts.fuel.is_some() {
2015 "Optimization fuel is incompatible with multiple threads",
2019 if codegen_units == Some(0) {
2022 "Value for codegen units must be a positive nonzero integer",
2026 let incremental = match (&debugging_opts.incremental, &cg.incremental) {
2027 (&Some(ref path1), &Some(ref path2)) => {
2032 "conflicting paths for `-Z incremental` and \
2033 `-C incremental` specified: {} versus {}",
2041 (&Some(ref path), &None) => Some(path),
2042 (&None, &Some(ref path)) => Some(path),
2043 (&None, &None) => None,
2044 }.map(|m| PathBuf::from(m));
2046 if debugging_opts.profile && incremental.is_some() {
2049 "can't instrument with gcov profiling when compiling incrementally",
2053 let mut prints = Vec::<PrintRequest>::new();
2054 if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
2055 prints.push(PrintRequest::TargetCPUs);
2056 cg.target_cpu = None;
2058 if cg.target_feature == "help" {
2059 prints.push(PrintRequest::TargetFeatures);
2060 cg.target_feature = String::new();
2062 if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
2063 prints.push(PrintRequest::RelocationModels);
2064 cg.relocation_model = None;
2066 if cg.code_model.as_ref().map_or(false, |s| s == "help") {
2067 prints.push(PrintRequest::CodeModels);
2068 cg.code_model = None;
2073 .map_or(false, |s| s == "help")
2075 prints.push(PrintRequest::TlsModels);
2076 debugging_opts.tls_model = None;
2081 let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
2082 let target_triple = if let Some(target) = matches.opt_str("target") {
2083 if target.ends_with(".json") {
2084 let path = Path::new(&target);
2085 TargetTriple::from_path(&path).unwrap_or_else(|_|
2086 early_error(error_format, &format!("target file {:?} does not exist", path)))
2088 TargetTriple::TargetTriple(target)
2091 TargetTriple::from_triple(host_triple())
2094 if matches.opt_present("O") {
2095 if cg.opt_level.is_some() {
2096 early_error(error_format, "-O and -C opt-level both provided");
2100 match cg.opt_level.as_ref().map(String::as_ref) {
2101 None => OptLevel::No,
2102 Some("0") => OptLevel::No,
2103 Some("1") => OptLevel::Less,
2104 Some("2") => OptLevel::Default,
2105 Some("3") => OptLevel::Aggressive,
2106 Some("s") => OptLevel::Size,
2107 Some("z") => OptLevel::SizeMin,
2112 "optimization level needs to be \
2113 between 0-3, s or z (instead was `{}`)",
2121 let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
2122 let debuginfo = if matches.opt_present("g") {
2123 if cg.debuginfo.is_some() {
2124 early_error(error_format, "-g and -C debuginfo both provided");
2128 match cg.debuginfo {
2129 None | Some(0) => DebugInfo::None,
2130 Some(1) => DebugInfo::Limited,
2131 Some(2) => DebugInfo::Full,
2136 "debug info level needs to be between \
2137 0-2 (instead was `{}`)",
2145 let mut search_paths = vec![];
2146 for s in &matches.opt_strs("L") {
2147 search_paths.push(SearchPath::from_cli_opt(&s[..], error_format));
2154 // Parse string of the form "[KIND=]lib[:new_name]",
2155 // where KIND is one of "dylib", "framework", "static".
2156 let mut parts = s.splitn(2, '=');
2157 let kind = parts.next().unwrap();
2158 let (name, kind) = match (parts.next(), kind) {
2159 (None, name) => (name, None),
2160 (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
2161 (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
2162 (Some(name), "static") => (name, Some(cstore::NativeStatic)),
2163 (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
2168 "unknown library kind `{}`, expected \
2169 one of dylib, framework, or static",
2175 if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
2179 "the library kind 'static-nobundle' is only \
2180 accepted on the nightly compiler"
2184 let mut name_parts = name.splitn(2, ':');
2185 let name = name_parts.next().unwrap();
2186 let new_name = name_parts.next();
2187 (name.to_owned(), new_name.map(|n| n.to_owned()), kind)
2191 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
2192 let test = matches.opt_present("test");
2194 let is_unstable_enabled = nightly_options::is_unstable_enabled(matches);
2196 prints.extend(matches.opt_strs("print").into_iter().map(|s| match &*s {
2197 "crate-name" => PrintRequest::CrateName,
2198 "file-names" => PrintRequest::FileNames,
2199 "sysroot" => PrintRequest::Sysroot,
2200 "cfg" => PrintRequest::Cfg,
2201 "target-list" => PrintRequest::TargetList,
2202 "target-cpus" => PrintRequest::TargetCPUs,
2203 "target-features" => PrintRequest::TargetFeatures,
2204 "relocation-models" => PrintRequest::RelocationModels,
2205 "code-models" => PrintRequest::CodeModels,
2206 "tls-models" => PrintRequest::TlsModels,
2207 "native-static-libs" => PrintRequest::NativeStaticLibs,
2208 "target-spec-json" => {
2209 if is_unstable_enabled {
2210 PrintRequest::TargetSpec
2214 "the `-Z unstable-options` flag must also be passed to \
2215 enable the target-spec-json print option",
2219 req => early_error(error_format, &format!("unknown print request `{}`", req)),
2222 let borrowck_mode = match debugging_opts.borrowck.as_ref().map(|s| &s[..]) {
2223 None | Some("ast") => BorrowckMode::Ast,
2224 Some("mir") => BorrowckMode::Mir,
2225 Some("compare") => BorrowckMode::Compare,
2226 Some("migrate") => BorrowckMode::Migrate,
2227 Some(m) => early_error(error_format, &format!("unknown borrowck mode `{}`", m)),
2230 if !cg.remark.is_empty() && debuginfo == DebugInfo::None {
2233 "-C remark requires \"-C debuginfo=n\" to show source locations",
2237 if matches.opt_present("extern-private") && !debugging_opts.unstable_options {
2239 ErrorOutputType::default(),
2240 "'--extern-private' is unstable and only \
2241 available for nightly builds of rustc."
2245 let extern_private = matches.opt_strs("extern-private");
2247 let mut externs: BTreeMap<_, BTreeSet<_>> = BTreeMap::new();
2248 for arg in matches.opt_strs("extern").into_iter().chain(matches.opt_strs("extern-private")) {
2249 let mut parts = arg.splitn(2, '=');
2250 let name = parts.next().unwrap_or_else(||
2251 early_error(error_format, "--extern value must not be empty"));
2252 let location = parts.next().map(|s| s.to_string());
2253 if location.is_none() && !is_unstable_enabled {
2256 "the `-Z unstable-options` flag must also be passed to \
2257 enable `--extern crate_name` without `=path`",
2262 .entry(name.to_owned())
2267 let crate_name = matches.opt_str("crate-name");
2269 let remap_path_prefix = matches
2270 .opt_strs("remap-path-prefix")
2273 let mut parts = remap.rsplitn(2, '='); // reverse iterator
2274 let to = parts.next();
2275 let from = parts.next();
2277 (Some(from), Some(to)) => (PathBuf::from(from), PathBuf::from(to)),
2280 "--remap-path-prefix must contain '=' between FROM and TO",
2289 optimize: opt_level,
2294 output_types: OutputTypes(output_types),
2296 maybe_sysroot: sysroot_opt,
2305 externs: Externs(externs),
2309 unstable_features: UnstableFeatures::from_environment(),
2311 actually_rustdoc: false,
2312 cli_forced_codegen_units: codegen_units,
2313 cli_forced_thinlto_off: disable_thinlto,
2322 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
2323 let mut crate_types: Vec<CrateType> = Vec::new();
2324 for unparsed_crate_type in &list_list {
2325 for part in unparsed_crate_type.split(',') {
2326 let new_part = match part {
2327 "lib" => default_lib_output(),
2328 "rlib" => CrateType::Rlib,
2329 "staticlib" => CrateType::Staticlib,
2330 "dylib" => CrateType::Dylib,
2331 "cdylib" => CrateType::Cdylib,
2332 "bin" => CrateType::Executable,
2333 "proc-macro" => CrateType::ProcMacro,
2334 _ => return Err(format!("unknown crate type: `{}`", part))
2336 if !crate_types.contains(&new_part) {
2337 crate_types.push(new_part)
2345 pub mod nightly_options {
2347 use syntax::feature_gate::UnstableFeatures;
2348 use super::{ErrorOutputType, OptionStability, RustcOptGroup};
2349 use crate::session::early_error;
2351 pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
2356 .any(|x| *x == "unstable-options")
2359 pub fn is_nightly_build() -> bool {
2360 UnstableFeatures::from_environment().is_nightly_build()
2363 pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
2364 let has_z_unstable_option = matches
2367 .any(|x| *x == "unstable-options");
2368 let really_allows_unstable_options =
2369 UnstableFeatures::from_environment().is_nightly_build();
2371 for opt in flags.iter() {
2372 if opt.stability == OptionStability::Stable {
2375 if !matches.opt_present(opt.name) {
2378 if opt.name != "Z" && !has_z_unstable_option {
2380 ErrorOutputType::default(),
2382 "the `-Z unstable-options` flag must also be passed to enable \
2388 if really_allows_unstable_options {
2391 match opt.stability {
2392 OptionStability::Unstable => {
2394 "the option `{}` is only accepted on the \
2398 early_error(ErrorOutputType::default(), &msg);
2400 OptionStability::Stable => {}
2406 impl fmt::Display for CrateType {
2407 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2409 CrateType::Executable => "bin".fmt(f),
2410 CrateType::Dylib => "dylib".fmt(f),
2411 CrateType::Rlib => "rlib".fmt(f),
2412 CrateType::Staticlib => "staticlib".fmt(f),
2413 CrateType::Cdylib => "cdylib".fmt(f),
2414 CrateType::ProcMacro => "proc-macro".fmt(f),
2419 /// Command-line arguments passed to the compiler have to be incorporated with
2420 /// the dependency tracking system for incremental compilation. This module
2421 /// provides some utilities to make this more convenient.
2423 /// The values of all command-line arguments that are relevant for dependency
2424 /// tracking are hashed into a single value that determines whether the
2425 /// incremental compilation cache can be re-used or not. This hashing is done
2426 /// via the DepTrackingHash trait defined below, since the standard Hash
2427 /// implementation might not be suitable (e.g., arguments are stored in a Vec,
2428 /// the hash of which is order dependent, but we might not want the order of
2429 /// arguments to make a difference for the hash).
2431 /// However, since the value provided by Hash::hash often *is* suitable,
2432 /// especially for primitive types, there is the
2433 /// impl_dep_tracking_hash_via_hash!() macro that allows to simply reuse the
2434 /// Hash implementation for DepTrackingHash. It's important though that
2435 /// we have an opt-in scheme here, so one is hopefully forced to think about
2436 /// how the hash should be calculated when adding a new command-line argument.
2439 use crate::middle::cstore;
2440 use std::collections::BTreeMap;
2441 use std::hash::Hash;
2442 use std::path::PathBuf;
2443 use std::collections::hash_map::DefaultHasher;
2444 use super::{CrateType, DebugInfo, ErrorOutputType, OptLevel, OutputTypes,
2445 Passes, Sanitizer, LtoCli, LinkerPluginLto};
2446 use syntax::feature_gate::UnstableFeatures;
2447 use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel, TargetTriple};
2448 use syntax::edition::Edition;
2450 pub trait DepTrackingHash {
2451 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);
2454 macro_rules! impl_dep_tracking_hash_via_hash {
2456 impl DepTrackingHash for $t {
2457 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
2458 Hash::hash(self, hasher);
2464 macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
2466 impl DepTrackingHash for Vec<$t> {
2467 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2468 let mut elems: Vec<&$t> = self.iter().collect();
2470 Hash::hash(&elems.len(), hasher);
2471 for (index, elem) in elems.iter().enumerate() {
2472 Hash::hash(&index, hasher);
2473 DepTrackingHash::hash(*elem, hasher, error_format);
2480 impl_dep_tracking_hash_via_hash!(bool);
2481 impl_dep_tracking_hash_via_hash!(usize);
2482 impl_dep_tracking_hash_via_hash!(u64);
2483 impl_dep_tracking_hash_via_hash!(String);
2484 impl_dep_tracking_hash_via_hash!(PathBuf);
2485 impl_dep_tracking_hash_via_hash!(lint::Level);
2486 impl_dep_tracking_hash_via_hash!(Option<bool>);
2487 impl_dep_tracking_hash_via_hash!(Option<usize>);
2488 impl_dep_tracking_hash_via_hash!(Option<String>);
2489 impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
2490 impl_dep_tracking_hash_via_hash!(Option<Vec<String>>);
2491 impl_dep_tracking_hash_via_hash!(Option<MergeFunctions>);
2492 impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
2493 impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
2494 impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
2495 impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
2496 impl_dep_tracking_hash_via_hash!(Option<cstore::NativeLibraryKind>);
2497 impl_dep_tracking_hash_via_hash!(CrateType);
2498 impl_dep_tracking_hash_via_hash!(MergeFunctions);
2499 impl_dep_tracking_hash_via_hash!(PanicStrategy);
2500 impl_dep_tracking_hash_via_hash!(RelroLevel);
2501 impl_dep_tracking_hash_via_hash!(Passes);
2502 impl_dep_tracking_hash_via_hash!(OptLevel);
2503 impl_dep_tracking_hash_via_hash!(LtoCli);
2504 impl_dep_tracking_hash_via_hash!(DebugInfo);
2505 impl_dep_tracking_hash_via_hash!(UnstableFeatures);
2506 impl_dep_tracking_hash_via_hash!(OutputTypes);
2507 impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
2508 impl_dep_tracking_hash_via_hash!(Sanitizer);
2509 impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
2510 impl_dep_tracking_hash_via_hash!(TargetTriple);
2511 impl_dep_tracking_hash_via_hash!(Edition);
2512 impl_dep_tracking_hash_via_hash!(LinkerPluginLto);
2514 impl_dep_tracking_hash_for_sortable_vec_of!(String);
2515 impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
2516 impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
2517 impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
2518 impl_dep_tracking_hash_for_sortable_vec_of!((
2521 Option<cstore::NativeLibraryKind>
2523 impl_dep_tracking_hash_for_sortable_vec_of!((String, u64));
2525 impl<T1, T2> DepTrackingHash for (T1, T2)
2527 T1: DepTrackingHash,
2528 T2: DepTrackingHash,
2530 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2531 Hash::hash(&0, hasher);
2532 DepTrackingHash::hash(&self.0, hasher, error_format);
2533 Hash::hash(&1, hasher);
2534 DepTrackingHash::hash(&self.1, hasher, error_format);
2538 impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
2540 T1: DepTrackingHash,
2541 T2: DepTrackingHash,
2542 T3: DepTrackingHash,
2544 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2545 Hash::hash(&0, hasher);
2546 DepTrackingHash::hash(&self.0, hasher, error_format);
2547 Hash::hash(&1, hasher);
2548 DepTrackingHash::hash(&self.1, hasher, error_format);
2549 Hash::hash(&2, hasher);
2550 DepTrackingHash::hash(&self.2, hasher, error_format);
2554 // This is a stable hash because BTreeMap is a sorted container
2556 sub_hashes: BTreeMap<&'static str, &dyn DepTrackingHash>,
2557 hasher: &mut DefaultHasher,
2558 error_format: ErrorOutputType,
2560 for (key, sub_hash) in sub_hashes {
2561 // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
2562 // the keys, as they are just plain strings
2563 Hash::hash(&key.len(), hasher);
2564 Hash::hash(key, hasher);
2565 sub_hash.hash(hasher, error_format);
2574 use crate::middle::cstore;
2575 use crate::session::config::{build_configuration, build_session_options_and_crate_config};
2576 use crate::session::config::{LtoCli, LinkerPluginLto};
2577 use crate::session::build_session;
2578 use crate::session::search_paths::SearchPath;
2579 use std::collections::{BTreeMap, BTreeSet};
2580 use std::iter::FromIterator;
2581 use std::path::PathBuf;
2582 use super::{Externs, OutputType, OutputTypes};
2583 use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel};
2584 use syntax::symbol::Symbol;
2585 use syntax::edition::{Edition, DEFAULT_EDITION};
2589 fn optgroups() -> getopts::Options {
2590 let mut opts = getopts::Options::new();
2591 for group in super::rustc_optgroups() {
2592 (group.apply)(&mut opts);
2597 fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
2598 BTreeMap::from_iter(entries.into_iter())
2601 fn mk_set<V: Ord>(entries: Vec<V>) -> BTreeSet<V> {
2602 BTreeSet::from_iter(entries.into_iter())
2605 // When the user supplies --test we should implicitly supply --cfg test
2607 fn test_switch_implies_cfg_test() {
2608 syntax::with_globals(|| {
2609 let matches = &match optgroups().parse(&["--test".to_string()]) {
2611 Err(f) => panic!("test_switch_implies_cfg_test: {}", f),
2613 let registry = errors::registry::Registry::new(&[]);
2614 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2615 let sess = build_session(sessopts, None, registry);
2616 let cfg = build_configuration(&sess, cfg);
2617 assert!(cfg.contains(&(Symbol::intern("test"), None)));
2621 // When the user supplies --test and --cfg test, don't implicitly add
2622 // another --cfg test
2624 fn test_switch_implies_cfg_test_unless_cfg_test() {
2625 syntax::with_globals(|| {
2626 let matches = &match optgroups().parse(&["--test".to_string(),
2627 "--cfg=test".to_string()]) {
2629 Err(f) => panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f),
2631 let registry = errors::registry::Registry::new(&[]);
2632 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2633 let sess = build_session(sessopts, None, registry);
2634 let cfg = build_configuration(&sess, cfg);
2635 let mut test_items = cfg.iter().filter(|&&(name, _)| name == "test");
2636 assert!(test_items.next().is_some());
2637 assert!(test_items.next().is_none());
2642 fn test_can_print_warnings() {
2643 syntax::with_globals(|| {
2644 let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
2645 let registry = errors::registry::Registry::new(&[]);
2646 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2647 let sess = build_session(sessopts, None, registry);
2648 assert!(!sess.diagnostic().flags.can_emit_warnings);
2651 syntax::with_globals(|| {
2652 let matches = optgroups()
2653 .parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()])
2655 let registry = errors::registry::Registry::new(&[]);
2656 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2657 let sess = build_session(sessopts, None, registry);
2658 assert!(sess.diagnostic().flags.can_emit_warnings);
2661 syntax::with_globals(|| {
2662 let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
2663 let registry = errors::registry::Registry::new(&[]);
2664 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2665 let sess = build_session(sessopts, None, registry);
2666 assert!(sess.diagnostic().flags.can_emit_warnings);
2671 fn test_output_types_tracking_hash_different_paths() {
2672 let mut v1 = Options::default();
2673 let mut v2 = Options::default();
2674 let mut v3 = Options::default();
2677 OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("./some/thing")))]);
2679 OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("/some/thing")))]);
2680 v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
2682 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2683 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2684 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2687 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2688 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2689 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2693 fn test_output_types_tracking_hash_different_construction_order() {
2694 let mut v1 = Options::default();
2695 let mut v2 = Options::default();
2697 v1.output_types = OutputTypes::new(&[
2698 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2699 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2702 v2.output_types = OutputTypes::new(&[
2703 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2704 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2707 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2710 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2714 fn test_externs_tracking_hash_different_construction_order() {
2715 let mut v1 = Options::default();
2716 let mut v2 = Options::default();
2717 let mut v3 = Options::default();
2719 v1.externs = Externs::new(mk_map(vec![
2722 mk_set(vec![Some(String::from("b")), Some(String::from("c"))]),
2726 mk_set(vec![Some(String::from("e")), Some(String::from("f"))]),
2730 v2.externs = Externs::new(mk_map(vec![
2733 mk_set(vec![Some(String::from("e")), Some(String::from("f"))]),
2737 mk_set(vec![Some(String::from("b")), Some(String::from("c"))]),
2741 v3.externs = Externs::new(mk_map(vec![
2744 mk_set(vec![Some(String::from("b")), Some(String::from("c"))]),
2748 mk_set(vec![Some(String::from("f")), Some(String::from("e"))]),
2752 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2753 assert_eq!(v1.dep_tracking_hash(), v3.dep_tracking_hash());
2754 assert_eq!(v2.dep_tracking_hash(), v3.dep_tracking_hash());
2757 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2758 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2759 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2763 fn test_lints_tracking_hash_different_values() {
2764 let mut v1 = Options::default();
2765 let mut v2 = Options::default();
2766 let mut v3 = Options::default();
2768 v1.lint_opts = vec![
2769 (String::from("a"), lint::Allow),
2770 (String::from("b"), lint::Warn),
2771 (String::from("c"), lint::Deny),
2772 (String::from("d"), lint::Forbid),
2775 v2.lint_opts = vec![
2776 (String::from("a"), lint::Allow),
2777 (String::from("b"), lint::Warn),
2778 (String::from("X"), lint::Deny),
2779 (String::from("d"), lint::Forbid),
2782 v3.lint_opts = vec![
2783 (String::from("a"), lint::Allow),
2784 (String::from("b"), lint::Warn),
2785 (String::from("c"), lint::Forbid),
2786 (String::from("d"), lint::Deny),
2789 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2790 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2791 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2794 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2795 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2796 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2800 fn test_lints_tracking_hash_different_construction_order() {
2801 let mut v1 = Options::default();
2802 let mut v2 = Options::default();
2804 v1.lint_opts = vec![
2805 (String::from("a"), lint::Allow),
2806 (String::from("b"), lint::Warn),
2807 (String::from("c"), lint::Deny),
2808 (String::from("d"), lint::Forbid),
2811 v2.lint_opts = vec![
2812 (String::from("a"), lint::Allow),
2813 (String::from("c"), lint::Deny),
2814 (String::from("b"), lint::Warn),
2815 (String::from("d"), lint::Forbid),
2818 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2821 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2822 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2826 fn test_search_paths_tracking_hash_different_order() {
2827 let mut v1 = Options::default();
2828 let mut v2 = Options::default();
2829 let mut v3 = Options::default();
2830 let mut v4 = Options::default();
2834 .push(SearchPath::from_cli_opt("native=abc", super::ErrorOutputType::Json(false)));
2836 .push(SearchPath::from_cli_opt("crate=def", super::ErrorOutputType::Json(false)));
2838 .push(SearchPath::from_cli_opt("dependency=ghi", super::ErrorOutputType::Json(false)));
2840 .push(SearchPath::from_cli_opt("framework=jkl", super::ErrorOutputType::Json(false)));
2842 .push(SearchPath::from_cli_opt("all=mno", super::ErrorOutputType::Json(false)));
2845 .push(SearchPath::from_cli_opt("native=abc", super::ErrorOutputType::Json(false)));
2847 .push(SearchPath::from_cli_opt("dependency=ghi", super::ErrorOutputType::Json(false)));
2849 .push(SearchPath::from_cli_opt("crate=def", super::ErrorOutputType::Json(false)));
2851 .push(SearchPath::from_cli_opt("framework=jkl", super::ErrorOutputType::Json(false)));
2853 .push(SearchPath::from_cli_opt("all=mno", super::ErrorOutputType::Json(false)));
2856 .push(SearchPath::from_cli_opt("crate=def", super::ErrorOutputType::Json(false)));
2858 .push(SearchPath::from_cli_opt("framework=jkl", super::ErrorOutputType::Json(false)));
2860 .push(SearchPath::from_cli_opt("native=abc", super::ErrorOutputType::Json(false)));
2862 .push(SearchPath::from_cli_opt("dependency=ghi", super::ErrorOutputType::Json(false)));
2864 .push(SearchPath::from_cli_opt("all=mno", super::ErrorOutputType::Json(false)));
2867 .push(SearchPath::from_cli_opt("all=mno", super::ErrorOutputType::Json(false)));
2869 .push(SearchPath::from_cli_opt("native=abc", super::ErrorOutputType::Json(false)));
2871 .push(SearchPath::from_cli_opt("crate=def", super::ErrorOutputType::Json(false)));
2873 .push(SearchPath::from_cli_opt("dependency=ghi", super::ErrorOutputType::Json(false)));
2875 .push(SearchPath::from_cli_opt("framework=jkl", super::ErrorOutputType::Json(false)));
2877 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2878 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2879 assert!(v1.dep_tracking_hash() == v4.dep_tracking_hash());
2882 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2883 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2884 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2885 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2889 fn test_native_libs_tracking_hash_different_values() {
2890 let mut v1 = Options::default();
2891 let mut v2 = Options::default();
2892 let mut v3 = Options::default();
2893 let mut v4 = Options::default();
2897 (String::from("a"), None, Some(cstore::NativeStatic)),
2898 (String::from("b"), None, Some(cstore::NativeFramework)),
2899 (String::from("c"), None, Some(cstore::NativeUnknown)),
2904 (String::from("a"), None, Some(cstore::NativeStatic)),
2905 (String::from("X"), None, Some(cstore::NativeFramework)),
2906 (String::from("c"), None, Some(cstore::NativeUnknown)),
2911 (String::from("a"), None, Some(cstore::NativeStatic)),
2912 (String::from("b"), None, Some(cstore::NativeStatic)),
2913 (String::from("c"), None, Some(cstore::NativeUnknown)),
2918 (String::from("a"), None, Some(cstore::NativeStatic)),
2921 Some(String::from("X")),
2922 Some(cstore::NativeFramework),
2924 (String::from("c"), None, Some(cstore::NativeUnknown)),
2927 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2928 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2929 assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
2932 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2933 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2934 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2935 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2939 fn test_native_libs_tracking_hash_different_order() {
2940 let mut v1 = Options::default();
2941 let mut v2 = Options::default();
2942 let mut v3 = Options::default();
2946 (String::from("a"), None, Some(cstore::NativeStatic)),
2947 (String::from("b"), None, Some(cstore::NativeFramework)),
2948 (String::from("c"), None, Some(cstore::NativeUnknown)),
2952 (String::from("b"), None, Some(cstore::NativeFramework)),
2953 (String::from("a"), None, Some(cstore::NativeStatic)),
2954 (String::from("c"), None, Some(cstore::NativeUnknown)),
2958 (String::from("c"), None, Some(cstore::NativeUnknown)),
2959 (String::from("a"), None, Some(cstore::NativeStatic)),
2960 (String::from("b"), None, Some(cstore::NativeFramework)),
2963 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2964 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2965 assert!(v2.dep_tracking_hash() == v3.dep_tracking_hash());
2968 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2969 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2970 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2974 fn test_codegen_options_tracking_hash() {
2975 let reference = Options::default();
2976 let mut opts = Options::default();
2978 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2979 opts.cg.ar = Some(String::from("abc"));
2980 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2982 opts.cg.linker = Some(PathBuf::from("linker"));
2983 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2985 opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
2986 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2988 opts.cg.link_dead_code = true;
2989 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2991 opts.cg.rpath = true;
2992 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2994 opts.cg.extra_filename = String::from("extra-filename");
2995 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2997 opts.cg.codegen_units = Some(42);
2998 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3000 opts.cg.remark = super::Passes::Some(vec![String::from("pass1"), String::from("pass2")]);
3001 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3003 opts.cg.save_temps = true;
3004 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3006 opts.cg.incremental = Some(String::from("abc"));
3007 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3009 // Make sure changing a [TRACKED] option changes the hash
3010 opts = reference.clone();
3011 opts.cg.lto = LtoCli::Fat;
3012 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3014 opts = reference.clone();
3015 opts.cg.target_cpu = Some(String::from("abc"));
3016 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3018 opts = reference.clone();
3019 opts.cg.target_feature = String::from("all the features, all of them");
3020 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3022 opts = reference.clone();
3023 opts.cg.passes = vec![String::from("1"), String::from("2")];
3024 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3026 opts = reference.clone();
3027 opts.cg.llvm_args = vec![String::from("1"), String::from("2")];
3028 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3030 opts = reference.clone();
3031 opts.cg.overflow_checks = Some(true);
3032 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3034 opts = reference.clone();
3035 opts.cg.no_prepopulate_passes = true;
3036 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3038 opts = reference.clone();
3039 opts.cg.no_vectorize_loops = true;
3040 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3042 opts = reference.clone();
3043 opts.cg.no_vectorize_slp = true;
3044 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3046 opts = reference.clone();
3047 opts.cg.soft_float = true;
3048 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3050 opts = reference.clone();
3051 opts.cg.prefer_dynamic = true;
3052 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3054 opts = reference.clone();
3055 opts.cg.no_integrated_as = true;
3056 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3058 opts = reference.clone();
3059 opts.cg.no_redzone = Some(true);
3060 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3062 opts = reference.clone();
3063 opts.cg.relocation_model = Some(String::from("relocation model"));
3064 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3066 opts = reference.clone();
3067 opts.cg.code_model = Some(String::from("code model"));
3068 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3070 opts = reference.clone();
3071 opts.debugging_opts.tls_model = Some(String::from("tls model"));
3072 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3074 opts = reference.clone();
3075 opts.debugging_opts.pgo_gen = Some(String::from("abc"));
3076 assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3078 opts = reference.clone();
3079 opts.debugging_opts.pgo_use = String::from("abc");
3080 assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3082 opts = reference.clone();
3083 opts.cg.metadata = vec![String::from("A"), String::from("B")];
3084 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3086 opts = reference.clone();
3087 opts.cg.debuginfo = Some(0xdeadbeef);
3088 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3090 opts = reference.clone();
3091 opts.cg.debuginfo = Some(0xba5eba11);
3092 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3094 opts = reference.clone();
3095 opts.cg.force_frame_pointers = Some(false);
3096 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3098 opts = reference.clone();
3099 opts.cg.debug_assertions = Some(true);
3100 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3102 opts = reference.clone();
3103 opts.cg.inline_threshold = Some(0xf007ba11);
3104 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3106 opts = reference.clone();
3107 opts.cg.panic = Some(PanicStrategy::Abort);
3108 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3110 opts = reference.clone();
3111 opts.cg.linker_plugin_lto = LinkerPluginLto::LinkerPluginAuto;
3112 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3116 fn test_debugging_options_tracking_hash() {
3117 let reference = Options::default();
3118 let mut opts = Options::default();
3120 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
3121 opts.debugging_opts.verbose = true;
3122 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3123 opts.debugging_opts.time_passes = true;
3124 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3125 opts.debugging_opts.count_llvm_insns = true;
3126 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3127 opts.debugging_opts.time_llvm_passes = true;
3128 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3129 opts.debugging_opts.input_stats = true;
3130 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3131 opts.debugging_opts.codegen_stats = true;
3132 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3133 opts.debugging_opts.borrowck_stats = true;
3134 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3135 opts.debugging_opts.meta_stats = true;
3136 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3137 opts.debugging_opts.print_link_args = true;
3138 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3139 opts.debugging_opts.print_llvm_passes = true;
3140 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3141 opts.debugging_opts.ast_json = true;
3142 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3143 opts.debugging_opts.ast_json_noexpand = true;
3144 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3145 opts.debugging_opts.ls = true;
3146 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3147 opts.debugging_opts.save_analysis = true;
3148 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3149 opts.debugging_opts.flowgraph_print_loans = true;
3150 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3151 opts.debugging_opts.flowgraph_print_moves = true;
3152 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3153 opts.debugging_opts.flowgraph_print_assigns = true;
3154 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3155 opts.debugging_opts.flowgraph_print_all = true;
3156 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3157 opts.debugging_opts.print_region_graph = true;
3158 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3159 opts.debugging_opts.parse_only = true;
3160 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3161 opts.debugging_opts.incremental = Some(String::from("abc"));
3162 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3163 opts.debugging_opts.dump_dep_graph = true;
3164 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3165 opts.debugging_opts.query_dep_graph = true;
3166 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3167 opts.debugging_opts.no_analysis = true;
3168 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3169 opts.debugging_opts.unstable_options = true;
3170 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3171 opts.debugging_opts.trace_macros = true;
3172 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3173 opts.debugging_opts.keep_hygiene_data = true;
3174 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3175 opts.debugging_opts.keep_ast = true;
3176 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3177 opts.debugging_opts.print_mono_items = Some(String::from("abc"));
3178 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3179 opts.debugging_opts.dump_mir = Some(String::from("abc"));
3180 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3181 opts.debugging_opts.dump_mir_dir = String::from("abc");
3182 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3183 opts.debugging_opts.dump_mir_graphviz = true;
3184 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3186 // Make sure changing a [TRACKED] option changes the hash
3187 opts = reference.clone();
3188 opts.debugging_opts.asm_comments = true;
3189 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3191 opts = reference.clone();
3192 opts.debugging_opts.verify_llvm_ir = true;
3193 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3195 opts = reference.clone();
3196 opts.debugging_opts.no_landing_pads = true;
3197 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3199 opts = reference.clone();
3200 opts.debugging_opts.fewer_names = true;
3201 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3203 opts = reference.clone();
3204 opts.debugging_opts.no_codegen = true;
3205 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3207 opts = reference.clone();
3208 opts.debugging_opts.treat_err_as_bug = true;
3209 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3211 opts = reference.clone();
3212 opts.debugging_opts.report_delayed_bugs = true;
3213 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3215 opts = reference.clone();
3216 opts.debugging_opts.continue_parse_after_error = true;
3217 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3219 opts = reference.clone();
3220 opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
3221 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3223 opts = reference.clone();
3224 opts.debugging_opts.force_overflow_checks = Some(true);
3225 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3227 opts = reference.clone();
3228 opts.debugging_opts.show_span = Some(String::from("abc"));
3229 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3231 opts = reference.clone();
3232 opts.debugging_opts.mir_opt_level = 3;
3233 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3235 opts = reference.clone();
3236 opts.debugging_opts.relro_level = Some(RelroLevel::Full);
3237 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3239 opts = reference.clone();
3240 opts.debugging_opts.merge_functions = Some(MergeFunctions::Disabled);
3241 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3245 fn test_edition_parsing() {
3246 // test default edition
3247 let options = Options::default();
3248 assert!(options.edition == DEFAULT_EDITION);
3250 let matches = optgroups()
3251 .parse(&["--edition=2018".to_string()])
3253 let (sessopts, _) = build_session_options_and_crate_config(&matches);
3254 assert!(sessopts.edition == Edition::Edition2018)