1 // ignore-tidy-filelength
3 //! Contains infrastructure for configuring the compiler, including parsing
4 //! command line options.
8 use crate::session::{early_error, early_warn, Session};
9 use crate::session::search_paths::SearchPath;
11 use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
12 use rustc_target::spec::{Target, TargetTriple};
14 use crate::middle::cstore;
17 use syntax::ast::{self, IntTy, UintTy, MetaItemKind};
18 use syntax::source_map::{FileName, FilePathMapping};
19 use syntax::edition::{Edition, EDITION_NAME_LIST, DEFAULT_EDITION};
20 use syntax::parse::token;
22 use syntax::symbol::{sym, Symbol};
23 use syntax::feature_gate::UnstableFeatures;
24 use errors::emitter::HumanReadableErrorType;
26 use errors::{ColorConfig, FatalError, Handler};
29 use std::collections::{BTreeMap, BTreeSet};
30 use std::collections::btree_map::Iter as BTreeMapIter;
31 use std::collections::btree_map::Keys as BTreeMapKeysIter;
32 use std::collections::btree_map::Values as BTreeMapValuesIter;
34 use rustc_data_structures::fx::FxHashSet;
36 use std::hash::Hasher;
37 use std::collections::hash_map::DefaultHasher;
38 use std::iter::FromIterator;
39 use std::path::{Path, PathBuf};
47 #[derive(Clone, Hash, Debug)]
55 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
65 impl_stable_hash_via_hash!(OptLevel);
67 /// This is what the `LtoCli` values get mapped to after resolving defaults and
68 /// and taking other command line options into account.
69 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
71 /// Don't do any LTO whatsoever
74 /// Do a full crate graph LTO with ThinLTO
77 /// Do a local graph LTO with ThinLTO (only relevant for multiple codegen
81 /// Do a full crate graph LTO with "fat" LTO
85 /// The different settings that the `-C lto` flag can have.
86 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
98 /// No `-C lto` flag passed
102 #[derive(Clone, PartialEq, Hash)]
103 pub enum LinkerPluginLto {
104 LinkerPlugin(PathBuf),
109 impl LinkerPluginLto {
110 pub fn enabled(&self) -> bool {
112 LinkerPluginLto::LinkerPlugin(_) |
113 LinkerPluginLto::LinkerPluginAuto => true,
114 LinkerPluginLto::Disabled => false,
119 #[derive(Clone, PartialEq, Hash)]
120 pub enum SwitchWithOptPath {
121 Enabled(Option<PathBuf>),
125 impl SwitchWithOptPath {
126 pub fn enabled(&self) -> bool {
128 SwitchWithOptPath::Enabled(_) => true,
129 SwitchWithOptPath::Disabled => false,
134 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
135 pub enum SymbolManglingVersion {
140 impl_stable_hash_via_hash!(SymbolManglingVersion);
142 #[derive(Clone, Copy, PartialEq, Hash)]
149 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
150 pub enum OutputType {
161 impl_stable_hash_via_hash!(OutputType);
164 fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
166 OutputType::Exe | OutputType::DepInfo | OutputType::Metadata => true,
168 | OutputType::Assembly
169 | OutputType::LlvmAssembly
171 | OutputType::Object => false,
175 fn shorthand(&self) -> &'static str {
177 OutputType::Bitcode => "llvm-bc",
178 OutputType::Assembly => "asm",
179 OutputType::LlvmAssembly => "llvm-ir",
180 OutputType::Mir => "mir",
181 OutputType::Object => "obj",
182 OutputType::Metadata => "metadata",
183 OutputType::Exe => "link",
184 OutputType::DepInfo => "dep-info",
188 fn from_shorthand(shorthand: &str) -> Option<Self> {
189 Some(match shorthand {
190 "asm" => OutputType::Assembly,
191 "llvm-ir" => OutputType::LlvmAssembly,
192 "mir" => OutputType::Mir,
193 "llvm-bc" => OutputType::Bitcode,
194 "obj" => OutputType::Object,
195 "metadata" => OutputType::Metadata,
196 "link" => OutputType::Exe,
197 "dep-info" => OutputType::DepInfo,
202 fn shorthands_display() -> String {
204 "`{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`",
205 OutputType::Bitcode.shorthand(),
206 OutputType::Assembly.shorthand(),
207 OutputType::LlvmAssembly.shorthand(),
208 OutputType::Mir.shorthand(),
209 OutputType::Object.shorthand(),
210 OutputType::Metadata.shorthand(),
211 OutputType::Exe.shorthand(),
212 OutputType::DepInfo.shorthand(),
216 pub fn extension(&self) -> &'static str {
218 OutputType::Bitcode => "bc",
219 OutputType::Assembly => "s",
220 OutputType::LlvmAssembly => "ll",
221 OutputType::Mir => "mir",
222 OutputType::Object => "o",
223 OutputType::Metadata => "rmeta",
224 OutputType::DepInfo => "d",
225 OutputType::Exe => "",
230 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
231 pub enum ErrorOutputType {
232 HumanReadable(HumanReadableErrorType),
234 /// Render the json in a human readable way (with indents and newlines)
236 /// The way the `rendered` field is created
237 json_rendered: HumanReadableErrorType,
241 impl Default for ErrorOutputType {
242 fn default() -> ErrorOutputType {
243 ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(ColorConfig::Auto))
247 // Use tree-based collections to cheaply get a deterministic Hash implementation.
248 // DO NOT switch BTreeMap out for an unsorted container type! That would break
249 // dependency tracking for command-line arguments.
250 #[derive(Clone, Hash)]
251 pub struct OutputTypes(BTreeMap<OutputType, Option<PathBuf>>);
253 impl_stable_hash_via_hash!(OutputTypes);
256 pub fn new(entries: &[(OutputType, Option<PathBuf>)]) -> OutputTypes {
257 OutputTypes(BTreeMap::from_iter(
258 entries.iter().map(|&(k, ref v)| (k, v.clone())),
262 pub fn get(&self, key: &OutputType) -> Option<&Option<PathBuf>> {
266 pub fn contains_key(&self, key: &OutputType) -> bool {
267 self.0.contains_key(key)
270 pub fn keys<'a>(&'a self) -> BTreeMapKeysIter<'a, OutputType, Option<PathBuf>> {
274 pub fn values<'a>(&'a self) -> BTreeMapValuesIter<'a, OutputType, Option<PathBuf>> {
278 pub fn len(&self) -> usize {
282 // True if any of the output types require codegen or linking.
283 pub fn should_codegen(&self) -> bool {
284 self.0.keys().any(|k| match *k {
286 | OutputType::Assembly
287 | OutputType::LlvmAssembly
290 | OutputType::Exe => true,
291 OutputType::Metadata | OutputType::DepInfo => false,
296 // Use tree-based collections to cheaply get a deterministic Hash implementation.
297 // DO NOT switch BTreeMap or BTreeSet out for an unsorted container type! That
298 // would break dependency tracking for command-line arguments.
299 #[derive(Clone, Hash)]
300 pub struct Externs(BTreeMap<String, ExternEntry>);
302 #[derive(Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Debug, Default)]
303 pub struct ExternEntry {
304 pub locations: BTreeSet<Option<String>>,
305 pub is_private_dep: bool
309 pub fn new(data: BTreeMap<String, ExternEntry>) -> Externs {
313 pub fn get(&self, key: &str) -> Option<&ExternEntry> {
317 pub fn iter<'a>(&'a self) -> BTreeMapIter<'a, String, ExternEntry> {
323 macro_rules! hash_option {
324 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [UNTRACKED]) => ({});
325 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({
326 if $sub_hashes.insert(stringify!($opt_name),
327 $opt_expr as &dyn dep_tracking::DepTrackingHash).is_some() {
328 bug!("Duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
334 [UNTRACKED_WITH_WARNING $warn_val:expr, $warn_text:expr, $error_format:expr]) => ({
335 if *$opt_expr == $warn_val {
336 early_warn($error_format, $warn_text)
341 macro_rules! top_level_options {
342 (pub struct Options { $(
343 $opt:ident : $t:ty [$dep_tracking_marker:ident $($warn_val:expr, $warn_text:expr)*],
351 pub fn dep_tracking_hash(&self) -> u64 {
352 let mut sub_hashes = BTreeMap::new();
357 [$dep_tracking_marker $($warn_val,
359 self.error_format)*]);
361 let mut hasher = DefaultHasher::new();
362 dep_tracking::stable_hash(sub_hashes,
371 // The top-level command-line options struct
373 // For each option, one has to specify how it behaves with regard to the
374 // dependency tracking system of incremental compilation. This is done via the
375 // square-bracketed directive after the field type. The options are:
378 // A change in the given field will cause the compiler to completely clear the
379 // incremental compilation cache before proceeding.
382 // Incremental compilation is not influenced by this option.
384 // [UNTRACKED_WITH_WARNING(val, warning)]
385 // The option is incompatible with incremental compilation in some way. If it
386 // has the value `val`, the string `warning` is emitted as a warning.
388 // If you add a new option to this struct or one of the sub-structs like
389 // CodegenOptions, think about how it influences incremental compilation. If in
390 // doubt, specify [TRACKED], which is always "correct" but might lead to
391 // unnecessary re-compilation.
394 // The crate config requested for the session, which may be combined
395 // with additional crate configurations during the compile process
396 crate_types: Vec<CrateType> [TRACKED],
397 optimize: OptLevel [TRACKED],
398 // Include the debug_assertions flag into dependency tracking, since it
399 // can influence whether overflow checks are done or not.
400 debug_assertions: bool [TRACKED],
401 debuginfo: DebugInfo [TRACKED],
402 lint_opts: Vec<(String, lint::Level)> [TRACKED],
403 lint_cap: Option<lint::Level> [TRACKED],
404 describe_lints: bool [UNTRACKED],
405 output_types: OutputTypes [TRACKED],
406 search_paths: Vec<SearchPath> [UNTRACKED],
407 libs: Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> [TRACKED],
408 maybe_sysroot: Option<PathBuf> [TRACKED],
410 target_triple: TargetTriple [TRACKED],
412 test: bool [TRACKED],
413 error_format: ErrorOutputType [UNTRACKED],
415 // if Some, enable incremental compilation, using the given
416 // directory to store intermediate results
417 incremental: Option<PathBuf> [UNTRACKED],
419 debugging_opts: DebuggingOptions [TRACKED],
420 prints: Vec<PrintRequest> [UNTRACKED],
421 // Determines which borrow checker(s) to run. This is the parsed, sanitized
422 // version of `debugging_opts.borrowck`, which is just a plain string.
423 borrowck_mode: BorrowckMode [UNTRACKED],
424 cg: CodegenOptions [TRACKED],
425 externs: Externs [UNTRACKED],
426 crate_name: Option<String> [TRACKED],
427 // An optional name to use as the crate for std during std injection,
428 // written `extern crate name as std`. Defaults to `std`. Used by
429 // out-of-tree drivers.
430 alt_std_name: Option<String> [TRACKED],
431 // Indicates how the compiler should treat unstable features
432 unstable_features: UnstableFeatures [TRACKED],
434 // Indicates whether this run of the compiler is actually rustdoc. This
435 // is currently just a hack and will be removed eventually, so please
436 // try to not rely on this too much.
437 actually_rustdoc: bool [TRACKED],
439 // Specifications of codegen units / ThinLTO which are forced as a
440 // result of parsing command line options. These are not necessarily
441 // what rustc was invoked with, but massaged a bit to agree with
442 // commands like `--emit llvm-ir` which they're often incompatible with
443 // if we otherwise use the defaults of rustc.
444 cli_forced_codegen_units: Option<usize> [UNTRACKED],
445 cli_forced_thinlto_off: bool [UNTRACKED],
447 // Remap source path prefixes in all output (messages, object files, debug, etc)
448 remap_path_prefix: Vec<(PathBuf, PathBuf)> [UNTRACKED],
450 edition: Edition [TRACKED],
454 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
455 pub enum PrintRequest {
470 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
471 pub enum BorrowckMode {
477 /// Should we run the MIR-based borrow check, but also fall back
478 /// on the AST borrow check if the MIR-based one errors.
479 pub fn migrate(self) -> bool {
481 BorrowckMode::Mir => false,
482 BorrowckMode::Migrate => true,
486 /// Should we emit the AST-based borrow checker errors?
487 pub fn use_ast(self) -> bool {
489 BorrowckMode::Mir => false,
490 BorrowckMode::Migrate => false,
496 /// Loads source from file
499 /// String that is shown in place of a filename
501 /// Anonymous source string
507 pub fn filestem(&self) -> &str {
509 Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap(),
510 Input::Str { .. } => "rust_out",
514 pub fn get_input(&mut self) -> Option<&mut String> {
516 Input::File(_) => None,
517 Input::Str { ref mut input, .. } => Some(input),
521 pub fn source_name(&self) -> FileName {
523 Input::File(ref ifile) => ifile.clone().into(),
524 Input::Str { ref name, .. } => name.clone(),
529 #[derive(Clone, Hash)]
530 pub struct OutputFilenames {
531 pub out_directory: PathBuf,
532 pub out_filestem: String,
533 pub single_output_file: Option<PathBuf>,
535 pub outputs: OutputTypes,
538 impl_stable_hash_via_hash!(OutputFilenames);
540 pub const RUST_CGU_EXT: &str = "rcgu";
542 impl OutputFilenames {
543 pub fn path(&self, flavor: OutputType) -> PathBuf {
546 .and_then(|p| p.to_owned())
547 .or_else(|| self.single_output_file.clone())
548 .unwrap_or_else(|| self.temp_path(flavor, None))
551 /// Gets the path where a compilation artifact of the given type for the
552 /// given codegen unit should be placed on disk. If codegen_unit_name is
553 /// None, a path distinct from those of any codegen unit will be generated.
554 pub fn temp_path(&self, flavor: OutputType, codegen_unit_name: Option<&str>) -> PathBuf {
555 let extension = flavor.extension();
556 self.temp_path_ext(extension, codegen_unit_name)
559 /// Like temp_path, but also supports things where there is no corresponding
560 /// OutputType, like noopt-bitcode or lto-bitcode.
561 pub fn temp_path_ext(&self, ext: &str, codegen_unit_name: Option<&str>) -> PathBuf {
562 let base = self.out_directory.join(&self.filestem());
564 let mut extension = String::new();
566 if let Some(codegen_unit_name) = codegen_unit_name {
567 extension.push_str(codegen_unit_name);
571 if !extension.is_empty() {
572 extension.push_str(".");
573 extension.push_str(RUST_CGU_EXT);
574 extension.push_str(".");
577 extension.push_str(ext);
580 let path = base.with_extension(&extension[..]);
584 pub fn with_extension(&self, extension: &str) -> PathBuf {
586 .join(&self.filestem())
587 .with_extension(extension)
590 pub fn filestem(&self) -> String {
591 format!("{}{}", self.out_filestem, self.extra)
595 pub fn host_triple() -> &'static str {
596 // Get the host triple out of the build environment. This ensures that our
597 // idea of the host triple is the same as for the set of libraries we've
598 // actually built. We can't just take LLVM's host triple because they
599 // normalize all ix86 architectures to i386.
601 // Instead of grabbing the host triple (for the current host), we grab (at
602 // compile time) the target triple that this rustc is built with and
603 // calling that (at runtime) the host triple.
604 (option_env!("CFG_COMPILER_HOST_TRIPLE")).expect("CFG_COMPILER_HOST_TRIPLE")
607 impl Default for Options {
608 fn default() -> Options {
610 crate_types: Vec::new(),
611 optimize: OptLevel::No,
612 debuginfo: DebugInfo::None,
613 lint_opts: Vec::new(),
615 describe_lints: false,
616 output_types: OutputTypes(BTreeMap::new()),
617 search_paths: vec![],
619 target_triple: TargetTriple::from_triple(host_triple()),
622 debugging_opts: basic_debugging_options(),
624 borrowck_mode: BorrowckMode::Migrate,
625 cg: basic_codegen_options(),
626 error_format: ErrorOutputType::default(),
627 externs: Externs(BTreeMap::new()),
631 unstable_features: UnstableFeatures::Disallow,
632 debug_assertions: true,
633 actually_rustdoc: false,
634 cli_forced_codegen_units: None,
635 cli_forced_thinlto_off: false,
636 remap_path_prefix: Vec::new(),
637 edition: DEFAULT_EDITION,
643 /// Returns `true` if there is a reason to build the dep graph.
644 pub fn build_dep_graph(&self) -> bool {
645 self.incremental.is_some() || self.debugging_opts.dump_dep_graph
646 || self.debugging_opts.query_dep_graph
650 pub fn enable_dep_node_debug_strs(&self) -> bool {
651 cfg!(debug_assertions)
652 && (self.debugging_opts.query_dep_graph || self.debugging_opts.incremental_info)
655 pub fn file_path_mapping(&self) -> FilePathMapping {
656 FilePathMapping::new(self.remap_path_prefix.clone())
659 /// Returns `true` if there will be an output file generated
660 pub fn will_create_output_file(&self) -> bool {
661 !self.debugging_opts.parse_only && // The file is just being parsed
662 !self.debugging_opts.ls // The file is just being queried
666 pub fn share_generics(&self) -> bool {
667 match self.debugging_opts.share_generics {
668 Some(setting) => setting,
670 match self.optimize {
674 OptLevel::SizeMin => true,
676 OptLevel::Aggressive => false,
683 // The type of entry function, so users can have their own entry functions
684 #[derive(Copy, Clone, PartialEq, Hash, Debug)]
685 pub enum EntryFnType {
690 impl_stable_hash_via_hash!(EntryFnType);
692 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
702 #[derive(Clone, Hash)]
709 pub fn is_empty(&self) -> bool {
711 Passes::Some(ref v) => v.is_empty(),
712 Passes::All => false,
717 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
718 /// at once. The goal of this macro is to define an interface that can be
719 /// programmatically used by the option parser in order to initialize the struct
720 /// without hardcoding field names all over the place.
722 /// The goal is to invoke this macro once with the correct fields, and then this
723 /// macro generates all necessary code. The main gotcha of this macro is the
724 /// cgsetters module which is a bunch of generated code to parse an option into
725 /// its respective field in the struct. There are a few hand-written parsers for
726 /// parsing specific types of values in this module.
727 macro_rules! options {
728 ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
729 $buildfn:ident, $prefix:expr, $outputname:expr,
730 $stat:ident, $mod_desc:ident, $mod_set:ident,
731 $($opt:ident : $t:ty = (
734 [$dep_tracking_marker:ident $(($dep_warn_val:expr, $dep_warn_text:expr))*],
739 pub struct $struct_name { $(pub $opt: $t),* }
741 pub fn $defaultfn() -> $struct_name {
742 $struct_name { $($opt: $init),* }
745 pub fn $buildfn(matches: &getopts::Matches, error_format: ErrorOutputType) -> $struct_name
747 let mut op = $defaultfn();
748 for option in matches.opt_strs($prefix) {
749 let mut iter = option.splitn(2, '=');
750 let key = iter.next().unwrap();
751 let value = iter.next();
752 let option_to_lookup = key.replace("-", "_");
753 let mut found = false;
754 for &(candidate, setter, opt_type_desc, _) in $stat {
755 if option_to_lookup != candidate { continue }
756 if !setter(&mut op, value) {
757 match (value, opt_type_desc) {
758 (Some(..), None) => {
759 early_error(error_format, &format!("{} option `{}` takes no \
760 value", $outputname, key))
762 (None, Some(type_desc)) => {
763 early_error(error_format, &format!("{0} option `{1}` requires \
764 {2} ({3} {1}=<value>)",
768 (Some(value), Some(type_desc)) => {
769 early_error(error_format, &format!("incorrect value `{}` for {} \
770 option `{}` - {} was expected",
774 (None, None) => bug!()
781 early_error(error_format, &format!("unknown {} option: `{}`",
788 impl<'a> dep_tracking::DepTrackingHash for $struct_name {
789 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
790 let mut sub_hashes = BTreeMap::new();
795 [$dep_tracking_marker $($dep_warn_val,
799 dep_tracking::stable_hash(sub_hashes, hasher, error_format);
803 pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
804 pub const $stat: &[(&str, $setter_name, Option<&str>, &str)] =
805 &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
807 #[allow(non_upper_case_globals, dead_code)]
809 pub const parse_bool: Option<&str> = None;
810 pub const parse_opt_bool: Option<&str> =
811 Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
812 pub const parse_string: Option<&str> = Some("a string");
813 pub const parse_string_push: Option<&str> = Some("a string");
814 pub const parse_pathbuf_push: Option<&str> = Some("a path");
815 pub const parse_opt_string: Option<&str> = Some("a string");
816 pub const parse_opt_pathbuf: Option<&str> = Some("a path");
817 pub const parse_list: Option<&str> = Some("a space-separated list of strings");
818 pub const parse_opt_list: Option<&str> = Some("a space-separated list of strings");
819 pub const parse_opt_comma_list: Option<&str> = Some("a comma-separated list of strings");
820 pub const parse_uint: Option<&str> = Some("a number");
821 pub const parse_passes: Option<&str> =
822 Some("a space-separated list of passes, or `all`");
823 pub const parse_opt_uint: Option<&str> =
825 pub const parse_panic_strategy: Option<&str> =
826 Some("either `unwind` or `abort`");
827 pub const parse_relro_level: Option<&str> =
828 Some("one of: `full`, `partial`, or `off`");
829 pub const parse_sanitizer: Option<&str> =
830 Some("one of: `address`, `leak`, `memory` or `thread`");
831 pub const parse_linker_flavor: Option<&str> =
832 Some(::rustc_target::spec::LinkerFlavor::one_of());
833 pub const parse_optimization_fuel: Option<&str> =
834 Some("crate=integer");
835 pub const parse_unpretty: Option<&str> =
836 Some("`string` or `string=string`");
837 pub const parse_treat_err_as_bug: Option<&str> =
838 Some("either no value or a number bigger than 0");
839 pub const parse_lto: Option<&str> =
840 Some("either a boolean (`yes`, `no`, `on`, `off`, etc), `thin`, \
842 pub const parse_linker_plugin_lto: Option<&str> =
843 Some("either a boolean (`yes`, `no`, `on`, `off`, etc), \
844 or the path to the linker plugin");
845 pub const parse_switch_with_opt_path: Option<&str> =
846 Some("an optional path to the profiling data output directory");
847 pub const parse_merge_functions: Option<&str> =
848 Some("one of: `disabled`, `trampolines`, or `aliases`");
849 pub const parse_symbol_mangling_version: Option<&str> =
850 Some("either `legacy` or `v0` (RFC 2603)");
855 use super::{$struct_name, Passes, Sanitizer, LtoCli, LinkerPluginLto, SwitchWithOptPath,
856 SymbolManglingVersion};
857 use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
858 use std::path::PathBuf;
859 use std::str::FromStr;
862 pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
863 $parse(&mut cg.$opt, v)
867 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
870 None => { *slot = true; true }
874 fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
878 "n" | "no" | "off" => {
881 "y" | "yes" | "on" => {
884 _ => { return false; }
889 None => { *slot = Some(true); true }
893 fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
895 Some(s) => { *slot = Some(s.to_string()); true },
900 fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
902 Some(s) => { *slot = Some(PathBuf::from(s)); true },
907 fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
909 Some(s) => { *slot = s.to_string(); true },
914 fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
916 Some(s) => { slot.push(s.to_string()); true },
921 fn parse_pathbuf_push(slot: &mut Vec<PathBuf>, v: Option<&str>) -> bool {
923 Some(s) => { slot.push(PathBuf::from(s)); true },
928 fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
932 slot.extend(s.split_whitespace().map(|s| s.to_string()));
939 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
943 let v = s.split_whitespace().map(|s| s.to_string()).collect();
951 fn parse_opt_comma_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
955 let v = s.split(',').map(|s| s.to_string()).collect();
963 fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
964 match v.and_then(|s| s.parse().ok()) {
965 Some(i) => { *slot = i; true },
970 fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
972 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
973 None => { *slot = None; false }
977 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
984 let mut passes = vec![];
985 if parse_list(&mut passes, v) {
986 *slot = Passes::Some(passes);
995 fn parse_panic_strategy(slot: &mut Option<PanicStrategy>, v: Option<&str>) -> bool {
997 Some("unwind") => *slot = Some(PanicStrategy::Unwind),
998 Some("abort") => *slot = Some(PanicStrategy::Abort),
1004 fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
1007 match s.parse::<RelroLevel>() {
1008 Ok(level) => *slot = Some(level),
1017 fn parse_sanitizer(slote: &mut Option<Sanitizer>, v: Option<&str>) -> bool {
1019 Some("address") => *slote = Some(Sanitizer::Address),
1020 Some("leak") => *slote = Some(Sanitizer::Leak),
1021 Some("memory") => *slote = Some(Sanitizer::Memory),
1022 Some("thread") => *slote = Some(Sanitizer::Thread),
1028 fn parse_linker_flavor(slote: &mut Option<LinkerFlavor>, v: Option<&str>) -> bool {
1029 match v.and_then(LinkerFlavor::from_str) {
1030 Some(lf) => *slote = Some(lf),
1036 fn parse_optimization_fuel(slot: &mut Option<(String, u64)>, v: Option<&str>) -> bool {
1040 let parts = s.split('=').collect::<Vec<_>>();
1041 if parts.len() != 2 { return false; }
1042 let crate_name = parts[0].to_string();
1043 let fuel = parts[1].parse::<u64>();
1044 if fuel.is_err() { return false; }
1045 *slot = Some((crate_name, fuel.unwrap()));
1051 fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
1054 Some(s) if s.split('=').count() <= 2 => {
1055 *slot = Some(s.to_string());
1062 fn parse_treat_err_as_bug(slot: &mut Option<usize>, v: Option<&str>) -> bool {
1064 Some(s) => { *slot = s.parse().ok().filter(|&x| x != 0); slot.unwrap_or(0) != 0 }
1065 None => { *slot = Some(1); true }
1069 fn parse_lto(slot: &mut LtoCli, v: Option<&str>) -> bool {
1071 let mut bool_arg = None;
1072 if parse_opt_bool(&mut bool_arg, v) {
1073 *slot = if bool_arg.unwrap() {
1083 None => LtoCli::NoParam,
1084 Some("thin") => LtoCli::Thin,
1085 Some("fat") => LtoCli::Fat,
1086 Some(_) => return false,
1091 fn parse_linker_plugin_lto(slot: &mut LinkerPluginLto, v: Option<&str>) -> bool {
1093 let mut bool_arg = None;
1094 if parse_opt_bool(&mut bool_arg, v) {
1095 *slot = if bool_arg.unwrap() {
1096 LinkerPluginLto::LinkerPluginAuto
1098 LinkerPluginLto::Disabled
1105 None => LinkerPluginLto::LinkerPluginAuto,
1106 Some(path) => LinkerPluginLto::LinkerPlugin(PathBuf::from(path)),
1111 fn parse_switch_with_opt_path(slot: &mut SwitchWithOptPath, v: Option<&str>) -> bool {
1113 None => SwitchWithOptPath::Enabled(None),
1114 Some(path) => SwitchWithOptPath::Enabled(Some(PathBuf::from(path))),
1119 fn parse_merge_functions(slot: &mut Option<MergeFunctions>, v: Option<&str>) -> bool {
1120 match v.and_then(|s| MergeFunctions::from_str(s).ok()) {
1121 Some(mergefunc) => *slot = Some(mergefunc),
1127 fn parse_symbol_mangling_version(
1128 slot: &mut SymbolManglingVersion,
1132 Some("legacy") => SymbolManglingVersion::Legacy,
1133 Some("v0") => SymbolManglingVersion::V0,
1141 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
1142 build_codegen_options, "C", "codegen",
1143 CG_OPTIONS, cg_type_desc, cgsetters,
1144 ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
1145 "this option is deprecated and does nothing"),
1146 linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
1147 "system linker to link outputs with"),
1148 link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1149 "a single extra argument to append to the linker invocation (can be used several times)"),
1150 link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1151 "extra arguments to append to the linker invocation (space separated)"),
1152 link_dead_code: bool = (false, parse_bool, [UNTRACKED],
1153 "don't let linker strip dead code (turning it on can be used for code coverage)"),
1154 lto: LtoCli = (LtoCli::Unspecified, parse_lto, [TRACKED],
1155 "perform LLVM link-time optimizations"),
1156 target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
1157 "select target processor (rustc --print target-cpus for details)"),
1158 target_feature: String = (String::new(), parse_string, [TRACKED],
1159 "target specific attributes (rustc --print target-features for details)"),
1160 passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1161 "a list of extra LLVM passes to run (space separated)"),
1162 llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1163 "a list of arguments to pass to llvm (space separated)"),
1164 save_temps: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1165 "`-C save-temps` might not produce all requested temporary products \
1166 when incremental compilation is enabled.")],
1167 "save all temporary output files during compilation"),
1168 rpath: bool = (false, parse_bool, [UNTRACKED],
1169 "set rpath values in libs/exes"),
1170 overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1171 "use overflow checks for integer arithmetic"),
1172 no_prepopulate_passes: bool = (false, parse_bool, [TRACKED],
1173 "don't pre-populate the pass manager with a list of passes"),
1174 no_vectorize_loops: bool = (false, parse_bool, [TRACKED],
1175 "don't run the loop vectorization optimization passes"),
1176 no_vectorize_slp: bool = (false, parse_bool, [TRACKED],
1177 "don't run LLVM's SLP vectorization pass"),
1178 soft_float: bool = (false, parse_bool, [TRACKED],
1179 "use soft float ABI (*eabihf targets only)"),
1180 prefer_dynamic: bool = (false, parse_bool, [TRACKED],
1181 "prefer dynamic linking to static linking"),
1182 no_integrated_as: bool = (false, parse_bool, [TRACKED],
1183 "use an external assembler rather than LLVM's integrated one"),
1184 no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
1185 "disable the use of the redzone"),
1186 relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
1187 "choose the relocation model to use (rustc --print relocation-models for details)"),
1188 code_model: Option<String> = (None, parse_opt_string, [TRACKED],
1189 "choose the code model to use (rustc --print code-models for details)"),
1190 metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1191 "metadata to mangle symbol names with"),
1192 extra_filename: String = (String::new(), parse_string, [UNTRACKED],
1193 "extra data to put in each output filename"),
1194 codegen_units: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1195 "divide crate into N units to optimize in parallel"),
1196 remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
1197 "print remarks for these optimization passes (space separated, or \"all\")"),
1198 no_stack_check: bool = (false, parse_bool, [UNTRACKED],
1199 "the --no-stack-check flag is deprecated and does nothing"),
1200 debuginfo: Option<usize> = (None, parse_opt_uint, [TRACKED],
1201 "debug info emission level, 0 = no debug info, 1 = line tables only, \
1202 2 = full debug info with variable and type information"),
1203 opt_level: Option<String> = (None, parse_opt_string, [TRACKED],
1204 "optimize with possible levels 0-3, s, or z"),
1205 force_frame_pointers: Option<bool> = (None, parse_opt_bool, [TRACKED],
1206 "force use of the frame pointers"),
1207 debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
1208 "explicitly enable the cfg(debug_assertions) directive"),
1209 inline_threshold: Option<usize> = (None, parse_opt_uint, [TRACKED],
1210 "set the threshold for inlining a function (default: 225)"),
1211 panic: Option<PanicStrategy> = (None, parse_panic_strategy,
1212 [TRACKED], "panic strategy to compile crate with"),
1213 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1214 "enable incremental compilation"),
1215 default_linker_libraries: Option<bool> = (None, parse_opt_bool, [UNTRACKED],
1216 "allow the linker to link its default libraries"),
1217 linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
1219 linker_plugin_lto: LinkerPluginLto = (LinkerPluginLto::Disabled,
1220 parse_linker_plugin_lto, [TRACKED],
1221 "generate build artifacts that are compatible with linker-based LTO."),
1225 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
1226 build_debugging_options, "Z", "debugging",
1227 DB_OPTIONS, db_type_desc, dbsetters,
1228 codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
1229 "the backend to use"),
1230 verbose: bool = (false, parse_bool, [UNTRACKED],
1231 "in general, enable more debug printouts"),
1232 span_free_formats: bool = (false, parse_bool, [UNTRACKED],
1233 "when debug-printing compiler state, do not include spans"), // o/w tests have closure@path
1234 identify_regions: bool = (false, parse_bool, [UNTRACKED],
1235 "make unnamed regions display as '# (where # is some non-ident unique id)"),
1236 borrowck: Option<String> = (None, parse_opt_string, [UNTRACKED],
1237 "select which borrowck is used (`mir` or `migrate`)"),
1238 time_passes: bool = (false, parse_bool, [UNTRACKED],
1239 "measure time of each rustc pass"),
1240 time: bool = (false, parse_bool, [UNTRACKED],
1241 "measure time of rustc processes"),
1242 time_llvm_passes: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1243 "The output of `-Z time-llvm-passes` will only reflect timings of \
1244 re-codegened modules when used with incremental compilation" )],
1245 "measure time of each LLVM pass"),
1246 input_stats: bool = (false, parse_bool, [UNTRACKED],
1247 "gather statistics about the input"),
1248 asm_comments: bool = (false, parse_bool, [TRACKED],
1249 "generate comments into the assembly (may change behavior)"),
1250 verify_llvm_ir: bool = (false, parse_bool, [TRACKED],
1252 borrowck_stats: bool = (false, parse_bool, [UNTRACKED],
1253 "gather borrowck statistics"),
1254 no_landing_pads: bool = (false, parse_bool, [TRACKED],
1255 "omit landing pads for unwinding"),
1256 fewer_names: bool = (false, parse_bool, [TRACKED],
1257 "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR)"),
1258 meta_stats: bool = (false, parse_bool, [UNTRACKED],
1259 "gather metadata statistics"),
1260 print_link_args: bool = (false, parse_bool, [UNTRACKED],
1261 "print the arguments passed to the linker"),
1262 print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1263 "prints the llvm optimization passes being run"),
1264 ast_json: bool = (false, parse_bool, [UNTRACKED],
1265 "print the AST as JSON and halt"),
1266 threads: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1267 "use a thread pool with N threads"),
1268 ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
1269 "print the pre-expansion AST as JSON and halt"),
1270 ls: bool = (false, parse_bool, [UNTRACKED],
1271 "list the symbols defined by a library crate"),
1272 save_analysis: bool = (false, parse_bool, [UNTRACKED],
1273 "write syntax and type analysis (in JSON format) information, in \
1274 addition to normal output"),
1275 flowgraph_print_loans: bool = (false, parse_bool, [UNTRACKED],
1276 "include loan analysis data in -Z unpretty flowgraph output"),
1277 flowgraph_print_moves: bool = (false, parse_bool, [UNTRACKED],
1278 "include move analysis data in -Z unpretty flowgraph output"),
1279 flowgraph_print_assigns: bool = (false, parse_bool, [UNTRACKED],
1280 "include assignment analysis data in -Z unpretty flowgraph output"),
1281 flowgraph_print_all: bool = (false, parse_bool, [UNTRACKED],
1282 "include all dataflow analysis data in -Z unpretty flowgraph output"),
1283 print_region_graph: bool = (false, parse_bool, [UNTRACKED],
1284 "prints region inference graph. \
1285 Use with RUST_REGION_GRAPH=help for more info"),
1286 parse_only: bool = (false, parse_bool, [UNTRACKED],
1287 "parse only; do not compile, assemble, or link"),
1288 dual_proc_macros: bool = (false, parse_bool, [TRACKED],
1289 "load proc macros for both target and host, but only link to the target"),
1290 no_codegen: bool = (false, parse_bool, [TRACKED],
1291 "run all passes except codegen; no output"),
1292 treat_err_as_bug: Option<usize> = (None, parse_treat_err_as_bug, [TRACKED],
1293 "treat error number `val` that occurs as bug"),
1294 report_delayed_bugs: bool = (false, parse_bool, [TRACKED],
1295 "immediately print bugs registered with `delay_span_bug`"),
1296 external_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1297 "show macro backtraces even for non-local macros"),
1298 teach: bool = (false, parse_bool, [TRACKED],
1299 "show extended diagnostic help"),
1300 continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
1301 "attempt to recover from parse errors (experimental)"),
1302 dep_tasks: bool = (false, parse_bool, [UNTRACKED],
1303 "print tasks that execute and the color their dep node gets (requires debug build)"),
1304 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1305 "enable incremental compilation (experimental)"),
1306 incremental_queries: bool = (true, parse_bool, [UNTRACKED],
1307 "enable incremental compilation support for queries (experimental)"),
1308 incremental_info: bool = (false, parse_bool, [UNTRACKED],
1309 "print high-level information about incremental reuse (or the lack thereof)"),
1310 incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
1311 "dump hash information in textual format to stdout"),
1312 incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
1313 "verify incr. comp. hashes of green query instances"),
1314 incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
1315 "ignore spans during ICH computation -- used for testing"),
1316 instrument_mcount: bool = (false, parse_bool, [TRACKED],
1317 "insert function instrument code for mcount-based tracing"),
1318 dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1319 "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
1320 query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1321 "enable queries of the dependency graph for regression testing"),
1322 profile_queries: bool = (false, parse_bool, [UNTRACKED],
1323 "trace and profile the queries of the incremental compilation framework"),
1324 profile_queries_and_keys: bool = (false, parse_bool, [UNTRACKED],
1325 "trace and profile the queries and keys of the incremental compilation framework"),
1326 no_analysis: bool = (false, parse_bool, [UNTRACKED],
1327 "parse and expand the source, but run no analysis"),
1328 extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1329 "load extra plugins"),
1330 unstable_options: bool = (false, parse_bool, [UNTRACKED],
1331 "adds unstable command line options to rustc interface"),
1332 force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1333 "force overflow checks on or off"),
1334 trace_macros: bool = (false, parse_bool, [UNTRACKED],
1335 "for every macro invocation, print its name and arguments"),
1336 debug_macros: bool = (false, parse_bool, [TRACKED],
1337 "emit line numbers debug info inside macros"),
1338 keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
1339 "don't clear the hygiene data after analysis"),
1340 keep_ast: bool = (false, parse_bool, [UNTRACKED],
1341 "keep the AST after lowering it to HIR"),
1342 show_span: Option<String> = (None, parse_opt_string, [TRACKED],
1343 "show spans for compiler debugging (expr|pat|ty)"),
1344 print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
1345 "print layout information for each type encountered"),
1346 print_mono_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
1347 "print the result of the monomorphization collection pass"),
1348 mir_opt_level: usize = (1, parse_uint, [TRACKED],
1349 "set the MIR optimization level (0-3, default: 1)"),
1350 mutable_noalias: Option<bool> = (None, parse_opt_bool, [TRACKED],
1351 "emit noalias metadata for mutable references (default: yes on LLVM >= 6)"),
1352 dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1353 "dump MIR state to file.
1354 `val` is used to select which passes and functions to dump. For example:
1355 `all` matches all passes and functions,
1356 `foo` matches all passes for functions whose name contains 'foo',
1357 `foo & ConstProp` only the 'ConstProp' pass for function names containing 'foo',
1358 `foo | bar` all passes for function names containing 'foo' or 'bar'."),
1360 dump_mir_dir: String = (String::from("mir_dump"), parse_string, [UNTRACKED],
1361 "the directory the MIR is dumped into"),
1362 dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
1363 "in addition to `.mir` files, create graphviz `.dot` files"),
1364 dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
1365 "if set, exclude the pass number when dumping MIR (used in tests)"),
1366 mir_emit_retag: bool = (false, parse_bool, [TRACKED],
1367 "emit Retagging MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0"),
1368 perf_stats: bool = (false, parse_bool, [UNTRACKED],
1369 "print some performance-related statistics"),
1370 query_stats: bool = (false, parse_bool, [UNTRACKED],
1371 "print some statistics about the query system"),
1372 hir_stats: bool = (false, parse_bool, [UNTRACKED],
1373 "print some statistics about AST and HIR"),
1374 always_encode_mir: bool = (false, parse_bool, [TRACKED],
1375 "encode MIR of all functions into the crate metadata"),
1376 json_rendered: Option<String> = (None, parse_opt_string, [UNTRACKED],
1377 "describes how to render the `rendered` field of json diagnostics"),
1378 unleash_the_miri_inside_of_you: bool = (false, parse_bool, [TRACKED],
1379 "take the breaks off const evaluation. NOTE: this is unsound"),
1380 osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
1381 "pass `-install_name @rpath/...` to the macOS linker"),
1382 sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
1384 fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
1385 "set the optimization fuel quota for a crate"),
1386 print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
1387 "make Rustc print the total optimization fuel used by a crate"),
1388 force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
1389 "force all crates to be `rustc_private` unstable"),
1390 pre_link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1391 "a single extra argument to prepend the linker invocation (can be used several times)"),
1392 pre_link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1393 "extra arguments to prepend to the linker invocation (space separated)"),
1394 profile: bool = (false, parse_bool, [TRACKED],
1395 "insert profiling code"),
1396 pgo_gen: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
1397 parse_switch_with_opt_path, [TRACKED],
1398 "Generate PGO profile data, to a given file, or to the default location if it's empty."),
1399 pgo_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1400 "Use PGO profile data from the given profile file."),
1401 disable_instrumentation_preinliner: bool = (false, parse_bool, [TRACKED],
1402 "Disable the instrumentation pre-inliner, useful for profiling / PGO."),
1403 relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
1404 "choose which RELRO level to use"),
1405 nll_facts: bool = (false, parse_bool, [UNTRACKED],
1406 "dump facts from NLL analysis into side files"),
1407 nll_dont_emit_read_for_match: bool = (false, parse_bool, [UNTRACKED],
1408 "in match codegen, do not include FakeRead statements (used by mir-borrowck)"),
1409 dont_buffer_diagnostics: bool = (false, parse_bool, [UNTRACKED],
1410 "emit diagnostics rather than buffering (breaks NLL error downgrading, sorting)."),
1411 polonius: bool = (false, parse_bool, [UNTRACKED],
1412 "enable polonius-based borrow-checker"),
1413 codegen_time_graph: bool = (false, parse_bool, [UNTRACKED],
1414 "generate a graphical HTML report of time spent in codegen and LLVM"),
1415 thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
1416 "enable ThinLTO when possible"),
1417 inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
1418 "control whether #[inline] functions are in all cgus"),
1419 tls_model: Option<String> = (None, parse_opt_string, [TRACKED],
1420 "choose the TLS model to use (rustc --print tls-models for details)"),
1421 saturating_float_casts: bool = (false, parse_bool, [TRACKED],
1422 "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
1423 the max/min integer respectively, and NaN is mapped to 0"),
1424 lower_128bit_ops: Option<bool> = (None, parse_opt_bool, [TRACKED],
1425 "rewrite operators on i128 and u128 into lang item calls (typically provided \
1426 by compiler-builtins) so codegen doesn't need to support them,
1427 overriding the default for the current target"),
1428 human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
1429 "generate human-readable, predictable names for codegen units"),
1430 dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
1431 "in dep-info output, omit targets for tracking dependencies of the dep-info files \
1433 unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
1434 "Present the input source, unstable (and less-pretty) variants;
1435 valid types are any of the types for `--pretty`, as well as:
1436 `expanded`, `expanded,identified`,
1437 `expanded,hygiene` (with internal representations),
1438 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
1439 `flowgraph,unlabelled=<nodeid>` (unlabelled graphviz formatted flowgraph for node),
1440 `everybody_loops` (all function bodies replaced with `loop {}`),
1441 `hir` (the HIR), `hir,identified`,
1442 `hir,typed` (HIR with types for each node),
1443 `hir-tree` (dump the raw HIR),
1444 `mir` (the MIR), or `mir-cfg` (graphviz formatted MIR)"),
1445 run_dsymutil: Option<bool> = (None, parse_opt_bool, [TRACKED],
1446 "run `dsymutil` and delete intermediate object files"),
1447 ui_testing: bool = (false, parse_bool, [UNTRACKED],
1448 "format compiler diagnostics in a way that's better suitable for UI testing"),
1449 embed_bitcode: bool = (false, parse_bool, [TRACKED],
1450 "embed LLVM bitcode in object files"),
1451 strip_debuginfo_if_disabled: Option<bool> = (None, parse_opt_bool, [TRACKED],
1452 "tell the linker to strip debuginfo when building without debuginfo enabled."),
1453 share_generics: Option<bool> = (None, parse_opt_bool, [TRACKED],
1454 "make the current crate share its generic instantiations"),
1455 chalk: bool = (false, parse_bool, [TRACKED],
1456 "enable the experimental Chalk-based trait solving engine"),
1457 no_parallel_llvm: bool = (false, parse_bool, [UNTRACKED],
1458 "don't run LLVM in parallel (while keeping codegen-units and ThinLTO)"),
1459 no_leak_check: bool = (false, parse_bool, [UNTRACKED],
1460 "disables the 'leak check' for subtyping; unsound, but useful for tests"),
1461 no_interleave_lints: bool = (false, parse_bool, [UNTRACKED],
1462 "don't interleave execution of lints; allows benchmarking individual lints"),
1463 crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],
1464 "inject the given attribute in the crate"),
1465 self_profile: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
1466 parse_switch_with_opt_path, [UNTRACKED],
1467 "run the self profiler and output the raw event data"),
1468 self_profile_events: Option<Vec<String>> = (None, parse_opt_comma_list, [UNTRACKED],
1469 "specifies which kinds of events get recorded by the self profiler"),
1470 emit_stack_sizes: bool = (false, parse_bool, [UNTRACKED],
1471 "emits a section containing stack size metadata"),
1472 plt: Option<bool> = (None, parse_opt_bool, [TRACKED],
1473 "whether to use the PLT when calling into shared libraries;
1474 only has effect for PIC code on systems with ELF binaries
1475 (default: PLT is disabled if full relro is enabled)"),
1476 merge_functions: Option<MergeFunctions> = (None, parse_merge_functions, [TRACKED],
1477 "control the operation of the MergeFunctions LLVM pass, taking
1478 the same values as the target option of the same name"),
1479 allow_features: Option<Vec<String>> = (None, parse_opt_comma_list, [TRACKED],
1480 "only allow the listed language features to be enabled in code (space separated)"),
1481 emit_artifact_notifications: bool = (false, parse_bool, [UNTRACKED],
1482 "emit notifications after each artifact has been output (only in the JSON format)"),
1483 symbol_mangling_version: SymbolManglingVersion = (SymbolManglingVersion::Legacy,
1484 parse_symbol_mangling_version, [TRACKED],
1485 "which mangling version to use for symbol names"),
1488 pub fn default_lib_output() -> CrateType {
1492 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
1493 let end = &sess.target.target.target_endian;
1494 let arch = &sess.target.target.arch;
1495 let wordsz = &sess.target.target.target_pointer_width;
1496 let os = &sess.target.target.target_os;
1497 let env = &sess.target.target.target_env;
1498 let vendor = &sess.target.target.target_vendor;
1499 let min_atomic_width = sess.target.target.min_atomic_width();
1500 let max_atomic_width = sess.target.target.max_atomic_width();
1501 let atomic_cas = sess.target.target.options.atomic_cas;
1503 let mut ret = FxHashSet::default();
1504 ret.reserve(6); // the minimum number of insertions
1506 ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
1507 if let Some(ref fam) = sess.target.target.options.target_family {
1508 ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam))));
1509 if fam == "windows" || fam == "unix" {
1510 ret.insert((Symbol::intern(fam), None));
1513 ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
1514 ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
1516 Symbol::intern("target_pointer_width"),
1517 Some(Symbol::intern(wordsz)),
1519 ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
1521 Symbol::intern("target_vendor"),
1522 Some(Symbol::intern(vendor)),
1524 if sess.target.target.options.has_elf_tls {
1525 ret.insert((sym::target_thread_local, None));
1527 for &i in &[8, 16, 32, 64, 128] {
1528 if i >= min_atomic_width && i <= max_atomic_width {
1529 let s = i.to_string();
1531 sym::target_has_atomic,
1532 Some(Symbol::intern(&s)),
1536 sym::target_has_atomic,
1537 Some(Symbol::intern("ptr")),
1543 ret.insert((sym::target_has_atomic, Some(Symbol::intern("cas"))));
1545 if sess.opts.debug_assertions {
1546 ret.insert((Symbol::intern("debug_assertions"), None));
1548 if sess.opts.crate_types.contains(&CrateType::ProcMacro) {
1549 ret.insert((sym::proc_macro, None));
1554 /// Converts the crate cfg! configuration from String to Symbol.
1555 /// `rustc_interface::interface::Config` accepts this in the compiler configuration,
1556 /// but the symbol interner is not yet set up then, so we must convert it later.
1557 pub fn to_crate_config(cfg: FxHashSet<(String, Option<String>)>) -> ast::CrateConfig {
1559 .map(|(a, b)| (Symbol::intern(&a), b.map(|b| Symbol::intern(&b))))
1563 pub fn build_configuration(sess: &Session, mut user_cfg: ast::CrateConfig) -> ast::CrateConfig {
1564 // Combine the configuration requested by the session (command line) with
1565 // some default and generated configuration items
1566 let default_cfg = default_configuration(sess);
1567 // If the user wants a test runner, then add the test cfg
1569 user_cfg.insert((sym::test, None));
1571 user_cfg.extend(default_cfg.iter().cloned());
1575 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
1576 let target = Target::search(&opts.target_triple).unwrap_or_else(|e| {
1577 sp.struct_fatal(&format!("Error loading target specification: {}", e))
1578 .help("Use `--print target-list` for a list of built-in targets")
1583 let (isize_ty, usize_ty) = match &target.target_pointer_width[..] {
1584 "16" => (ast::IntTy::I16, ast::UintTy::U16),
1585 "32" => (ast::IntTy::I32, ast::UintTy::U32),
1586 "64" => (ast::IntTy::I64, ast::UintTy::U64),
1587 w => sp.fatal(&format!(
1588 "target specification was invalid: \
1589 unrecognized target-pointer-width {}",
1601 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1602 pub enum OptionStability {
1607 pub struct RustcOptGroup {
1608 pub apply: Box<dyn Fn(&mut getopts::Options) -> &mut getopts::Options>,
1609 pub name: &'static str,
1610 pub stability: OptionStability,
1613 impl RustcOptGroup {
1614 pub fn is_stable(&self) -> bool {
1615 self.stability == OptionStability::Stable
1618 pub fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
1620 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1625 stability: OptionStability::Stable,
1629 pub fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
1631 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1636 stability: OptionStability::Unstable,
1641 // The `opt` local module holds wrappers around the `getopts` API that
1642 // adds extra rustc-specific metadata to each option; such metadata
1643 // is exposed by . The public
1644 // functions below ending with `_u` are the functions that return
1645 // *unstable* options, i.e., options that are only enabled when the
1646 // user also passes the `-Z unstable-options` debugging flag.
1648 // The `fn opt_u` etc below are written so that we can use them
1649 // in the future; do not warn about them not being used right now.
1650 #![allow(dead_code)]
1653 use super::RustcOptGroup;
1655 pub type R = RustcOptGroup;
1656 pub type S = &'static str;
1658 fn stable<F>(name: S, f: F) -> R
1660 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1662 RustcOptGroup::stable(name, f)
1665 fn unstable<F>(name: S, f: F) -> R
1667 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1669 RustcOptGroup::unstable(name, f)
1672 fn longer(a: S, b: S) -> S {
1673 if a.len() > b.len() {
1680 pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
1681 stable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1683 pub fn multi_s(a: S, b: S, c: S, d: S) -> R {
1684 stable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1686 pub fn flag_s(a: S, b: S, c: S) -> R {
1687 stable(longer(a, b), move |opts| opts.optflag(a, b, c))
1689 pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R {
1690 stable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1692 pub fn flagmulti_s(a: S, b: S, c: S) -> R {
1693 stable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1696 pub fn opt(a: S, b: S, c: S, d: S) -> R {
1697 unstable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1699 pub fn multi(a: S, b: S, c: S, d: S) -> R {
1700 unstable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1702 pub fn flag(a: S, b: S, c: S) -> R {
1703 unstable(longer(a, b), move |opts| opts.optflag(a, b, c))
1705 pub fn flagopt(a: S, b: S, c: S, d: S) -> R {
1706 unstable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1708 pub fn flagmulti(a: S, b: S, c: S) -> R {
1709 unstable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1713 /// Returns the "short" subset of the rustc command line options,
1714 /// including metadata for each option, such as whether the option is
1715 /// part of the stable long-term interface for rustc.
1716 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
1718 opt::flag_s("h", "help", "Display this message"),
1719 opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
1723 "Add a directory to the library search path. The
1724 optional KIND can be one of dependency, crate, native,
1725 framework or all (the default).",
1731 "Link the generated crate(s) to the specified native
1732 library NAME. The optional KIND can be one of
1733 static, dylib, or framework. If omitted, dylib is
1740 "Comma separated list of types of crates
1741 for the compiler to emit",
1742 "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]",
1747 "Specify the name of the crate being built",
1753 "Specify which edition of the compiler to use when compiling code.",
1759 "Comma separated list of types of output for \
1760 the compiler to emit",
1761 "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]",
1766 "Compiler information to print on stdout",
1767 "[crate-name|file-names|sysroot|cfg|target-list|\
1768 target-cpus|target-features|relocation-models|\
1769 code-models|tls-models|target-spec-json|native-static-libs]",
1771 opt::flagmulti_s("g", "", "Equivalent to -C debuginfo=2"),
1772 opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
1773 opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
1777 "Write output to compiler-chosen filename \
1784 "Provide a detailed explanation of an error \
1788 opt::flag_s("", "test", "Build a test harness"),
1792 "Target triple for which the code is compiled",
1795 opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
1796 opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
1797 opt::multi_s("D", "deny", "Set lint denied", "OPT"),
1798 opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
1802 "Set the most restrictive lint level. \
1803 More restrictive lints are capped at this \
1807 opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
1808 opt::flag_s("V", "version", "Print version info and exit"),
1809 opt::flag_s("v", "verbose", "Use verbose output"),
1813 /// Returns all rustc command line options, including metadata for
1814 /// each option, such as whether the option is part of the stable
1815 /// long-term interface for rustc.
1816 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
1817 let mut opts = rustc_short_optgroups();
1822 "Specify where an external rust library is located",
1828 "Specify where an extern rust library is located, marking it as a private dependency",
1831 opt::opt_s("", "sysroot", "Override the system root", "PATH"),
1832 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
1836 "How errors and other messages are produced",
1842 "Choose `rendered` field of json diagnostics render scheme",
1848 "Configure coloring of output:
1849 auto = colorize, if output goes to a tty (default);
1850 always = always colorize output;
1851 never = never colorize output",
1852 "auto|always|never",
1857 "Pretty-print the input instead of compiling;
1858 valid types are: `normal` (un-annotated source),
1859 `expanded` (crates expanded), or
1860 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
1865 "remap-path-prefix",
1866 "Remap source names in all output (compiler messages and output files)",
1873 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
1874 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
1875 syntax::with_default_globals(move || {
1876 let cfg = cfgspecs.into_iter().map(|s| {
1877 let sess = parse::ParseSess::new(FilePathMapping::empty());
1878 let filename = FileName::cfg_spec_source_code(&s);
1879 let mut parser = parse::new_parser_from_source_str(&sess, filename, s.to_string());
1881 macro_rules! error {($reason: expr) => {
1882 early_error(ErrorOutputType::default(),
1883 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s));
1886 match &mut parser.parse_meta_item() {
1887 Ok(meta_item) if parser.token == token::Eof => {
1888 if meta_item.path.segments.len() != 1 {
1889 error!("argument key must be an identifier");
1891 match &meta_item.node {
1892 MetaItemKind::List(..) => {
1893 error!(r#"expected `key` or `key="value"`"#);
1895 MetaItemKind::NameValue(lit) if !lit.node.is_str() => {
1896 error!("argument value must be a string");
1898 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
1899 let ident = meta_item.ident().expect("multi-segment cfg key");
1900 return (ident.name, meta_item.value_str());
1905 Err(err) => err.cancel(),
1908 error!(r#"expected `key` or `key="value"`"#);
1909 }).collect::<ast::CrateConfig>();
1910 cfg.into_iter().map(|(a, b)| {
1911 (a.to_string(), b.map(|b| b.to_string()))
1916 pub fn get_cmd_lint_options(matches: &getopts::Matches,
1917 error_format: ErrorOutputType)
1918 -> (Vec<(String, lint::Level)>, bool, Option<lint::Level>) {
1919 let mut lint_opts = vec![];
1920 let mut describe_lints = false;
1922 for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
1923 for lint_name in matches.opt_strs(level.as_str()) {
1924 if lint_name == "help" {
1925 describe_lints = true;
1927 lint_opts.push((lint_name.replace("-", "_"), level));
1932 let lint_cap = matches.opt_str("cap-lints").map(|cap| {
1933 lint::Level::from_str(&cap)
1934 .unwrap_or_else(|| early_error(error_format, &format!("unknown lint level: `{}`", cap)))
1936 (lint_opts, describe_lints, lint_cap)
1939 pub fn build_session_options_and_crate_config(
1940 matches: &getopts::Matches,
1941 ) -> (Options, FxHashSet<(String, Option<String>)>) {
1942 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
1943 Some("auto") => ColorConfig::Auto,
1944 Some("always") => ColorConfig::Always,
1945 Some("never") => ColorConfig::Never,
1947 None => ColorConfig::Auto,
1949 Some(arg) => early_error(
1950 ErrorOutputType::default(),
1952 "argument for --color must be auto, \
1953 always or never (instead was `{}`)",
1959 let edition = match matches.opt_str("edition") {
1960 Some(arg) => Edition::from_str(&arg).unwrap_or_else(|_|
1962 ErrorOutputType::default(),
1964 "argument for --edition must be one of: \
1965 {}. (instead was `{}`)",
1971 None => DEFAULT_EDITION,
1974 if !edition.is_stable() && !nightly_options::is_nightly_build() {
1976 ErrorOutputType::default(),
1978 "Edition {} is unstable and only \
1979 available for nightly builds of rustc.",
1985 let json_rendered = matches.opt_str("json-rendered").and_then(|s| match s.as_str() {
1987 "termcolor" => Some(HumanReadableErrorType::Default(ColorConfig::Always)),
1989 ErrorOutputType::default(),
1991 "argument for --json-rendered must be `plain` or `termcolor` (instead was `{}`)",
1995 }).unwrap_or(HumanReadableErrorType::Default(ColorConfig::Never));
1997 // We need the opts_present check because the driver will send us Matches
1998 // with only stable options if no unstable options are used. Since error-format
1999 // is unstable, it will not be present. We have to use opts_present not
2000 // opt_present because the latter will panic.
2001 let error_format = if matches.opts_present(&["error-format".to_owned()]) {
2002 match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
2004 Some("human") => ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color)),
2005 Some("human-annotate-rs") => {
2006 ErrorOutputType::HumanReadable(HumanReadableErrorType::AnnotateRs(color))
2008 Some("json") => ErrorOutputType::Json { pretty: false, json_rendered },
2009 Some("pretty-json") => ErrorOutputType::Json { pretty: true, json_rendered },
2010 Some("short") => ErrorOutputType::HumanReadable(HumanReadableErrorType::Short(color)),
2012 Some(arg) => early_error(
2013 ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color)),
2015 "argument for --error-format must be `human`, `json` or \
2016 `short` (instead was `{}`)",
2022 ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color))
2025 let unparsed_crate_types = matches.opt_strs("crate-type");
2026 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
2027 .unwrap_or_else(|e| early_error(error_format, &e[..]));
2030 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
2032 let mut debugging_opts = build_debugging_options(matches, error_format);
2034 if !debugging_opts.unstable_options {
2035 if matches.opt_str("json-rendered").is_some() {
2036 early_error(error_format, "`--json-rendered=x` is unstable");
2038 if let ErrorOutputType::Json { pretty: true, json_rendered } = error_format {
2040 ErrorOutputType::Json { pretty: false, json_rendered },
2041 "--error-format=pretty-json is unstable",
2044 if let ErrorOutputType::HumanReadable(HumanReadableErrorType::AnnotateRs(_)) =
2047 ErrorOutputType::Json { pretty: false, json_rendered },
2048 "--error-format=human-annotate-rs is unstable",
2053 if debugging_opts.pgo_gen.enabled() && debugging_opts.pgo_use.is_some() {
2056 "options `-Z pgo-gen` and `-Z pgo-use` are exclusive",
2060 let mut output_types = BTreeMap::new();
2061 if !debugging_opts.parse_only {
2062 for list in matches.opt_strs("emit") {
2063 for output_type in list.split(',') {
2064 let mut parts = output_type.splitn(2, '=');
2065 let shorthand = parts.next().unwrap();
2066 let output_type = OutputType::from_shorthand(shorthand).unwrap_or_else(||
2070 "unknown emission type: `{}` - expected one of: {}",
2072 OutputType::shorthands_display(),
2076 let path = parts.next().map(PathBuf::from);
2077 output_types.insert(output_type, path);
2081 if output_types.is_empty() {
2082 output_types.insert(OutputType::Exe, None);
2085 let mut cg = build_codegen_options(matches, error_format);
2086 let mut codegen_units = cg.codegen_units;
2087 let mut disable_thinlto = false;
2089 // Issue #30063: if user requests llvm-related output to one
2090 // particular path, disable codegen-units.
2091 let incompatible: Vec<_> = output_types
2093 .map(|ot_path| ot_path.0)
2094 .filter(|ot| !ot.is_compatible_with_codegen_units_and_single_output_file())
2095 .map(|ot| ot.shorthand())
2097 if !incompatible.is_empty() {
2098 match codegen_units {
2099 Some(n) if n > 1 => {
2100 if matches.opt_present("o") {
2101 for ot in &incompatible {
2105 "--emit={} with -o incompatible with \
2106 -C codegen-units=N for N > 1",
2111 early_warn(error_format, "resetting to default -C codegen-units=1");
2112 codegen_units = Some(1);
2113 disable_thinlto = true;
2117 codegen_units = Some(1);
2118 disable_thinlto = true;
2123 if debugging_opts.threads == Some(0) {
2126 "Value for threads must be a positive nonzero integer",
2130 if debugging_opts.threads.unwrap_or(1) > 1 && debugging_opts.fuel.is_some() {
2133 "Optimization fuel is incompatible with multiple threads",
2137 if codegen_units == Some(0) {
2140 "Value for codegen units must be a positive nonzero integer",
2144 let incremental = match (&debugging_opts.incremental, &cg.incremental) {
2145 (&Some(ref path1), &Some(ref path2)) => {
2150 "conflicting paths for `-Z incremental` and \
2151 `-C incremental` specified: {} versus {}",
2159 (&Some(ref path), &None) => Some(path),
2160 (&None, &Some(ref path)) => Some(path),
2161 (&None, &None) => None,
2162 }.map(|m| PathBuf::from(m));
2164 if debugging_opts.profile && incremental.is_some() {
2167 "can't instrument with gcov profiling when compiling incrementally",
2171 let mut prints = Vec::<PrintRequest>::new();
2172 if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
2173 prints.push(PrintRequest::TargetCPUs);
2174 cg.target_cpu = None;
2176 if cg.target_feature == "help" {
2177 prints.push(PrintRequest::TargetFeatures);
2178 cg.target_feature = String::new();
2180 if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
2181 prints.push(PrintRequest::RelocationModels);
2182 cg.relocation_model = None;
2184 if cg.code_model.as_ref().map_or(false, |s| s == "help") {
2185 prints.push(PrintRequest::CodeModels);
2186 cg.code_model = None;
2191 .map_or(false, |s| s == "help")
2193 prints.push(PrintRequest::TlsModels);
2194 debugging_opts.tls_model = None;
2199 let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
2200 let target_triple = if let Some(target) = matches.opt_str("target") {
2201 if target.ends_with(".json") {
2202 let path = Path::new(&target);
2203 TargetTriple::from_path(&path).unwrap_or_else(|_|
2204 early_error(error_format, &format!("target file {:?} does not exist", path)))
2206 TargetTriple::TargetTriple(target)
2209 TargetTriple::from_triple(host_triple())
2212 // The `-O` and `-C opt-level` flags specify the same setting, so we want to be able
2213 // to use them interchangeably. However, because they're technically different flags,
2214 // we need to work out manually which should take precedence if both are supplied (i.e.
2215 // the rightmost flag). We do this by finding the (rightmost) position of both flags and
2216 // comparing them. Note that if a flag is not found, its position will be `None`, which
2217 // always compared less than `Some(_)`.
2218 let max_o = matches.opt_positions("O").into_iter().max();
2219 let max_c = matches.opt_strs_pos("C").into_iter().flat_map(|(i, s)| {
2220 if let Some("opt-level") = s.splitn(2, '=').next() {
2229 match cg.opt_level.as_ref().map(String::as_ref) {
2230 None => OptLevel::No,
2231 Some("0") => OptLevel::No,
2232 Some("1") => OptLevel::Less,
2233 Some("2") => OptLevel::Default,
2234 Some("3") => OptLevel::Aggressive,
2235 Some("s") => OptLevel::Size,
2236 Some("z") => OptLevel::SizeMin,
2241 "optimization level needs to be \
2242 between 0-3, s or z (instead was `{}`)",
2250 // The `-g` and `-C debuginfo` flags specify the same setting, so we want to be able
2251 // to use them interchangeably. See the note above (regarding `-O` and `-C opt-level`)
2252 // for more details.
2253 let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
2254 let max_g = matches.opt_positions("g").into_iter().max();
2255 let max_c = matches.opt_strs_pos("C").into_iter().flat_map(|(i, s)| {
2256 if let Some("debuginfo") = s.splitn(2, '=').next() {
2262 let debuginfo = if max_g > max_c {
2265 match cg.debuginfo {
2266 None | Some(0) => DebugInfo::None,
2267 Some(1) => DebugInfo::Limited,
2268 Some(2) => DebugInfo::Full,
2273 "debug info level needs to be between \
2274 0-2 (instead was `{}`)",
2282 let mut search_paths = vec![];
2283 for s in &matches.opt_strs("L") {
2284 search_paths.push(SearchPath::from_cli_opt(&s[..], error_format));
2291 // Parse string of the form "[KIND=]lib[:new_name]",
2292 // where KIND is one of "dylib", "framework", "static".
2293 let mut parts = s.splitn(2, '=');
2294 let kind = parts.next().unwrap();
2295 let (name, kind) = match (parts.next(), kind) {
2296 (None, name) => (name, None),
2297 (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
2298 (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
2299 (Some(name), "static") => (name, Some(cstore::NativeStatic)),
2300 (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
2305 "unknown library kind `{}`, expected \
2306 one of dylib, framework, or static",
2312 if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
2316 "the library kind 'static-nobundle' is only \
2317 accepted on the nightly compiler"
2321 let mut name_parts = name.splitn(2, ':');
2322 let name = name_parts.next().unwrap();
2323 let new_name = name_parts.next();
2324 (name.to_owned(), new_name.map(|n| n.to_owned()), kind)
2328 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
2329 let test = matches.opt_present("test");
2331 let is_unstable_enabled = nightly_options::is_unstable_enabled(matches);
2333 prints.extend(matches.opt_strs("print").into_iter().map(|s| match &*s {
2334 "crate-name" => PrintRequest::CrateName,
2335 "file-names" => PrintRequest::FileNames,
2336 "sysroot" => PrintRequest::Sysroot,
2337 "cfg" => PrintRequest::Cfg,
2338 "target-list" => PrintRequest::TargetList,
2339 "target-cpus" => PrintRequest::TargetCPUs,
2340 "target-features" => PrintRequest::TargetFeatures,
2341 "relocation-models" => PrintRequest::RelocationModels,
2342 "code-models" => PrintRequest::CodeModels,
2343 "tls-models" => PrintRequest::TlsModels,
2344 "native-static-libs" => PrintRequest::NativeStaticLibs,
2345 "target-spec-json" => {
2346 if is_unstable_enabled {
2347 PrintRequest::TargetSpec
2351 "the `-Z unstable-options` flag must also be passed to \
2352 enable the target-spec-json print option",
2356 req => early_error(error_format, &format!("unknown print request `{}`", req)),
2359 let borrowck_mode = match debugging_opts.borrowck.as_ref().map(|s| &s[..]) {
2360 None | Some("migrate") => BorrowckMode::Migrate,
2361 Some("mir") => BorrowckMode::Mir,
2362 Some(m) => early_error(error_format, &format!("unknown borrowck mode `{}`", m)),
2365 if !cg.remark.is_empty() && debuginfo == DebugInfo::None {
2368 "-C remark requires \"-C debuginfo=n\" to show source locations",
2372 if matches.opt_present("extern-private") && !debugging_opts.unstable_options {
2374 ErrorOutputType::default(),
2375 "'--extern-private' is unstable and only \
2376 available for nightly builds of rustc."
2380 // We start out with a Vec<(Option<String>, bool)>>,
2381 // and later convert it into a BTreeSet<(Option<String>, bool)>
2382 // This allows to modify entries in-place to set their correct
2384 let mut externs: BTreeMap<String, ExternEntry> = BTreeMap::new();
2385 for (arg, private) in matches.opt_strs("extern").into_iter().map(|v| (v, false))
2386 .chain(matches.opt_strs("extern-private").into_iter().map(|v| (v, true))) {
2388 let mut parts = arg.splitn(2, '=');
2389 let name = parts.next().unwrap_or_else(||
2390 early_error(error_format, "--extern value must not be empty"));
2391 let location = parts.next().map(|s| s.to_string());
2392 if location.is_none() && !is_unstable_enabled {
2395 "the `-Z unstable-options` flag must also be passed to \
2396 enable `--extern crate_name` without `=path`",
2401 .entry(name.to_owned())
2405 entry.locations.insert(location.clone());
2407 // Crates start out being not private,
2408 // and go to being private if we see an '--extern-private'
2410 entry.is_private_dep |= private;
2413 let crate_name = matches.opt_str("crate-name");
2415 let remap_path_prefix = matches
2416 .opt_strs("remap-path-prefix")
2419 let mut parts = remap.rsplitn(2, '='); // reverse iterator
2420 let to = parts.next();
2421 let from = parts.next();
2423 (Some(from), Some(to)) => (PathBuf::from(from), PathBuf::from(to)),
2426 "--remap-path-prefix must contain '=' between FROM and TO",
2435 optimize: opt_level,
2440 output_types: OutputTypes(output_types),
2442 maybe_sysroot: sysroot_opt,
2451 externs: Externs(externs),
2455 unstable_features: UnstableFeatures::from_environment(),
2457 actually_rustdoc: false,
2458 cli_forced_codegen_units: codegen_units,
2459 cli_forced_thinlto_off: disable_thinlto,
2467 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
2468 let mut crate_types: Vec<CrateType> = Vec::new();
2469 for unparsed_crate_type in &list_list {
2470 for part in unparsed_crate_type.split(',') {
2471 let new_part = match part {
2472 "lib" => default_lib_output(),
2473 "rlib" => CrateType::Rlib,
2474 "staticlib" => CrateType::Staticlib,
2475 "dylib" => CrateType::Dylib,
2476 "cdylib" => CrateType::Cdylib,
2477 "bin" => CrateType::Executable,
2478 "proc-macro" => CrateType::ProcMacro,
2479 _ => return Err(format!("unknown crate type: `{}`", part))
2481 if !crate_types.contains(&new_part) {
2482 crate_types.push(new_part)
2490 pub mod nightly_options {
2492 use syntax::feature_gate::UnstableFeatures;
2493 use super::{ErrorOutputType, OptionStability, RustcOptGroup};
2494 use crate::session::early_error;
2496 pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
2501 .any(|x| *x == "unstable-options")
2504 pub fn is_nightly_build() -> bool {
2505 UnstableFeatures::from_environment().is_nightly_build()
2508 pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
2509 let has_z_unstable_option = matches
2512 .any(|x| *x == "unstable-options");
2513 let really_allows_unstable_options =
2514 UnstableFeatures::from_environment().is_nightly_build();
2516 for opt in flags.iter() {
2517 if opt.stability == OptionStability::Stable {
2520 if !matches.opt_present(opt.name) {
2523 if opt.name != "Z" && !has_z_unstable_option {
2525 ErrorOutputType::default(),
2527 "the `-Z unstable-options` flag must also be passed to enable \
2533 if really_allows_unstable_options {
2536 match opt.stability {
2537 OptionStability::Unstable => {
2539 "the option `{}` is only accepted on the \
2543 early_error(ErrorOutputType::default(), &msg);
2545 OptionStability::Stable => {}
2551 impl fmt::Display for CrateType {
2552 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2554 CrateType::Executable => "bin".fmt(f),
2555 CrateType::Dylib => "dylib".fmt(f),
2556 CrateType::Rlib => "rlib".fmt(f),
2557 CrateType::Staticlib => "staticlib".fmt(f),
2558 CrateType::Cdylib => "cdylib".fmt(f),
2559 CrateType::ProcMacro => "proc-macro".fmt(f),
2564 /// Command-line arguments passed to the compiler have to be incorporated with
2565 /// the dependency tracking system for incremental compilation. This module
2566 /// provides some utilities to make this more convenient.
2568 /// The values of all command-line arguments that are relevant for dependency
2569 /// tracking are hashed into a single value that determines whether the
2570 /// incremental compilation cache can be re-used or not. This hashing is done
2571 /// via the DepTrackingHash trait defined below, since the standard Hash
2572 /// implementation might not be suitable (e.g., arguments are stored in a Vec,
2573 /// the hash of which is order dependent, but we might not want the order of
2574 /// arguments to make a difference for the hash).
2576 /// However, since the value provided by Hash::hash often *is* suitable,
2577 /// especially for primitive types, there is the
2578 /// impl_dep_tracking_hash_via_hash!() macro that allows to simply reuse the
2579 /// Hash implementation for DepTrackingHash. It's important though that
2580 /// we have an opt-in scheme here, so one is hopefully forced to think about
2581 /// how the hash should be calculated when adding a new command-line argument.
2584 use crate::middle::cstore;
2585 use std::collections::BTreeMap;
2586 use std::hash::Hash;
2587 use std::path::PathBuf;
2588 use std::collections::hash_map::DefaultHasher;
2589 use super::{CrateType, DebugInfo, ErrorOutputType, OptLevel, OutputTypes,
2590 Passes, Sanitizer, LtoCli, LinkerPluginLto, SwitchWithOptPath,
2591 SymbolManglingVersion};
2592 use syntax::feature_gate::UnstableFeatures;
2593 use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel, TargetTriple};
2594 use syntax::edition::Edition;
2596 pub trait DepTrackingHash {
2597 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);
2600 macro_rules! impl_dep_tracking_hash_via_hash {
2602 impl DepTrackingHash for $t {
2603 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
2604 Hash::hash(self, hasher);
2610 macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
2612 impl DepTrackingHash for Vec<$t> {
2613 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2614 let mut elems: Vec<&$t> = self.iter().collect();
2616 Hash::hash(&elems.len(), hasher);
2617 for (index, elem) in elems.iter().enumerate() {
2618 Hash::hash(&index, hasher);
2619 DepTrackingHash::hash(*elem, hasher, error_format);
2626 impl_dep_tracking_hash_via_hash!(bool);
2627 impl_dep_tracking_hash_via_hash!(usize);
2628 impl_dep_tracking_hash_via_hash!(u64);
2629 impl_dep_tracking_hash_via_hash!(String);
2630 impl_dep_tracking_hash_via_hash!(PathBuf);
2631 impl_dep_tracking_hash_via_hash!(lint::Level);
2632 impl_dep_tracking_hash_via_hash!(Option<bool>);
2633 impl_dep_tracking_hash_via_hash!(Option<usize>);
2634 impl_dep_tracking_hash_via_hash!(Option<String>);
2635 impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
2636 impl_dep_tracking_hash_via_hash!(Option<Vec<String>>);
2637 impl_dep_tracking_hash_via_hash!(Option<MergeFunctions>);
2638 impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
2639 impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
2640 impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
2641 impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
2642 impl_dep_tracking_hash_via_hash!(Option<cstore::NativeLibraryKind>);
2643 impl_dep_tracking_hash_via_hash!(CrateType);
2644 impl_dep_tracking_hash_via_hash!(MergeFunctions);
2645 impl_dep_tracking_hash_via_hash!(PanicStrategy);
2646 impl_dep_tracking_hash_via_hash!(RelroLevel);
2647 impl_dep_tracking_hash_via_hash!(Passes);
2648 impl_dep_tracking_hash_via_hash!(OptLevel);
2649 impl_dep_tracking_hash_via_hash!(LtoCli);
2650 impl_dep_tracking_hash_via_hash!(DebugInfo);
2651 impl_dep_tracking_hash_via_hash!(UnstableFeatures);
2652 impl_dep_tracking_hash_via_hash!(OutputTypes);
2653 impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
2654 impl_dep_tracking_hash_via_hash!(Sanitizer);
2655 impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
2656 impl_dep_tracking_hash_via_hash!(TargetTriple);
2657 impl_dep_tracking_hash_via_hash!(Edition);
2658 impl_dep_tracking_hash_via_hash!(LinkerPluginLto);
2659 impl_dep_tracking_hash_via_hash!(SwitchWithOptPath);
2660 impl_dep_tracking_hash_via_hash!(SymbolManglingVersion);
2662 impl_dep_tracking_hash_for_sortable_vec_of!(String);
2663 impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
2664 impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
2665 impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
2666 impl_dep_tracking_hash_for_sortable_vec_of!((
2669 Option<cstore::NativeLibraryKind>
2671 impl_dep_tracking_hash_for_sortable_vec_of!((String, u64));
2673 impl<T1, T2> DepTrackingHash for (T1, T2)
2675 T1: DepTrackingHash,
2676 T2: DepTrackingHash,
2678 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2679 Hash::hash(&0, hasher);
2680 DepTrackingHash::hash(&self.0, hasher, error_format);
2681 Hash::hash(&1, hasher);
2682 DepTrackingHash::hash(&self.1, hasher, error_format);
2686 impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
2688 T1: DepTrackingHash,
2689 T2: DepTrackingHash,
2690 T3: DepTrackingHash,
2692 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2693 Hash::hash(&0, hasher);
2694 DepTrackingHash::hash(&self.0, hasher, error_format);
2695 Hash::hash(&1, hasher);
2696 DepTrackingHash::hash(&self.1, hasher, error_format);
2697 Hash::hash(&2, hasher);
2698 DepTrackingHash::hash(&self.2, hasher, error_format);
2702 // This is a stable hash because BTreeMap is a sorted container
2704 sub_hashes: BTreeMap<&'static str, &dyn DepTrackingHash>,
2705 hasher: &mut DefaultHasher,
2706 error_format: ErrorOutputType,
2708 for (key, sub_hash) in sub_hashes {
2709 // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
2710 // the keys, as they are just plain strings
2711 Hash::hash(&key.len(), hasher);
2712 Hash::hash(key, hasher);
2713 sub_hash.hash(hasher, error_format);
2722 use crate::middle::cstore;
2723 use crate::session::config::{
2724 build_configuration,
2725 build_session_options_and_crate_config,
2728 use crate::session::config::{LtoCli, LinkerPluginLto, SwitchWithOptPath, ExternEntry};
2729 use crate::session::build_session;
2730 use crate::session::search_paths::SearchPath;
2731 use std::collections::{BTreeMap, BTreeSet};
2732 use std::iter::FromIterator;
2733 use std::path::PathBuf;
2734 use super::{Externs, OutputType, OutputTypes, SymbolManglingVersion};
2735 use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel};
2736 use syntax::symbol::sym;
2737 use syntax::edition::{Edition, DEFAULT_EDITION};
2742 fn new_public<S: Into<String>,
2743 I: IntoIterator<Item = Option<S>>>(locations: I) -> ExternEntry {
2744 let locations: BTreeSet<_> = locations.into_iter().map(|o| o.map(|s| s.into()))
2749 is_private_dep: false
2754 fn optgroups() -> getopts::Options {
2755 let mut opts = getopts::Options::new();
2756 for group in super::rustc_optgroups() {
2757 (group.apply)(&mut opts);
2762 fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
2763 BTreeMap::from_iter(entries.into_iter())
2766 // When the user supplies --test we should implicitly supply --cfg test
2768 fn test_switch_implies_cfg_test() {
2769 syntax::with_default_globals(|| {
2770 let matches = &match optgroups().parse(&["--test".to_string()]) {
2772 Err(f) => panic!("test_switch_implies_cfg_test: {}", f),
2774 let registry = errors::registry::Registry::new(&[]);
2775 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2776 let sess = build_session(sessopts, None, registry);
2777 let cfg = build_configuration(&sess, to_crate_config(cfg));
2778 assert!(cfg.contains(&(sym::test, None)));
2782 // When the user supplies --test and --cfg test, don't implicitly add
2783 // another --cfg test
2785 fn test_switch_implies_cfg_test_unless_cfg_test() {
2786 syntax::with_default_globals(|| {
2787 let matches = &match optgroups().parse(&["--test".to_string(),
2788 "--cfg=test".to_string()]) {
2790 Err(f) => panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f),
2792 let registry = errors::registry::Registry::new(&[]);
2793 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2794 let sess = build_session(sessopts, None, registry);
2795 let cfg = build_configuration(&sess, to_crate_config(cfg));
2796 let mut test_items = cfg.iter().filter(|&&(name, _)| name == sym::test);
2797 assert!(test_items.next().is_some());
2798 assert!(test_items.next().is_none());
2803 fn test_can_print_warnings() {
2804 syntax::with_default_globals(|| {
2805 let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
2806 let registry = errors::registry::Registry::new(&[]);
2807 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2808 let sess = build_session(sessopts, None, registry);
2809 assert!(!sess.diagnostic().flags.can_emit_warnings);
2812 syntax::with_default_globals(|| {
2813 let matches = optgroups()
2814 .parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()])
2816 let registry = errors::registry::Registry::new(&[]);
2817 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2818 let sess = build_session(sessopts, None, registry);
2819 assert!(sess.diagnostic().flags.can_emit_warnings);
2822 syntax::with_default_globals(|| {
2823 let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
2824 let registry = errors::registry::Registry::new(&[]);
2825 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2826 let sess = build_session(sessopts, None, registry);
2827 assert!(sess.diagnostic().flags.can_emit_warnings);
2832 fn test_output_types_tracking_hash_different_paths() {
2833 let mut v1 = Options::default();
2834 let mut v2 = Options::default();
2835 let mut v3 = Options::default();
2838 OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("./some/thing")))]);
2840 OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("/some/thing")))]);
2841 v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
2843 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2844 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2845 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2848 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2849 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2850 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2854 fn test_output_types_tracking_hash_different_construction_order() {
2855 let mut v1 = Options::default();
2856 let mut v2 = Options::default();
2858 v1.output_types = OutputTypes::new(&[
2859 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2860 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2863 v2.output_types = OutputTypes::new(&[
2864 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2865 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2868 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2871 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2875 fn test_externs_tracking_hash_different_construction_order() {
2876 let mut v1 = Options::default();
2877 let mut v2 = Options::default();
2878 let mut v3 = Options::default();
2880 v1.externs = Externs::new(mk_map(vec![
2883 ExternEntry::new_public(vec![Some("b"), Some("c")])
2887 ExternEntry::new_public(vec![Some("e"), Some("f")])
2891 v2.externs = Externs::new(mk_map(vec![
2894 ExternEntry::new_public(vec![Some("e"), Some("f")])
2898 ExternEntry::new_public(vec![Some("b"), Some("c")])
2902 v3.externs = Externs::new(mk_map(vec![
2905 ExternEntry::new_public(vec![Some("b"), Some("c")])
2909 ExternEntry::new_public(vec![Some("f"), Some("e")])
2913 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2914 assert_eq!(v1.dep_tracking_hash(), v3.dep_tracking_hash());
2915 assert_eq!(v2.dep_tracking_hash(), v3.dep_tracking_hash());
2918 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2919 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2920 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2924 fn test_lints_tracking_hash_different_values() {
2925 let mut v1 = Options::default();
2926 let mut v2 = Options::default();
2927 let mut v3 = Options::default();
2929 v1.lint_opts = vec![
2930 (String::from("a"), lint::Allow),
2931 (String::from("b"), lint::Warn),
2932 (String::from("c"), lint::Deny),
2933 (String::from("d"), lint::Forbid),
2936 v2.lint_opts = vec![
2937 (String::from("a"), lint::Allow),
2938 (String::from("b"), lint::Warn),
2939 (String::from("X"), lint::Deny),
2940 (String::from("d"), lint::Forbid),
2943 v3.lint_opts = vec![
2944 (String::from("a"), lint::Allow),
2945 (String::from("b"), lint::Warn),
2946 (String::from("c"), lint::Forbid),
2947 (String::from("d"), lint::Deny),
2950 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2951 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2952 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2955 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2956 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2957 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2961 fn test_lints_tracking_hash_different_construction_order() {
2962 let mut v1 = Options::default();
2963 let mut v2 = Options::default();
2965 v1.lint_opts = vec![
2966 (String::from("a"), lint::Allow),
2967 (String::from("b"), lint::Warn),
2968 (String::from("c"), lint::Deny),
2969 (String::from("d"), lint::Forbid),
2972 v2.lint_opts = vec![
2973 (String::from("a"), lint::Allow),
2974 (String::from("c"), lint::Deny),
2975 (String::from("b"), lint::Warn),
2976 (String::from("d"), lint::Forbid),
2979 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2982 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2983 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2987 fn test_search_paths_tracking_hash_different_order() {
2988 let mut v1 = Options::default();
2989 let mut v2 = Options::default();
2990 let mut v3 = Options::default();
2991 let mut v4 = Options::default();
2993 const JSON: super::ErrorOutputType = super::ErrorOutputType::Json {
2995 json_rendered: super::HumanReadableErrorType::Default(super::ColorConfig::Never),
3000 .push(SearchPath::from_cli_opt("native=abc", JSON));
3002 .push(SearchPath::from_cli_opt("crate=def", JSON));
3004 .push(SearchPath::from_cli_opt("dependency=ghi", JSON));
3006 .push(SearchPath::from_cli_opt("framework=jkl", JSON));
3008 .push(SearchPath::from_cli_opt("all=mno", JSON));
3011 .push(SearchPath::from_cli_opt("native=abc", JSON));
3013 .push(SearchPath::from_cli_opt("dependency=ghi", JSON));
3015 .push(SearchPath::from_cli_opt("crate=def", JSON));
3017 .push(SearchPath::from_cli_opt("framework=jkl", JSON));
3019 .push(SearchPath::from_cli_opt("all=mno", JSON));
3022 .push(SearchPath::from_cli_opt("crate=def", JSON));
3024 .push(SearchPath::from_cli_opt("framework=jkl", JSON));
3026 .push(SearchPath::from_cli_opt("native=abc", JSON));
3028 .push(SearchPath::from_cli_opt("dependency=ghi", JSON));
3030 .push(SearchPath::from_cli_opt("all=mno", JSON));
3033 .push(SearchPath::from_cli_opt("all=mno", JSON));
3035 .push(SearchPath::from_cli_opt("native=abc", JSON));
3037 .push(SearchPath::from_cli_opt("crate=def", JSON));
3039 .push(SearchPath::from_cli_opt("dependency=ghi", JSON));
3041 .push(SearchPath::from_cli_opt("framework=jkl", JSON));
3043 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
3044 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
3045 assert!(v1.dep_tracking_hash() == v4.dep_tracking_hash());
3048 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
3049 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
3050 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
3051 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
3055 fn test_native_libs_tracking_hash_different_values() {
3056 let mut v1 = Options::default();
3057 let mut v2 = Options::default();
3058 let mut v3 = Options::default();
3059 let mut v4 = Options::default();
3063 (String::from("a"), None, Some(cstore::NativeStatic)),
3064 (String::from("b"), None, Some(cstore::NativeFramework)),
3065 (String::from("c"), None, Some(cstore::NativeUnknown)),
3070 (String::from("a"), None, Some(cstore::NativeStatic)),
3071 (String::from("X"), None, Some(cstore::NativeFramework)),
3072 (String::from("c"), None, Some(cstore::NativeUnknown)),
3077 (String::from("a"), None, Some(cstore::NativeStatic)),
3078 (String::from("b"), None, Some(cstore::NativeStatic)),
3079 (String::from("c"), None, Some(cstore::NativeUnknown)),
3084 (String::from("a"), None, Some(cstore::NativeStatic)),
3087 Some(String::from("X")),
3088 Some(cstore::NativeFramework),
3090 (String::from("c"), None, Some(cstore::NativeUnknown)),
3093 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
3094 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
3095 assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
3098 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
3099 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
3100 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
3101 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
3105 fn test_native_libs_tracking_hash_different_order() {
3106 let mut v1 = Options::default();
3107 let mut v2 = Options::default();
3108 let mut v3 = Options::default();
3112 (String::from("a"), None, Some(cstore::NativeStatic)),
3113 (String::from("b"), None, Some(cstore::NativeFramework)),
3114 (String::from("c"), None, Some(cstore::NativeUnknown)),
3118 (String::from("b"), None, Some(cstore::NativeFramework)),
3119 (String::from("a"), None, Some(cstore::NativeStatic)),
3120 (String::from("c"), None, Some(cstore::NativeUnknown)),
3124 (String::from("c"), None, Some(cstore::NativeUnknown)),
3125 (String::from("a"), None, Some(cstore::NativeStatic)),
3126 (String::from("b"), None, Some(cstore::NativeFramework)),
3129 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
3130 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
3131 assert!(v2.dep_tracking_hash() == v3.dep_tracking_hash());
3134 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
3135 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
3136 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
3140 fn test_codegen_options_tracking_hash() {
3141 let reference = Options::default();
3142 let mut opts = Options::default();
3144 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
3145 opts.cg.ar = Some(String::from("abc"));
3146 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3148 opts.cg.linker = Some(PathBuf::from("linker"));
3149 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3151 opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
3152 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3154 opts.cg.link_dead_code = true;
3155 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3157 opts.cg.rpath = true;
3158 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3160 opts.cg.extra_filename = String::from("extra-filename");
3161 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3163 opts.cg.codegen_units = Some(42);
3164 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3166 opts.cg.remark = super::Passes::Some(vec![String::from("pass1"), String::from("pass2")]);
3167 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3169 opts.cg.save_temps = true;
3170 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3172 opts.cg.incremental = Some(String::from("abc"));
3173 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3175 // Make sure changing a [TRACKED] option changes the hash
3176 opts = reference.clone();
3177 opts.cg.lto = LtoCli::Fat;
3178 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3180 opts = reference.clone();
3181 opts.cg.target_cpu = Some(String::from("abc"));
3182 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3184 opts = reference.clone();
3185 opts.cg.target_feature = String::from("all the features, all of them");
3186 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3188 opts = reference.clone();
3189 opts.cg.passes = vec![String::from("1"), String::from("2")];
3190 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3192 opts = reference.clone();
3193 opts.cg.llvm_args = vec![String::from("1"), String::from("2")];
3194 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3196 opts = reference.clone();
3197 opts.cg.overflow_checks = Some(true);
3198 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3200 opts = reference.clone();
3201 opts.cg.no_prepopulate_passes = true;
3202 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3204 opts = reference.clone();
3205 opts.cg.no_vectorize_loops = true;
3206 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3208 opts = reference.clone();
3209 opts.cg.no_vectorize_slp = true;
3210 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3212 opts = reference.clone();
3213 opts.cg.soft_float = true;
3214 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3216 opts = reference.clone();
3217 opts.cg.prefer_dynamic = true;
3218 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3220 opts = reference.clone();
3221 opts.cg.no_integrated_as = true;
3222 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3224 opts = reference.clone();
3225 opts.cg.no_redzone = Some(true);
3226 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3228 opts = reference.clone();
3229 opts.cg.relocation_model = Some(String::from("relocation model"));
3230 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3232 opts = reference.clone();
3233 opts.cg.code_model = Some(String::from("code model"));
3234 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3236 opts = reference.clone();
3237 opts.debugging_opts.tls_model = Some(String::from("tls model"));
3238 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3240 opts = reference.clone();
3241 opts.debugging_opts.pgo_gen = SwitchWithOptPath::Enabled(None);
3242 assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3244 opts = reference.clone();
3245 opts.debugging_opts.pgo_use = Some(PathBuf::from("abc"));
3246 assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3248 opts = reference.clone();
3249 opts.cg.metadata = vec![String::from("A"), String::from("B")];
3250 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3252 opts = reference.clone();
3253 opts.cg.debuginfo = Some(0xdeadbeef);
3254 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3256 opts = reference.clone();
3257 opts.cg.debuginfo = Some(0xba5eba11);
3258 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3260 opts = reference.clone();
3261 opts.cg.force_frame_pointers = Some(false);
3262 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3264 opts = reference.clone();
3265 opts.cg.debug_assertions = Some(true);
3266 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3268 opts = reference.clone();
3269 opts.cg.inline_threshold = Some(0xf007ba11);
3270 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3272 opts = reference.clone();
3273 opts.cg.panic = Some(PanicStrategy::Abort);
3274 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3276 opts = reference.clone();
3277 opts.cg.linker_plugin_lto = LinkerPluginLto::LinkerPluginAuto;
3278 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3282 fn test_debugging_options_tracking_hash() {
3283 let reference = Options::default();
3284 let mut opts = Options::default();
3286 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
3287 opts.debugging_opts.verbose = true;
3288 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3289 opts.debugging_opts.time_passes = true;
3290 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3291 opts.debugging_opts.time_llvm_passes = true;
3292 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3293 opts.debugging_opts.input_stats = true;
3294 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3295 opts.debugging_opts.borrowck_stats = true;
3296 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3297 opts.debugging_opts.meta_stats = true;
3298 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3299 opts.debugging_opts.print_link_args = true;
3300 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3301 opts.debugging_opts.print_llvm_passes = true;
3302 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3303 opts.debugging_opts.ast_json = true;
3304 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3305 opts.debugging_opts.ast_json_noexpand = true;
3306 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3307 opts.debugging_opts.ls = true;
3308 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3309 opts.debugging_opts.save_analysis = true;
3310 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3311 opts.debugging_opts.flowgraph_print_loans = true;
3312 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3313 opts.debugging_opts.flowgraph_print_moves = true;
3314 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3315 opts.debugging_opts.flowgraph_print_assigns = true;
3316 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3317 opts.debugging_opts.flowgraph_print_all = true;
3318 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3319 opts.debugging_opts.print_region_graph = true;
3320 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3321 opts.debugging_opts.parse_only = true;
3322 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3323 opts.debugging_opts.incremental = Some(String::from("abc"));
3324 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3325 opts.debugging_opts.dump_dep_graph = true;
3326 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3327 opts.debugging_opts.query_dep_graph = true;
3328 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3329 opts.debugging_opts.no_analysis = true;
3330 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3331 opts.debugging_opts.unstable_options = true;
3332 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3333 opts.debugging_opts.trace_macros = true;
3334 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3335 opts.debugging_opts.keep_hygiene_data = true;
3336 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3337 opts.debugging_opts.keep_ast = true;
3338 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3339 opts.debugging_opts.print_mono_items = Some(String::from("abc"));
3340 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3341 opts.debugging_opts.dump_mir = Some(String::from("abc"));
3342 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3343 opts.debugging_opts.dump_mir_dir = String::from("abc");
3344 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3345 opts.debugging_opts.dump_mir_graphviz = true;
3346 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3348 // Make sure changing a [TRACKED] option changes the hash
3349 opts = reference.clone();
3350 opts.debugging_opts.asm_comments = true;
3351 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3353 opts = reference.clone();
3354 opts.debugging_opts.verify_llvm_ir = true;
3355 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3357 opts = reference.clone();
3358 opts.debugging_opts.no_landing_pads = true;
3359 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3361 opts = reference.clone();
3362 opts.debugging_opts.fewer_names = true;
3363 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3365 opts = reference.clone();
3366 opts.debugging_opts.no_codegen = true;
3367 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3369 opts = reference.clone();
3370 opts.debugging_opts.treat_err_as_bug = Some(1);
3371 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3373 opts = reference.clone();
3374 opts.debugging_opts.report_delayed_bugs = true;
3375 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3377 opts = reference.clone();
3378 opts.debugging_opts.continue_parse_after_error = true;
3379 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3381 opts = reference.clone();
3382 opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
3383 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3385 opts = reference.clone();
3386 opts.debugging_opts.force_overflow_checks = Some(true);
3387 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3389 opts = reference.clone();
3390 opts.debugging_opts.show_span = Some(String::from("abc"));
3391 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3393 opts = reference.clone();
3394 opts.debugging_opts.mir_opt_level = 3;
3395 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3397 opts = reference.clone();
3398 opts.debugging_opts.relro_level = Some(RelroLevel::Full);
3399 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3401 opts = reference.clone();
3402 opts.debugging_opts.merge_functions = Some(MergeFunctions::Disabled);
3403 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3405 opts = reference.clone();
3406 opts.debugging_opts.allow_features = Some(vec![String::from("lang_items")]);
3407 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3409 opts = reference.clone();
3410 opts.debugging_opts.symbol_mangling_version = SymbolManglingVersion::V0;
3411 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3415 fn test_edition_parsing() {
3416 // test default edition
3417 let options = Options::default();
3418 assert!(options.edition == DEFAULT_EDITION);
3420 let matches = optgroups()
3421 .parse(&["--edition=2018".to_string()])
3423 let (sessopts, _) = build_session_options_and_crate_config(&matches);
3424 assert!(sessopts.edition == Edition::Edition2018)