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(Clone, Copy, PartialEq, Hash)]
141 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
142 pub enum OutputType {
153 impl_stable_hash_via_hash!(OutputType);
156 fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
158 OutputType::Exe | OutputType::DepInfo | OutputType::Metadata => true,
160 | OutputType::Assembly
161 | OutputType::LlvmAssembly
163 | OutputType::Object => false,
167 fn shorthand(&self) -> &'static str {
169 OutputType::Bitcode => "llvm-bc",
170 OutputType::Assembly => "asm",
171 OutputType::LlvmAssembly => "llvm-ir",
172 OutputType::Mir => "mir",
173 OutputType::Object => "obj",
174 OutputType::Metadata => "metadata",
175 OutputType::Exe => "link",
176 OutputType::DepInfo => "dep-info",
180 fn from_shorthand(shorthand: &str) -> Option<Self> {
181 Some(match shorthand {
182 "asm" => OutputType::Assembly,
183 "llvm-ir" => OutputType::LlvmAssembly,
184 "mir" => OutputType::Mir,
185 "llvm-bc" => OutputType::Bitcode,
186 "obj" => OutputType::Object,
187 "metadata" => OutputType::Metadata,
188 "link" => OutputType::Exe,
189 "dep-info" => OutputType::DepInfo,
194 fn shorthands_display() -> String {
196 "`{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`",
197 OutputType::Bitcode.shorthand(),
198 OutputType::Assembly.shorthand(),
199 OutputType::LlvmAssembly.shorthand(),
200 OutputType::Mir.shorthand(),
201 OutputType::Object.shorthand(),
202 OutputType::Metadata.shorthand(),
203 OutputType::Exe.shorthand(),
204 OutputType::DepInfo.shorthand(),
208 pub fn extension(&self) -> &'static str {
210 OutputType::Bitcode => "bc",
211 OutputType::Assembly => "s",
212 OutputType::LlvmAssembly => "ll",
213 OutputType::Mir => "mir",
214 OutputType::Object => "o",
215 OutputType::Metadata => "rmeta",
216 OutputType::DepInfo => "d",
217 OutputType::Exe => "",
222 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
223 pub enum ErrorOutputType {
224 HumanReadable(HumanReadableErrorType),
226 /// Render the json in a human readable way (with indents and newlines)
228 /// The way the `rendered` field is created
229 json_rendered: HumanReadableErrorType,
233 impl Default for ErrorOutputType {
234 fn default() -> ErrorOutputType {
235 ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(ColorConfig::Auto))
239 // Use tree-based collections to cheaply get a deterministic Hash implementation.
240 // DO NOT switch BTreeMap out for an unsorted container type! That would break
241 // dependency tracking for command-line arguments.
242 #[derive(Clone, Hash)]
243 pub struct OutputTypes(BTreeMap<OutputType, Option<PathBuf>>);
245 impl_stable_hash_via_hash!(OutputTypes);
248 pub fn new(entries: &[(OutputType, Option<PathBuf>)]) -> OutputTypes {
249 OutputTypes(BTreeMap::from_iter(
250 entries.iter().map(|&(k, ref v)| (k, v.clone())),
254 pub fn get(&self, key: &OutputType) -> Option<&Option<PathBuf>> {
258 pub fn contains_key(&self, key: &OutputType) -> bool {
259 self.0.contains_key(key)
262 pub fn keys<'a>(&'a self) -> BTreeMapKeysIter<'a, OutputType, Option<PathBuf>> {
266 pub fn values<'a>(&'a self) -> BTreeMapValuesIter<'a, OutputType, Option<PathBuf>> {
270 pub fn len(&self) -> usize {
274 // True if any of the output types require codegen or linking.
275 pub fn should_codegen(&self) -> bool {
276 self.0.keys().any(|k| match *k {
278 | OutputType::Assembly
279 | OutputType::LlvmAssembly
282 | OutputType::Exe => true,
283 OutputType::Metadata | OutputType::DepInfo => false,
288 // Use tree-based collections to cheaply get a deterministic Hash implementation.
289 // DO NOT switch BTreeMap or BTreeSet out for an unsorted container type! That
290 // would break dependency tracking for command-line arguments.
291 #[derive(Clone, Hash)]
292 pub struct Externs(BTreeMap<String, ExternEntry>);
294 #[derive(Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Debug, Default)]
295 pub struct ExternEntry {
296 pub locations: BTreeSet<Option<String>>,
297 pub is_private_dep: bool
301 pub fn new(data: BTreeMap<String, ExternEntry>) -> Externs {
305 pub fn get(&self, key: &str) -> Option<&ExternEntry> {
309 pub fn iter<'a>(&'a self) -> BTreeMapIter<'a, String, ExternEntry> {
315 macro_rules! hash_option {
316 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [UNTRACKED]) => ({});
317 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({
318 if $sub_hashes.insert(stringify!($opt_name),
319 $opt_expr as &dyn dep_tracking::DepTrackingHash).is_some() {
320 bug!("Duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
326 [UNTRACKED_WITH_WARNING $warn_val:expr, $warn_text:expr, $error_format:expr]) => ({
327 if *$opt_expr == $warn_val {
328 early_warn($error_format, $warn_text)
333 macro_rules! top_level_options {
334 (pub struct Options { $(
335 $opt:ident : $t:ty [$dep_tracking_marker:ident $($warn_val:expr, $warn_text:expr)*],
343 pub fn dep_tracking_hash(&self) -> u64 {
344 let mut sub_hashes = BTreeMap::new();
349 [$dep_tracking_marker $($warn_val,
351 self.error_format)*]);
353 let mut hasher = DefaultHasher::new();
354 dep_tracking::stable_hash(sub_hashes,
363 // The top-level command-line options struct
365 // For each option, one has to specify how it behaves with regard to the
366 // dependency tracking system of incremental compilation. This is done via the
367 // square-bracketed directive after the field type. The options are:
370 // A change in the given field will cause the compiler to completely clear the
371 // incremental compilation cache before proceeding.
374 // Incremental compilation is not influenced by this option.
376 // [UNTRACKED_WITH_WARNING(val, warning)]
377 // The option is incompatible with incremental compilation in some way. If it
378 // has the value `val`, the string `warning` is emitted as a warning.
380 // If you add a new option to this struct or one of the sub-structs like
381 // CodegenOptions, think about how it influences incremental compilation. If in
382 // doubt, specify [TRACKED], which is always "correct" but might lead to
383 // unnecessary re-compilation.
386 // The crate config requested for the session, which may be combined
387 // with additional crate configurations during the compile process
388 crate_types: Vec<CrateType> [TRACKED],
389 optimize: OptLevel [TRACKED],
390 // Include the debug_assertions flag into dependency tracking, since it
391 // can influence whether overflow checks are done or not.
392 debug_assertions: bool [TRACKED],
393 debuginfo: DebugInfo [TRACKED],
394 lint_opts: Vec<(String, lint::Level)> [TRACKED],
395 lint_cap: Option<lint::Level> [TRACKED],
396 describe_lints: bool [UNTRACKED],
397 output_types: OutputTypes [TRACKED],
398 search_paths: Vec<SearchPath> [UNTRACKED],
399 libs: Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> [TRACKED],
400 maybe_sysroot: Option<PathBuf> [TRACKED],
402 target_triple: TargetTriple [TRACKED],
404 test: bool [TRACKED],
405 error_format: ErrorOutputType [UNTRACKED],
407 // if Some, enable incremental compilation, using the given
408 // directory to store intermediate results
409 incremental: Option<PathBuf> [UNTRACKED],
411 debugging_opts: DebuggingOptions [TRACKED],
412 prints: Vec<PrintRequest> [UNTRACKED],
413 // Determines which borrow checker(s) to run. This is the parsed, sanitized
414 // version of `debugging_opts.borrowck`, which is just a plain string.
415 borrowck_mode: BorrowckMode [UNTRACKED],
416 cg: CodegenOptions [TRACKED],
417 externs: Externs [UNTRACKED],
418 crate_name: Option<String> [TRACKED],
419 // An optional name to use as the crate for std during std injection,
420 // written `extern crate name as std`. Defaults to `std`. Used by
421 // out-of-tree drivers.
422 alt_std_name: Option<String> [TRACKED],
423 // Indicates how the compiler should treat unstable features
424 unstable_features: UnstableFeatures [TRACKED],
426 // Indicates whether this run of the compiler is actually rustdoc. This
427 // is currently just a hack and will be removed eventually, so please
428 // try to not rely on this too much.
429 actually_rustdoc: bool [TRACKED],
431 // Specifications of codegen units / ThinLTO which are forced as a
432 // result of parsing command line options. These are not necessarily
433 // what rustc was invoked with, but massaged a bit to agree with
434 // commands like `--emit llvm-ir` which they're often incompatible with
435 // if we otherwise use the defaults of rustc.
436 cli_forced_codegen_units: Option<usize> [UNTRACKED],
437 cli_forced_thinlto_off: bool [UNTRACKED],
439 // Remap source path prefixes in all output (messages, object files, debug, etc)
440 remap_path_prefix: Vec<(PathBuf, PathBuf)> [UNTRACKED],
442 edition: Edition [TRACKED],
446 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
447 pub enum PrintRequest {
462 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
463 pub enum BorrowckMode {
469 /// Should we run the MIR-based borrow check, but also fall back
470 /// on the AST borrow check if the MIR-based one errors.
471 pub fn migrate(self) -> bool {
473 BorrowckMode::Mir => false,
474 BorrowckMode::Migrate => true,
478 /// Should we emit the AST-based borrow checker errors?
479 pub fn use_ast(self) -> bool {
481 BorrowckMode::Mir => false,
482 BorrowckMode::Migrate => false,
488 /// Loads source from file
491 /// String that is shown in place of a filename
493 /// Anonymous source string
499 pub fn filestem(&self) -> &str {
501 Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap(),
502 Input::Str { .. } => "rust_out",
506 pub fn get_input(&mut self) -> Option<&mut String> {
508 Input::File(_) => None,
509 Input::Str { ref mut input, .. } => Some(input),
513 pub fn source_name(&self) -> FileName {
515 Input::File(ref ifile) => ifile.clone().into(),
516 Input::Str { ref name, .. } => name.clone(),
521 #[derive(Clone, Hash)]
522 pub struct OutputFilenames {
523 pub out_directory: PathBuf,
524 pub out_filestem: String,
525 pub single_output_file: Option<PathBuf>,
527 pub outputs: OutputTypes,
530 impl_stable_hash_via_hash!(OutputFilenames);
532 pub const RUST_CGU_EXT: &str = "rcgu";
534 impl OutputFilenames {
535 pub fn path(&self, flavor: OutputType) -> PathBuf {
538 .and_then(|p| p.to_owned())
539 .or_else(|| self.single_output_file.clone())
540 .unwrap_or_else(|| self.temp_path(flavor, None))
543 /// Gets the path where a compilation artifact of the given type for the
544 /// given codegen unit should be placed on disk. If codegen_unit_name is
545 /// None, a path distinct from those of any codegen unit will be generated.
546 pub fn temp_path(&self, flavor: OutputType, codegen_unit_name: Option<&str>) -> PathBuf {
547 let extension = flavor.extension();
548 self.temp_path_ext(extension, codegen_unit_name)
551 /// Like temp_path, but also supports things where there is no corresponding
552 /// OutputType, like noopt-bitcode or lto-bitcode.
553 pub fn temp_path_ext(&self, ext: &str, codegen_unit_name: Option<&str>) -> PathBuf {
554 let base = self.out_directory.join(&self.filestem());
556 let mut extension = String::new();
558 if let Some(codegen_unit_name) = codegen_unit_name {
559 extension.push_str(codegen_unit_name);
563 if !extension.is_empty() {
564 extension.push_str(".");
565 extension.push_str(RUST_CGU_EXT);
566 extension.push_str(".");
569 extension.push_str(ext);
572 let path = base.with_extension(&extension[..]);
576 pub fn with_extension(&self, extension: &str) -> PathBuf {
578 .join(&self.filestem())
579 .with_extension(extension)
582 pub fn filestem(&self) -> String {
583 format!("{}{}", self.out_filestem, self.extra)
587 pub fn host_triple() -> &'static str {
588 // Get the host triple out of the build environment. This ensures that our
589 // idea of the host triple is the same as for the set of libraries we've
590 // actually built. We can't just take LLVM's host triple because they
591 // normalize all ix86 architectures to i386.
593 // Instead of grabbing the host triple (for the current host), we grab (at
594 // compile time) the target triple that this rustc is built with and
595 // calling that (at runtime) the host triple.
596 (option_env!("CFG_COMPILER_HOST_TRIPLE")).expect("CFG_COMPILER_HOST_TRIPLE")
599 impl Default for Options {
600 fn default() -> Options {
602 crate_types: Vec::new(),
603 optimize: OptLevel::No,
604 debuginfo: DebugInfo::None,
605 lint_opts: Vec::new(),
607 describe_lints: false,
608 output_types: OutputTypes(BTreeMap::new()),
609 search_paths: vec![],
611 target_triple: TargetTriple::from_triple(host_triple()),
614 debugging_opts: basic_debugging_options(),
616 borrowck_mode: BorrowckMode::Migrate,
617 cg: basic_codegen_options(),
618 error_format: ErrorOutputType::default(),
619 externs: Externs(BTreeMap::new()),
623 unstable_features: UnstableFeatures::Disallow,
624 debug_assertions: true,
625 actually_rustdoc: false,
626 cli_forced_codegen_units: None,
627 cli_forced_thinlto_off: false,
628 remap_path_prefix: Vec::new(),
629 edition: DEFAULT_EDITION,
635 /// Returns `true` if there is a reason to build the dep graph.
636 pub fn build_dep_graph(&self) -> bool {
637 self.incremental.is_some() || self.debugging_opts.dump_dep_graph
638 || self.debugging_opts.query_dep_graph
642 pub fn enable_dep_node_debug_strs(&self) -> bool {
643 cfg!(debug_assertions)
644 && (self.debugging_opts.query_dep_graph || self.debugging_opts.incremental_info)
647 pub fn file_path_mapping(&self) -> FilePathMapping {
648 FilePathMapping::new(self.remap_path_prefix.clone())
651 /// Returns `true` if there will be an output file generated
652 pub fn will_create_output_file(&self) -> bool {
653 !self.debugging_opts.parse_only && // The file is just being parsed
654 !self.debugging_opts.ls // The file is just being queried
658 pub fn share_generics(&self) -> bool {
659 match self.debugging_opts.share_generics {
660 Some(setting) => setting,
662 match self.optimize {
666 OptLevel::SizeMin => true,
668 OptLevel::Aggressive => false,
675 // The type of entry function, so users can have their own entry functions
676 #[derive(Copy, Clone, PartialEq, Hash, Debug)]
677 pub enum EntryFnType {
682 impl_stable_hash_via_hash!(EntryFnType);
684 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
694 #[derive(Clone, Hash)]
701 pub fn is_empty(&self) -> bool {
703 Passes::Some(ref v) => v.is_empty(),
704 Passes::All => false,
709 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
710 /// at once. The goal of this macro is to define an interface that can be
711 /// programmatically used by the option parser in order to initialize the struct
712 /// without hardcoding field names all over the place.
714 /// The goal is to invoke this macro once with the correct fields, and then this
715 /// macro generates all necessary code. The main gotcha of this macro is the
716 /// cgsetters module which is a bunch of generated code to parse an option into
717 /// its respective field in the struct. There are a few hand-written parsers for
718 /// parsing specific types of values in this module.
719 macro_rules! options {
720 ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
721 $buildfn:ident, $prefix:expr, $outputname:expr,
722 $stat:ident, $mod_desc:ident, $mod_set:ident,
723 $($opt:ident : $t:ty = (
726 [$dep_tracking_marker:ident $(($dep_warn_val:expr, $dep_warn_text:expr))*],
731 pub struct $struct_name { $(pub $opt: $t),* }
733 pub fn $defaultfn() -> $struct_name {
734 $struct_name { $($opt: $init),* }
737 pub fn $buildfn(matches: &getopts::Matches, error_format: ErrorOutputType) -> $struct_name
739 let mut op = $defaultfn();
740 for option in matches.opt_strs($prefix) {
741 let mut iter = option.splitn(2, '=');
742 let key = iter.next().unwrap();
743 let value = iter.next();
744 let option_to_lookup = key.replace("-", "_");
745 let mut found = false;
746 for &(candidate, setter, opt_type_desc, _) in $stat {
747 if option_to_lookup != candidate { continue }
748 if !setter(&mut op, value) {
749 match (value, opt_type_desc) {
750 (Some(..), None) => {
751 early_error(error_format, &format!("{} option `{}` takes no \
752 value", $outputname, key))
754 (None, Some(type_desc)) => {
755 early_error(error_format, &format!("{0} option `{1}` requires \
756 {2} ({3} {1}=<value>)",
760 (Some(value), Some(type_desc)) => {
761 early_error(error_format, &format!("incorrect value `{}` for {} \
762 option `{}` - {} was expected",
766 (None, None) => bug!()
773 early_error(error_format, &format!("unknown {} option: `{}`",
780 impl<'a> dep_tracking::DepTrackingHash for $struct_name {
781 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
782 let mut sub_hashes = BTreeMap::new();
787 [$dep_tracking_marker $($dep_warn_val,
791 dep_tracking::stable_hash(sub_hashes, hasher, error_format);
795 pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
796 pub const $stat: &[(&str, $setter_name, Option<&str>, &str)] =
797 &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
799 #[allow(non_upper_case_globals, dead_code)]
801 pub const parse_bool: Option<&str> = None;
802 pub const parse_opt_bool: Option<&str> =
803 Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
804 pub const parse_string: Option<&str> = Some("a string");
805 pub const parse_string_push: Option<&str> = Some("a string");
806 pub const parse_pathbuf_push: Option<&str> = Some("a path");
807 pub const parse_opt_string: Option<&str> = Some("a string");
808 pub const parse_opt_pathbuf: Option<&str> = Some("a path");
809 pub const parse_list: Option<&str> = Some("a space-separated list of strings");
810 pub const parse_opt_list: Option<&str> = Some("a space-separated list of strings");
811 pub const parse_opt_comma_list: Option<&str> = Some("a comma-separated list of strings");
812 pub const parse_uint: Option<&str> = Some("a number");
813 pub const parse_passes: Option<&str> =
814 Some("a space-separated list of passes, or `all`");
815 pub const parse_opt_uint: Option<&str> =
817 pub const parse_panic_strategy: Option<&str> =
818 Some("either `unwind` or `abort`");
819 pub const parse_relro_level: Option<&str> =
820 Some("one of: `full`, `partial`, or `off`");
821 pub const parse_sanitizer: Option<&str> =
822 Some("one of: `address`, `leak`, `memory` or `thread`");
823 pub const parse_linker_flavor: Option<&str> =
824 Some(::rustc_target::spec::LinkerFlavor::one_of());
825 pub const parse_optimization_fuel: Option<&str> =
826 Some("crate=integer");
827 pub const parse_unpretty: Option<&str> =
828 Some("`string` or `string=string`");
829 pub const parse_treat_err_as_bug: Option<&str> =
830 Some("either no value or a number bigger than 0");
831 pub const parse_lto: Option<&str> =
832 Some("either a boolean (`yes`, `no`, `on`, `off`, etc), `thin`, \
834 pub const parse_linker_plugin_lto: Option<&str> =
835 Some("either a boolean (`yes`, `no`, `on`, `off`, etc), \
836 or the path to the linker plugin");
837 pub const parse_switch_with_opt_path: Option<&str> =
838 Some("an optional path to the profiling data output directory");
839 pub const parse_merge_functions: Option<&str> =
840 Some("one of: `disabled`, `trampolines`, or `aliases`");
845 use super::{$struct_name, Passes, Sanitizer, LtoCli, LinkerPluginLto, SwitchWithOptPath};
846 use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
847 use std::path::PathBuf;
848 use std::str::FromStr;
851 pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
852 $parse(&mut cg.$opt, v)
856 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
859 None => { *slot = true; true }
863 fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
867 "n" | "no" | "off" => {
870 "y" | "yes" | "on" => {
873 _ => { return false; }
878 None => { *slot = Some(true); true }
882 fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
884 Some(s) => { *slot = Some(s.to_string()); true },
889 fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
891 Some(s) => { *slot = Some(PathBuf::from(s)); true },
896 fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
898 Some(s) => { *slot = s.to_string(); true },
903 fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
905 Some(s) => { slot.push(s.to_string()); true },
910 fn parse_pathbuf_push(slot: &mut Vec<PathBuf>, v: Option<&str>) -> bool {
912 Some(s) => { slot.push(PathBuf::from(s)); true },
917 fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
921 slot.extend(s.split_whitespace().map(|s| s.to_string()));
928 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
932 let v = s.split_whitespace().map(|s| s.to_string()).collect();
940 fn parse_opt_comma_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
944 let v = s.split(',').map(|s| s.to_string()).collect();
952 fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
953 match v.and_then(|s| s.parse().ok()) {
954 Some(i) => { *slot = i; true },
959 fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
961 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
962 None => { *slot = None; false }
966 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
973 let mut passes = vec![];
974 if parse_list(&mut passes, v) {
975 *slot = Passes::Some(passes);
984 fn parse_panic_strategy(slot: &mut Option<PanicStrategy>, v: Option<&str>) -> bool {
986 Some("unwind") => *slot = Some(PanicStrategy::Unwind),
987 Some("abort") => *slot = Some(PanicStrategy::Abort),
993 fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
996 match s.parse::<RelroLevel>() {
997 Ok(level) => *slot = Some(level),
1006 fn parse_sanitizer(slote: &mut Option<Sanitizer>, v: Option<&str>) -> bool {
1008 Some("address") => *slote = Some(Sanitizer::Address),
1009 Some("leak") => *slote = Some(Sanitizer::Leak),
1010 Some("memory") => *slote = Some(Sanitizer::Memory),
1011 Some("thread") => *slote = Some(Sanitizer::Thread),
1017 fn parse_linker_flavor(slote: &mut Option<LinkerFlavor>, v: Option<&str>) -> bool {
1018 match v.and_then(LinkerFlavor::from_str) {
1019 Some(lf) => *slote = Some(lf),
1025 fn parse_optimization_fuel(slot: &mut Option<(String, u64)>, v: Option<&str>) -> bool {
1029 let parts = s.split('=').collect::<Vec<_>>();
1030 if parts.len() != 2 { return false; }
1031 let crate_name = parts[0].to_string();
1032 let fuel = parts[1].parse::<u64>();
1033 if fuel.is_err() { return false; }
1034 *slot = Some((crate_name, fuel.unwrap()));
1040 fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
1043 Some(s) if s.split('=').count() <= 2 => {
1044 *slot = Some(s.to_string());
1051 fn parse_treat_err_as_bug(slot: &mut Option<usize>, v: Option<&str>) -> bool {
1053 Some(s) => { *slot = s.parse().ok().filter(|&x| x != 0); slot.unwrap_or(0) != 0 }
1054 None => { *slot = Some(1); true }
1058 fn parse_lto(slot: &mut LtoCli, v: Option<&str>) -> bool {
1060 let mut bool_arg = None;
1061 if parse_opt_bool(&mut bool_arg, v) {
1062 *slot = if bool_arg.unwrap() {
1072 None => LtoCli::NoParam,
1073 Some("thin") => LtoCli::Thin,
1074 Some("fat") => LtoCli::Fat,
1075 Some(_) => return false,
1080 fn parse_linker_plugin_lto(slot: &mut LinkerPluginLto, v: Option<&str>) -> bool {
1082 let mut bool_arg = None;
1083 if parse_opt_bool(&mut bool_arg, v) {
1084 *slot = if bool_arg.unwrap() {
1085 LinkerPluginLto::LinkerPluginAuto
1087 LinkerPluginLto::Disabled
1094 None => LinkerPluginLto::LinkerPluginAuto,
1095 Some(path) => LinkerPluginLto::LinkerPlugin(PathBuf::from(path)),
1100 fn parse_switch_with_opt_path(slot: &mut SwitchWithOptPath, v: Option<&str>) -> bool {
1102 None => SwitchWithOptPath::Enabled(None),
1103 Some(path) => SwitchWithOptPath::Enabled(Some(PathBuf::from(path))),
1108 fn parse_merge_functions(slot: &mut Option<MergeFunctions>, v: Option<&str>) -> bool {
1109 match v.and_then(|s| MergeFunctions::from_str(s).ok()) {
1110 Some(mergefunc) => *slot = Some(mergefunc),
1118 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
1119 build_codegen_options, "C", "codegen",
1120 CG_OPTIONS, cg_type_desc, cgsetters,
1121 ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
1122 "this option is deprecated and does nothing"),
1123 linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
1124 "system linker to link outputs with"),
1125 link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1126 "a single extra argument to append to the linker invocation (can be used several times)"),
1127 link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1128 "extra arguments to append to the linker invocation (space separated)"),
1129 link_dead_code: bool = (false, parse_bool, [UNTRACKED],
1130 "don't let linker strip dead code (turning it on can be used for code coverage)"),
1131 lto: LtoCli = (LtoCli::Unspecified, parse_lto, [TRACKED],
1132 "perform LLVM link-time optimizations"),
1133 target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
1134 "select target processor (rustc --print target-cpus for details)"),
1135 target_feature: String = (String::new(), parse_string, [TRACKED],
1136 "target specific attributes (rustc --print target-features for details)"),
1137 passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1138 "a list of extra LLVM passes to run (space separated)"),
1139 llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1140 "a list of arguments to pass to llvm (space separated)"),
1141 save_temps: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1142 "`-C save-temps` might not produce all requested temporary products \
1143 when incremental compilation is enabled.")],
1144 "save all temporary output files during compilation"),
1145 rpath: bool = (false, parse_bool, [UNTRACKED],
1146 "set rpath values in libs/exes"),
1147 overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1148 "use overflow checks for integer arithmetic"),
1149 no_prepopulate_passes: bool = (false, parse_bool, [TRACKED],
1150 "don't pre-populate the pass manager with a list of passes"),
1151 no_vectorize_loops: bool = (false, parse_bool, [TRACKED],
1152 "don't run the loop vectorization optimization passes"),
1153 no_vectorize_slp: bool = (false, parse_bool, [TRACKED],
1154 "don't run LLVM's SLP vectorization pass"),
1155 soft_float: bool = (false, parse_bool, [TRACKED],
1156 "use soft float ABI (*eabihf targets only)"),
1157 prefer_dynamic: bool = (false, parse_bool, [TRACKED],
1158 "prefer dynamic linking to static linking"),
1159 no_integrated_as: bool = (false, parse_bool, [TRACKED],
1160 "use an external assembler rather than LLVM's integrated one"),
1161 no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
1162 "disable the use of the redzone"),
1163 relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
1164 "choose the relocation model to use (rustc --print relocation-models for details)"),
1165 code_model: Option<String> = (None, parse_opt_string, [TRACKED],
1166 "choose the code model to use (rustc --print code-models for details)"),
1167 metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1168 "metadata to mangle symbol names with"),
1169 extra_filename: String = (String::new(), parse_string, [UNTRACKED],
1170 "extra data to put in each output filename"),
1171 codegen_units: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1172 "divide crate into N units to optimize in parallel"),
1173 remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
1174 "print remarks for these optimization passes (space separated, or \"all\")"),
1175 no_stack_check: bool = (false, parse_bool, [UNTRACKED],
1176 "the --no-stack-check flag is deprecated and does nothing"),
1177 debuginfo: Option<usize> = (None, parse_opt_uint, [TRACKED],
1178 "debug info emission level, 0 = no debug info, 1 = line tables only, \
1179 2 = full debug info with variable and type information"),
1180 opt_level: Option<String> = (None, parse_opt_string, [TRACKED],
1181 "optimize with possible levels 0-3, s, or z"),
1182 force_frame_pointers: Option<bool> = (None, parse_opt_bool, [TRACKED],
1183 "force use of the frame pointers"),
1184 debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
1185 "explicitly enable the cfg(debug_assertions) directive"),
1186 inline_threshold: Option<usize> = (None, parse_opt_uint, [TRACKED],
1187 "set the threshold for inlining a function (default: 225)"),
1188 panic: Option<PanicStrategy> = (None, parse_panic_strategy,
1189 [TRACKED], "panic strategy to compile crate with"),
1190 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1191 "enable incremental compilation"),
1192 default_linker_libraries: Option<bool> = (None, parse_opt_bool, [UNTRACKED],
1193 "allow the linker to link its default libraries"),
1194 linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
1196 linker_plugin_lto: LinkerPluginLto = (LinkerPluginLto::Disabled,
1197 parse_linker_plugin_lto, [TRACKED],
1198 "generate build artifacts that are compatible with linker-based LTO."),
1202 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
1203 build_debugging_options, "Z", "debugging",
1204 DB_OPTIONS, db_type_desc, dbsetters,
1205 codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
1206 "the backend to use"),
1207 verbose: bool = (false, parse_bool, [UNTRACKED],
1208 "in general, enable more debug printouts"),
1209 span_free_formats: bool = (false, parse_bool, [UNTRACKED],
1210 "when debug-printing compiler state, do not include spans"), // o/w tests have closure@path
1211 identify_regions: bool = (false, parse_bool, [UNTRACKED],
1212 "make unnamed regions display as '# (where # is some non-ident unique id)"),
1213 borrowck: Option<String> = (None, parse_opt_string, [UNTRACKED],
1214 "select which borrowck is used (`mir` or `migrate`)"),
1215 time_passes: bool = (false, parse_bool, [UNTRACKED],
1216 "measure time of each rustc pass"),
1217 time: bool = (false, parse_bool, [UNTRACKED],
1218 "measure time of rustc processes"),
1219 count_llvm_insns: bool = (false, parse_bool,
1220 [UNTRACKED_WITH_WARNING(true,
1221 "The output generated by `-Z count_llvm_insns` might not be reliable \
1222 when used with incremental compilation")],
1223 "count where LLVM instrs originate"),
1224 time_llvm_passes: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1225 "The output of `-Z time-llvm-passes` will only reflect timings of \
1226 re-codegened modules when used with incremental compilation" )],
1227 "measure time of each LLVM pass"),
1228 input_stats: bool = (false, parse_bool, [UNTRACKED],
1229 "gather statistics about the input"),
1230 codegen_stats: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1231 "The output of `-Z codegen-stats` might not be accurate when incremental \
1232 compilation is enabled")],
1233 "gather codegen statistics"),
1234 asm_comments: bool = (false, parse_bool, [TRACKED],
1235 "generate comments into the assembly (may change behavior)"),
1236 verify_llvm_ir: bool = (false, parse_bool, [TRACKED],
1238 borrowck_stats: bool = (false, parse_bool, [UNTRACKED],
1239 "gather borrowck statistics"),
1240 no_landing_pads: bool = (false, parse_bool, [TRACKED],
1241 "omit landing pads for unwinding"),
1242 fewer_names: bool = (false, parse_bool, [TRACKED],
1243 "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR)"),
1244 meta_stats: bool = (false, parse_bool, [UNTRACKED],
1245 "gather metadata statistics"),
1246 print_link_args: bool = (false, parse_bool, [UNTRACKED],
1247 "print the arguments passed to the linker"),
1248 print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1249 "prints the llvm optimization passes being run"),
1250 ast_json: bool = (false, parse_bool, [UNTRACKED],
1251 "print the AST as JSON and halt"),
1252 threads: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1253 "use a thread pool with N threads"),
1254 ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
1255 "print the pre-expansion AST as JSON and halt"),
1256 ls: bool = (false, parse_bool, [UNTRACKED],
1257 "list the symbols defined by a library crate"),
1258 save_analysis: bool = (false, parse_bool, [UNTRACKED],
1259 "write syntax and type analysis (in JSON format) information, in \
1260 addition to normal output"),
1261 flowgraph_print_loans: bool = (false, parse_bool, [UNTRACKED],
1262 "include loan analysis data in -Z unpretty flowgraph output"),
1263 flowgraph_print_moves: bool = (false, parse_bool, [UNTRACKED],
1264 "include move analysis data in -Z unpretty flowgraph output"),
1265 flowgraph_print_assigns: bool = (false, parse_bool, [UNTRACKED],
1266 "include assignment analysis data in -Z unpretty flowgraph output"),
1267 flowgraph_print_all: bool = (false, parse_bool, [UNTRACKED],
1268 "include all dataflow analysis data in -Z unpretty flowgraph output"),
1269 print_region_graph: bool = (false, parse_bool, [UNTRACKED],
1270 "prints region inference graph. \
1271 Use with RUST_REGION_GRAPH=help for more info"),
1272 parse_only: bool = (false, parse_bool, [UNTRACKED],
1273 "parse only; do not compile, assemble, or link"),
1274 dual_proc_macros: bool = (false, parse_bool, [TRACKED],
1275 "load proc macros for both target and host, but only link to the target"),
1276 no_codegen: bool = (false, parse_bool, [TRACKED],
1277 "run all passes except codegen; no output"),
1278 treat_err_as_bug: Option<usize> = (None, parse_treat_err_as_bug, [TRACKED],
1279 "treat error number `val` that occurs as bug"),
1280 report_delayed_bugs: bool = (false, parse_bool, [TRACKED],
1281 "immediately print bugs registered with `delay_span_bug`"),
1282 external_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1283 "show macro backtraces even for non-local macros"),
1284 teach: bool = (false, parse_bool, [TRACKED],
1285 "show extended diagnostic help"),
1286 continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
1287 "attempt to recover from parse errors (experimental)"),
1288 dep_tasks: bool = (false, parse_bool, [UNTRACKED],
1289 "print tasks that execute and the color their dep node gets (requires debug build)"),
1290 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1291 "enable incremental compilation (experimental)"),
1292 incremental_queries: bool = (true, parse_bool, [UNTRACKED],
1293 "enable incremental compilation support for queries (experimental)"),
1294 incremental_info: bool = (false, parse_bool, [UNTRACKED],
1295 "print high-level information about incremental reuse (or the lack thereof)"),
1296 incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
1297 "dump hash information in textual format to stdout"),
1298 incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
1299 "verify incr. comp. hashes of green query instances"),
1300 incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
1301 "ignore spans during ICH computation -- used for testing"),
1302 instrument_mcount: bool = (false, parse_bool, [TRACKED],
1303 "insert function instrument code for mcount-based tracing"),
1304 dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1305 "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
1306 query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1307 "enable queries of the dependency graph for regression testing"),
1308 profile_queries: bool = (false, parse_bool, [UNTRACKED],
1309 "trace and profile the queries of the incremental compilation framework"),
1310 profile_queries_and_keys: bool = (false, parse_bool, [UNTRACKED],
1311 "trace and profile the queries and keys of the incremental compilation framework"),
1312 no_analysis: bool = (false, parse_bool, [UNTRACKED],
1313 "parse and expand the source, but run no analysis"),
1314 extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1315 "load extra plugins"),
1316 unstable_options: bool = (false, parse_bool, [UNTRACKED],
1317 "adds unstable command line options to rustc interface"),
1318 force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1319 "force overflow checks on or off"),
1320 trace_macros: bool = (false, parse_bool, [UNTRACKED],
1321 "for every macro invocation, print its name and arguments"),
1322 debug_macros: bool = (false, parse_bool, [TRACKED],
1323 "emit line numbers debug info inside macros"),
1324 keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
1325 "don't clear the hygiene data after analysis"),
1326 keep_ast: bool = (false, parse_bool, [UNTRACKED],
1327 "keep the AST after lowering it to HIR"),
1328 show_span: Option<String> = (None, parse_opt_string, [TRACKED],
1329 "show spans for compiler debugging (expr|pat|ty)"),
1330 print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
1331 "print layout information for each type encountered"),
1332 print_mono_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
1333 "print the result of the monomorphization collection pass"),
1334 mir_opt_level: usize = (1, parse_uint, [TRACKED],
1335 "set the MIR optimization level (0-3, default: 1)"),
1336 mutable_noalias: Option<bool> = (None, parse_opt_bool, [TRACKED],
1337 "emit noalias metadata for mutable references (default: yes on LLVM >= 6)"),
1338 dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1339 "dump MIR state to file.
1340 `val` is used to select which passes and functions to dump. For example:
1341 `all` matches all passes and functions,
1342 `foo` matches all passes for functions whose name contains 'foo',
1343 `foo & ConstProp` only the 'ConstProp' pass for function names containing 'foo',
1344 `foo | bar` all passes for function names containing 'foo' or 'bar'."),
1346 dump_mir_dir: String = (String::from("mir_dump"), parse_string, [UNTRACKED],
1347 "the directory the MIR is dumped into"),
1348 dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
1349 "in addition to `.mir` files, create graphviz `.dot` files"),
1350 dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
1351 "if set, exclude the pass number when dumping MIR (used in tests)"),
1352 mir_emit_retag: bool = (false, parse_bool, [TRACKED],
1353 "emit Retagging MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0"),
1354 perf_stats: bool = (false, parse_bool, [UNTRACKED],
1355 "print some performance-related statistics"),
1356 query_stats: bool = (false, parse_bool, [UNTRACKED],
1357 "print some statistics about the query system"),
1358 hir_stats: bool = (false, parse_bool, [UNTRACKED],
1359 "print some statistics about AST and HIR"),
1360 always_encode_mir: bool = (false, parse_bool, [TRACKED],
1361 "encode MIR of all functions into the crate metadata"),
1362 json_rendered: Option<String> = (None, parse_opt_string, [UNTRACKED],
1363 "describes how to render the `rendered` field of json diagnostics"),
1364 unleash_the_miri_inside_of_you: bool = (false, parse_bool, [TRACKED],
1365 "take the breaks off const evaluation. NOTE: this is unsound"),
1366 osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
1367 "pass `-install_name @rpath/...` to the macOS linker"),
1368 sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
1370 fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
1371 "set the optimization fuel quota for a crate"),
1372 print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
1373 "make Rustc print the total optimization fuel used by a crate"),
1374 force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
1375 "force all crates to be `rustc_private` unstable"),
1376 pre_link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1377 "a single extra argument to prepend the linker invocation (can be used several times)"),
1378 pre_link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1379 "extra arguments to prepend to the linker invocation (space separated)"),
1380 profile: bool = (false, parse_bool, [TRACKED],
1381 "insert profiling code"),
1382 pgo_gen: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
1383 parse_switch_with_opt_path, [TRACKED],
1384 "Generate PGO profile data, to a given file, or to the default location if it's empty."),
1385 pgo_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1386 "Use PGO profile data from the given profile file."),
1387 disable_instrumentation_preinliner: bool = (false, parse_bool, [TRACKED],
1388 "Disable the instrumentation pre-inliner, useful for profiling / PGO."),
1389 relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
1390 "choose which RELRO level to use"),
1391 nll_facts: bool = (false, parse_bool, [UNTRACKED],
1392 "dump facts from NLL analysis into side files"),
1393 nll_dont_emit_read_for_match: bool = (false, parse_bool, [UNTRACKED],
1394 "in match codegen, do not include FakeRead statements (used by mir-borrowck)"),
1395 dont_buffer_diagnostics: bool = (false, parse_bool, [UNTRACKED],
1396 "emit diagnostics rather than buffering (breaks NLL error downgrading, sorting)."),
1397 polonius: bool = (false, parse_bool, [UNTRACKED],
1398 "enable polonius-based borrow-checker"),
1399 codegen_time_graph: bool = (false, parse_bool, [UNTRACKED],
1400 "generate a graphical HTML report of time spent in codegen and LLVM"),
1401 thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
1402 "enable ThinLTO when possible"),
1403 inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
1404 "control whether #[inline] functions are in all cgus"),
1405 tls_model: Option<String> = (None, parse_opt_string, [TRACKED],
1406 "choose the TLS model to use (rustc --print tls-models for details)"),
1407 saturating_float_casts: bool = (false, parse_bool, [TRACKED],
1408 "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
1409 the max/min integer respectively, and NaN is mapped to 0"),
1410 lower_128bit_ops: Option<bool> = (None, parse_opt_bool, [TRACKED],
1411 "rewrite operators on i128 and u128 into lang item calls (typically provided \
1412 by compiler-builtins) so codegen doesn't need to support them,
1413 overriding the default for the current target"),
1414 human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
1415 "generate human-readable, predictable names for codegen units"),
1416 dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
1417 "in dep-info output, omit targets for tracking dependencies of the dep-info files \
1419 unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
1420 "Present the input source, unstable (and less-pretty) variants;
1421 valid types are any of the types for `--pretty`, as well as:
1422 `expanded`, `expanded,identified`,
1423 `expanded,hygiene` (with internal representations),
1424 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
1425 `flowgraph,unlabelled=<nodeid>` (unlabelled graphviz formatted flowgraph for node),
1426 `everybody_loops` (all function bodies replaced with `loop {}`),
1427 `hir` (the HIR), `hir,identified`,
1428 `hir,typed` (HIR with types for each node),
1429 `hir-tree` (dump the raw HIR),
1430 `mir` (the MIR), or `mir-cfg` (graphviz formatted MIR)"),
1431 run_dsymutil: Option<bool> = (None, parse_opt_bool, [TRACKED],
1432 "run `dsymutil` and delete intermediate object files"),
1433 ui_testing: bool = (false, parse_bool, [UNTRACKED],
1434 "format compiler diagnostics in a way that's better suitable for UI testing"),
1435 embed_bitcode: bool = (false, parse_bool, [TRACKED],
1436 "embed LLVM bitcode in object files"),
1437 strip_debuginfo_if_disabled: Option<bool> = (None, parse_opt_bool, [TRACKED],
1438 "tell the linker to strip debuginfo when building without debuginfo enabled."),
1439 share_generics: Option<bool> = (None, parse_opt_bool, [TRACKED],
1440 "make the current crate share its generic instantiations"),
1441 chalk: bool = (false, parse_bool, [TRACKED],
1442 "enable the experimental Chalk-based trait solving engine"),
1443 no_parallel_llvm: bool = (false, parse_bool, [UNTRACKED],
1444 "don't run LLVM in parallel (while keeping codegen-units and ThinLTO)"),
1445 no_leak_check: bool = (false, parse_bool, [UNTRACKED],
1446 "disables the 'leak check' for subtyping; unsound, but useful for tests"),
1447 no_interleave_lints: bool = (false, parse_bool, [UNTRACKED],
1448 "don't interleave execution of lints; allows benchmarking individual lints"),
1449 crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],
1450 "inject the given attribute in the crate"),
1451 self_profile: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
1452 parse_switch_with_opt_path, [UNTRACKED],
1453 "run the self profiler and output the raw event data"),
1454 self_profile_events: Option<Vec<String>> = (None, parse_opt_comma_list, [UNTRACKED],
1455 "specifies which kinds of events get recorded by the self profiler"),
1456 emit_stack_sizes: bool = (false, parse_bool, [UNTRACKED],
1457 "emits a section containing stack size metadata"),
1458 plt: Option<bool> = (None, parse_opt_bool, [TRACKED],
1459 "whether to use the PLT when calling into shared libraries;
1460 only has effect for PIC code on systems with ELF binaries
1461 (default: PLT is disabled if full relro is enabled)"),
1462 merge_functions: Option<MergeFunctions> = (None, parse_merge_functions, [TRACKED],
1463 "control the operation of the MergeFunctions LLVM pass, taking
1464 the same values as the target option of the same name"),
1465 allow_features: Option<Vec<String>> = (None, parse_opt_comma_list, [TRACKED],
1466 "only allow the listed language features to be enabled in code (space separated)"),
1467 emit_artifact_notifications: bool = (false, parse_bool, [UNTRACKED],
1468 "emit notifications after each artifact has been output (only in the JSON format)"),
1471 pub fn default_lib_output() -> CrateType {
1475 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
1476 let end = &sess.target.target.target_endian;
1477 let arch = &sess.target.target.arch;
1478 let wordsz = &sess.target.target.target_pointer_width;
1479 let os = &sess.target.target.target_os;
1480 let env = &sess.target.target.target_env;
1481 let vendor = &sess.target.target.target_vendor;
1482 let min_atomic_width = sess.target.target.min_atomic_width();
1483 let max_atomic_width = sess.target.target.max_atomic_width();
1484 let atomic_cas = sess.target.target.options.atomic_cas;
1486 let mut ret = FxHashSet::default();
1487 ret.reserve(6); // the minimum number of insertions
1489 ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
1490 if let Some(ref fam) = sess.target.target.options.target_family {
1491 ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam))));
1492 if fam == "windows" || fam == "unix" {
1493 ret.insert((Symbol::intern(fam), None));
1496 ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
1497 ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
1499 Symbol::intern("target_pointer_width"),
1500 Some(Symbol::intern(wordsz)),
1502 ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
1504 Symbol::intern("target_vendor"),
1505 Some(Symbol::intern(vendor)),
1507 if sess.target.target.options.has_elf_tls {
1508 ret.insert((sym::target_thread_local, None));
1510 for &i in &[8, 16, 32, 64, 128] {
1511 if i >= min_atomic_width && i <= max_atomic_width {
1512 let s = i.to_string();
1514 sym::target_has_atomic,
1515 Some(Symbol::intern(&s)),
1519 sym::target_has_atomic,
1520 Some(Symbol::intern("ptr")),
1526 ret.insert((sym::target_has_atomic, Some(Symbol::intern("cas"))));
1528 if sess.opts.debug_assertions {
1529 ret.insert((Symbol::intern("debug_assertions"), None));
1531 if sess.opts.crate_types.contains(&CrateType::ProcMacro) {
1532 ret.insert((sym::proc_macro, None));
1537 /// Converts the crate cfg! configuration from String to Symbol.
1538 /// `rustc_interface::interface::Config` accepts this in the compiler configuration,
1539 /// but the symbol interner is not yet set up then, so we must convert it later.
1540 pub fn to_crate_config(cfg: FxHashSet<(String, Option<String>)>) -> ast::CrateConfig {
1542 .map(|(a, b)| (Symbol::intern(&a), b.map(|b| Symbol::intern(&b))))
1546 pub fn build_configuration(sess: &Session, mut user_cfg: ast::CrateConfig) -> ast::CrateConfig {
1547 // Combine the configuration requested by the session (command line) with
1548 // some default and generated configuration items
1549 let default_cfg = default_configuration(sess);
1550 // If the user wants a test runner, then add the test cfg
1552 user_cfg.insert((sym::test, None));
1554 user_cfg.extend(default_cfg.iter().cloned());
1558 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
1559 let target = Target::search(&opts.target_triple).unwrap_or_else(|e| {
1560 sp.struct_fatal(&format!("Error loading target specification: {}", e))
1561 .help("Use `--print target-list` for a list of built-in targets")
1566 let (isize_ty, usize_ty) = match &target.target_pointer_width[..] {
1567 "16" => (ast::IntTy::I16, ast::UintTy::U16),
1568 "32" => (ast::IntTy::I32, ast::UintTy::U32),
1569 "64" => (ast::IntTy::I64, ast::UintTy::U64),
1570 w => sp.fatal(&format!(
1571 "target specification was invalid: \
1572 unrecognized target-pointer-width {}",
1584 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1585 pub enum OptionStability {
1590 pub struct RustcOptGroup {
1591 pub apply: Box<dyn Fn(&mut getopts::Options) -> &mut getopts::Options>,
1592 pub name: &'static str,
1593 pub stability: OptionStability,
1596 impl RustcOptGroup {
1597 pub fn is_stable(&self) -> bool {
1598 self.stability == OptionStability::Stable
1601 pub fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
1603 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1608 stability: OptionStability::Stable,
1612 pub fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
1614 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1619 stability: OptionStability::Unstable,
1624 // The `opt` local module holds wrappers around the `getopts` API that
1625 // adds extra rustc-specific metadata to each option; such metadata
1626 // is exposed by . The public
1627 // functions below ending with `_u` are the functions that return
1628 // *unstable* options, i.e., options that are only enabled when the
1629 // user also passes the `-Z unstable-options` debugging flag.
1631 // The `fn opt_u` etc below are written so that we can use them
1632 // in the future; do not warn about them not being used right now.
1633 #![allow(dead_code)]
1636 use super::RustcOptGroup;
1638 pub type R = RustcOptGroup;
1639 pub type S = &'static str;
1641 fn stable<F>(name: S, f: F) -> R
1643 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1645 RustcOptGroup::stable(name, f)
1648 fn unstable<F>(name: S, f: F) -> R
1650 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1652 RustcOptGroup::unstable(name, f)
1655 fn longer(a: S, b: S) -> S {
1656 if a.len() > b.len() {
1663 pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
1664 stable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1666 pub fn multi_s(a: S, b: S, c: S, d: S) -> R {
1667 stable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1669 pub fn flag_s(a: S, b: S, c: S) -> R {
1670 stable(longer(a, b), move |opts| opts.optflag(a, b, c))
1672 pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R {
1673 stable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1675 pub fn flagmulti_s(a: S, b: S, c: S) -> R {
1676 stable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1679 pub fn opt(a: S, b: S, c: S, d: S) -> R {
1680 unstable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1682 pub fn multi(a: S, b: S, c: S, d: S) -> R {
1683 unstable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1685 pub fn flag(a: S, b: S, c: S) -> R {
1686 unstable(longer(a, b), move |opts| opts.optflag(a, b, c))
1688 pub fn flagopt(a: S, b: S, c: S, d: S) -> R {
1689 unstable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1691 pub fn flagmulti(a: S, b: S, c: S) -> R {
1692 unstable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1696 /// Returns the "short" subset of the rustc command line options,
1697 /// including metadata for each option, such as whether the option is
1698 /// part of the stable long-term interface for rustc.
1699 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
1701 opt::flag_s("h", "help", "Display this message"),
1702 opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
1706 "Add a directory to the library search path. The
1707 optional KIND can be one of dependency, crate, native,
1708 framework or all (the default).",
1714 "Link the generated crate(s) to the specified native
1715 library NAME. The optional KIND can be one of
1716 static, dylib, or framework. If omitted, dylib is
1723 "Comma separated list of types of crates
1724 for the compiler to emit",
1725 "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]",
1730 "Specify the name of the crate being built",
1736 "Specify which edition of the compiler to use when compiling code.",
1742 "Comma separated list of types of output for \
1743 the compiler to emit",
1744 "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]",
1749 "Compiler information to print on stdout",
1750 "[crate-name|file-names|sysroot|cfg|target-list|\
1751 target-cpus|target-features|relocation-models|\
1752 code-models|tls-models|target-spec-json|native-static-libs]",
1754 opt::flagmulti_s("g", "", "Equivalent to -C debuginfo=2"),
1755 opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
1756 opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
1760 "Write output to compiler-chosen filename \
1767 "Provide a detailed explanation of an error \
1771 opt::flag_s("", "test", "Build a test harness"),
1775 "Target triple for which the code is compiled",
1778 opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
1779 opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
1780 opt::multi_s("D", "deny", "Set lint denied", "OPT"),
1781 opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
1785 "Set the most restrictive lint level. \
1786 More restrictive lints are capped at this \
1790 opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
1791 opt::flag_s("V", "version", "Print version info and exit"),
1792 opt::flag_s("v", "verbose", "Use verbose output"),
1796 /// Returns all rustc command line options, including metadata for
1797 /// each option, such as whether the option is part of the stable
1798 /// long-term interface for rustc.
1799 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
1800 let mut opts = rustc_short_optgroups();
1805 "Specify where an external rust library is located",
1811 "Specify where an extern rust library is located, marking it as a private dependency",
1814 opt::opt_s("", "sysroot", "Override the system root", "PATH"),
1815 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
1819 "How errors and other messages are produced",
1825 "Choose `rendered` field of json diagnostics render scheme",
1831 "Configure coloring of output:
1832 auto = colorize, if output goes to a tty (default);
1833 always = always colorize output;
1834 never = never colorize output",
1835 "auto|always|never",
1840 "Pretty-print the input instead of compiling;
1841 valid types are: `normal` (un-annotated source),
1842 `expanded` (crates expanded), or
1843 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
1848 "remap-path-prefix",
1849 "Remap source names in all output (compiler messages and output files)",
1856 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
1857 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
1858 syntax::with_default_globals(move || {
1859 let cfg = cfgspecs.into_iter().map(|s| {
1860 let sess = parse::ParseSess::new(FilePathMapping::empty());
1861 let filename = FileName::cfg_spec_source_code(&s);
1862 let mut parser = parse::new_parser_from_source_str(&sess, filename, s.to_string());
1864 macro_rules! error {($reason: expr) => {
1865 early_error(ErrorOutputType::default(),
1866 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s));
1869 match &mut parser.parse_meta_item() {
1870 Ok(meta_item) if parser.token == token::Eof => {
1871 if meta_item.path.segments.len() != 1 {
1872 error!("argument key must be an identifier");
1874 match &meta_item.node {
1875 MetaItemKind::List(..) => {
1876 error!(r#"expected `key` or `key="value"`"#);
1878 MetaItemKind::NameValue(lit) if !lit.node.is_str() => {
1879 error!("argument value must be a string");
1881 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
1882 let ident = meta_item.ident().expect("multi-segment cfg key");
1883 return (ident.name, meta_item.value_str());
1888 Err(err) => err.cancel(),
1891 error!(r#"expected `key` or `key="value"`"#);
1892 }).collect::<ast::CrateConfig>();
1893 cfg.into_iter().map(|(a, b)| {
1894 (a.to_string(), b.map(|b| b.to_string()))
1899 pub fn get_cmd_lint_options(matches: &getopts::Matches,
1900 error_format: ErrorOutputType)
1901 -> (Vec<(String, lint::Level)>, bool, Option<lint::Level>) {
1902 let mut lint_opts = vec![];
1903 let mut describe_lints = false;
1905 for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
1906 for lint_name in matches.opt_strs(level.as_str()) {
1907 if lint_name == "help" {
1908 describe_lints = true;
1910 lint_opts.push((lint_name.replace("-", "_"), level));
1915 let lint_cap = matches.opt_str("cap-lints").map(|cap| {
1916 lint::Level::from_str(&cap)
1917 .unwrap_or_else(|| early_error(error_format, &format!("unknown lint level: `{}`", cap)))
1919 (lint_opts, describe_lints, lint_cap)
1922 pub fn build_session_options_and_crate_config(
1923 matches: &getopts::Matches,
1924 ) -> (Options, FxHashSet<(String, Option<String>)>) {
1925 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
1926 Some("auto") => ColorConfig::Auto,
1927 Some("always") => ColorConfig::Always,
1928 Some("never") => ColorConfig::Never,
1930 None => ColorConfig::Auto,
1932 Some(arg) => early_error(
1933 ErrorOutputType::default(),
1935 "argument for --color must be auto, \
1936 always or never (instead was `{}`)",
1942 let edition = match matches.opt_str("edition") {
1943 Some(arg) => Edition::from_str(&arg).unwrap_or_else(|_|
1945 ErrorOutputType::default(),
1947 "argument for --edition must be one of: \
1948 {}. (instead was `{}`)",
1954 None => DEFAULT_EDITION,
1957 if !edition.is_stable() && !nightly_options::is_nightly_build() {
1959 ErrorOutputType::default(),
1961 "Edition {} is unstable and only \
1962 available for nightly builds of rustc.",
1968 let json_rendered = matches.opt_str("json-rendered").and_then(|s| match s.as_str() {
1970 "termcolor" => Some(HumanReadableErrorType::Default(ColorConfig::Always)),
1972 ErrorOutputType::default(),
1974 "argument for --json-rendered must be `plain` or `termcolor` (instead was `{}`)",
1978 }).unwrap_or(HumanReadableErrorType::Default(ColorConfig::Never));
1980 // We need the opts_present check because the driver will send us Matches
1981 // with only stable options if no unstable options are used. Since error-format
1982 // is unstable, it will not be present. We have to use opts_present not
1983 // opt_present because the latter will panic.
1984 let error_format = if matches.opts_present(&["error-format".to_owned()]) {
1985 match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
1987 Some("human") => ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color)),
1988 Some("json") => ErrorOutputType::Json { pretty: false, json_rendered },
1989 Some("pretty-json") => ErrorOutputType::Json { pretty: true, json_rendered },
1990 Some("short") => ErrorOutputType::HumanReadable(HumanReadableErrorType::Short(color)),
1992 Some(arg) => early_error(
1993 ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color)),
1995 "argument for --error-format must be `human`, `json` or \
1996 `short` (instead was `{}`)",
2002 ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color))
2005 let unparsed_crate_types = matches.opt_strs("crate-type");
2006 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
2007 .unwrap_or_else(|e| early_error(error_format, &e[..]));
2010 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
2012 let mut debugging_opts = build_debugging_options(matches, error_format);
2014 if !debugging_opts.unstable_options {
2015 if matches.opt_str("json-rendered").is_some() {
2016 early_error(error_format, "`--json-rendered=x` is unstable");
2018 if let ErrorOutputType::Json { pretty: true, json_rendered } = error_format {
2020 ErrorOutputType::Json { pretty: false, json_rendered },
2021 "--error-format=pretty-json is unstable",
2026 if debugging_opts.pgo_gen.enabled() && debugging_opts.pgo_use.is_some() {
2029 "options `-Z pgo-gen` and `-Z pgo-use` are exclusive",
2033 let mut output_types = BTreeMap::new();
2034 if !debugging_opts.parse_only {
2035 for list in matches.opt_strs("emit") {
2036 for output_type in list.split(',') {
2037 let mut parts = output_type.splitn(2, '=');
2038 let shorthand = parts.next().unwrap();
2039 let output_type = OutputType::from_shorthand(shorthand).unwrap_or_else(||
2043 "unknown emission type: `{}` - expected one of: {}",
2045 OutputType::shorthands_display(),
2049 let path = parts.next().map(PathBuf::from);
2050 output_types.insert(output_type, path);
2054 if output_types.is_empty() {
2055 output_types.insert(OutputType::Exe, None);
2058 let mut cg = build_codegen_options(matches, error_format);
2059 let mut codegen_units = cg.codegen_units;
2060 let mut disable_thinlto = false;
2062 // Issue #30063: if user requests llvm-related output to one
2063 // particular path, disable codegen-units.
2064 let incompatible: Vec<_> = output_types
2066 .map(|ot_path| ot_path.0)
2067 .filter(|ot| !ot.is_compatible_with_codegen_units_and_single_output_file())
2068 .map(|ot| ot.shorthand())
2070 if !incompatible.is_empty() {
2071 match codegen_units {
2072 Some(n) if n > 1 => {
2073 if matches.opt_present("o") {
2074 for ot in &incompatible {
2078 "--emit={} with -o incompatible with \
2079 -C codegen-units=N for N > 1",
2084 early_warn(error_format, "resetting to default -C codegen-units=1");
2085 codegen_units = Some(1);
2086 disable_thinlto = true;
2090 codegen_units = Some(1);
2091 disable_thinlto = true;
2096 if debugging_opts.threads == Some(0) {
2099 "Value for threads must be a positive nonzero integer",
2103 if debugging_opts.threads.unwrap_or(1) > 1 && debugging_opts.fuel.is_some() {
2106 "Optimization fuel is incompatible with multiple threads",
2110 if codegen_units == Some(0) {
2113 "Value for codegen units must be a positive nonzero integer",
2117 let incremental = match (&debugging_opts.incremental, &cg.incremental) {
2118 (&Some(ref path1), &Some(ref path2)) => {
2123 "conflicting paths for `-Z incremental` and \
2124 `-C incremental` specified: {} versus {}",
2132 (&Some(ref path), &None) => Some(path),
2133 (&None, &Some(ref path)) => Some(path),
2134 (&None, &None) => None,
2135 }.map(|m| PathBuf::from(m));
2137 if debugging_opts.profile && incremental.is_some() {
2140 "can't instrument with gcov profiling when compiling incrementally",
2144 let mut prints = Vec::<PrintRequest>::new();
2145 if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
2146 prints.push(PrintRequest::TargetCPUs);
2147 cg.target_cpu = None;
2149 if cg.target_feature == "help" {
2150 prints.push(PrintRequest::TargetFeatures);
2151 cg.target_feature = String::new();
2153 if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
2154 prints.push(PrintRequest::RelocationModels);
2155 cg.relocation_model = None;
2157 if cg.code_model.as_ref().map_or(false, |s| s == "help") {
2158 prints.push(PrintRequest::CodeModels);
2159 cg.code_model = None;
2164 .map_or(false, |s| s == "help")
2166 prints.push(PrintRequest::TlsModels);
2167 debugging_opts.tls_model = None;
2172 let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
2173 let target_triple = if let Some(target) = matches.opt_str("target") {
2174 if target.ends_with(".json") {
2175 let path = Path::new(&target);
2176 TargetTriple::from_path(&path).unwrap_or_else(|_|
2177 early_error(error_format, &format!("target file {:?} does not exist", path)))
2179 TargetTriple::TargetTriple(target)
2182 TargetTriple::from_triple(host_triple())
2185 // The `-O` and `-C opt-level` flags specify the same setting, so we want to be able
2186 // to use them interchangeably. However, because they're technically different flags,
2187 // we need to work out manually which should take precedence if both are supplied (i.e.
2188 // the rightmost flag). We do this by finding the (rightmost) position of both flags and
2189 // comparing them. Note that if a flag is not found, its position will be `None`, which
2190 // always compared less than `Some(_)`.
2191 let max_o = matches.opt_positions("O").into_iter().max();
2192 let max_c = matches.opt_strs_pos("C").into_iter().flat_map(|(i, s)| {
2193 if let Some("opt-level") = s.splitn(2, '=').next() {
2202 match cg.opt_level.as_ref().map(String::as_ref) {
2203 None => OptLevel::No,
2204 Some("0") => OptLevel::No,
2205 Some("1") => OptLevel::Less,
2206 Some("2") => OptLevel::Default,
2207 Some("3") => OptLevel::Aggressive,
2208 Some("s") => OptLevel::Size,
2209 Some("z") => OptLevel::SizeMin,
2214 "optimization level needs to be \
2215 between 0-3, s or z (instead was `{}`)",
2223 // The `-g` and `-C debuginfo` flags specify the same setting, so we want to be able
2224 // to use them interchangeably. See the note above (regarding `-O` and `-C opt-level`)
2225 // for more details.
2226 let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
2227 let max_g = matches.opt_positions("g").into_iter().max();
2228 let max_c = matches.opt_strs_pos("C").into_iter().flat_map(|(i, s)| {
2229 if let Some("debuginfo") = s.splitn(2, '=').next() {
2235 let debuginfo = if max_g > max_c {
2238 match cg.debuginfo {
2239 None | Some(0) => DebugInfo::None,
2240 Some(1) => DebugInfo::Limited,
2241 Some(2) => DebugInfo::Full,
2246 "debug info level needs to be between \
2247 0-2 (instead was `{}`)",
2255 let mut search_paths = vec![];
2256 for s in &matches.opt_strs("L") {
2257 search_paths.push(SearchPath::from_cli_opt(&s[..], error_format));
2264 // Parse string of the form "[KIND=]lib[:new_name]",
2265 // where KIND is one of "dylib", "framework", "static".
2266 let mut parts = s.splitn(2, '=');
2267 let kind = parts.next().unwrap();
2268 let (name, kind) = match (parts.next(), kind) {
2269 (None, name) => (name, None),
2270 (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
2271 (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
2272 (Some(name), "static") => (name, Some(cstore::NativeStatic)),
2273 (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
2278 "unknown library kind `{}`, expected \
2279 one of dylib, framework, or static",
2285 if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
2289 "the library kind 'static-nobundle' is only \
2290 accepted on the nightly compiler"
2294 let mut name_parts = name.splitn(2, ':');
2295 let name = name_parts.next().unwrap();
2296 let new_name = name_parts.next();
2297 (name.to_owned(), new_name.map(|n| n.to_owned()), kind)
2301 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
2302 let test = matches.opt_present("test");
2304 let is_unstable_enabled = nightly_options::is_unstable_enabled(matches);
2306 prints.extend(matches.opt_strs("print").into_iter().map(|s| match &*s {
2307 "crate-name" => PrintRequest::CrateName,
2308 "file-names" => PrintRequest::FileNames,
2309 "sysroot" => PrintRequest::Sysroot,
2310 "cfg" => PrintRequest::Cfg,
2311 "target-list" => PrintRequest::TargetList,
2312 "target-cpus" => PrintRequest::TargetCPUs,
2313 "target-features" => PrintRequest::TargetFeatures,
2314 "relocation-models" => PrintRequest::RelocationModels,
2315 "code-models" => PrintRequest::CodeModels,
2316 "tls-models" => PrintRequest::TlsModels,
2317 "native-static-libs" => PrintRequest::NativeStaticLibs,
2318 "target-spec-json" => {
2319 if is_unstable_enabled {
2320 PrintRequest::TargetSpec
2324 "the `-Z unstable-options` flag must also be passed to \
2325 enable the target-spec-json print option",
2329 req => early_error(error_format, &format!("unknown print request `{}`", req)),
2332 let borrowck_mode = match debugging_opts.borrowck.as_ref().map(|s| &s[..]) {
2333 None | Some("migrate") => BorrowckMode::Migrate,
2334 Some("mir") => BorrowckMode::Mir,
2335 Some(m) => early_error(error_format, &format!("unknown borrowck mode `{}`", m)),
2338 if !cg.remark.is_empty() && debuginfo == DebugInfo::None {
2341 "-C remark requires \"-C debuginfo=n\" to show source locations",
2345 if matches.opt_present("extern-private") && !debugging_opts.unstable_options {
2347 ErrorOutputType::default(),
2348 "'--extern-private' is unstable and only \
2349 available for nightly builds of rustc."
2353 // We start out with a Vec<(Option<String>, bool)>>,
2354 // and later convert it into a BTreeSet<(Option<String>, bool)>
2355 // This allows to modify entries in-place to set their correct
2357 let mut externs: BTreeMap<String, ExternEntry> = BTreeMap::new();
2358 for (arg, private) in matches.opt_strs("extern").into_iter().map(|v| (v, false))
2359 .chain(matches.opt_strs("extern-private").into_iter().map(|v| (v, true))) {
2361 let mut parts = arg.splitn(2, '=');
2362 let name = parts.next().unwrap_or_else(||
2363 early_error(error_format, "--extern value must not be empty"));
2364 let location = parts.next().map(|s| s.to_string());
2365 if location.is_none() && !is_unstable_enabled {
2368 "the `-Z unstable-options` flag must also be passed to \
2369 enable `--extern crate_name` without `=path`",
2374 .entry(name.to_owned())
2378 entry.locations.insert(location.clone());
2380 // Crates start out being not private,
2381 // and go to being private if we see an '--extern-private'
2383 entry.is_private_dep |= private;
2386 let crate_name = matches.opt_str("crate-name");
2388 let remap_path_prefix = matches
2389 .opt_strs("remap-path-prefix")
2392 let mut parts = remap.rsplitn(2, '='); // reverse iterator
2393 let to = parts.next();
2394 let from = parts.next();
2396 (Some(from), Some(to)) => (PathBuf::from(from), PathBuf::from(to)),
2399 "--remap-path-prefix must contain '=' between FROM and TO",
2408 optimize: opt_level,
2413 output_types: OutputTypes(output_types),
2415 maybe_sysroot: sysroot_opt,
2424 externs: Externs(externs),
2428 unstable_features: UnstableFeatures::from_environment(),
2430 actually_rustdoc: false,
2431 cli_forced_codegen_units: codegen_units,
2432 cli_forced_thinlto_off: disable_thinlto,
2440 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
2441 let mut crate_types: Vec<CrateType> = Vec::new();
2442 for unparsed_crate_type in &list_list {
2443 for part in unparsed_crate_type.split(',') {
2444 let new_part = match part {
2445 "lib" => default_lib_output(),
2446 "rlib" => CrateType::Rlib,
2447 "staticlib" => CrateType::Staticlib,
2448 "dylib" => CrateType::Dylib,
2449 "cdylib" => CrateType::Cdylib,
2450 "bin" => CrateType::Executable,
2451 "proc-macro" => CrateType::ProcMacro,
2452 _ => return Err(format!("unknown crate type: `{}`", part))
2454 if !crate_types.contains(&new_part) {
2455 crate_types.push(new_part)
2463 pub mod nightly_options {
2465 use syntax::feature_gate::UnstableFeatures;
2466 use super::{ErrorOutputType, OptionStability, RustcOptGroup};
2467 use crate::session::early_error;
2469 pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
2474 .any(|x| *x == "unstable-options")
2477 pub fn is_nightly_build() -> bool {
2478 UnstableFeatures::from_environment().is_nightly_build()
2481 pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
2482 let has_z_unstable_option = matches
2485 .any(|x| *x == "unstable-options");
2486 let really_allows_unstable_options =
2487 UnstableFeatures::from_environment().is_nightly_build();
2489 for opt in flags.iter() {
2490 if opt.stability == OptionStability::Stable {
2493 if !matches.opt_present(opt.name) {
2496 if opt.name != "Z" && !has_z_unstable_option {
2498 ErrorOutputType::default(),
2500 "the `-Z unstable-options` flag must also be passed to enable \
2506 if really_allows_unstable_options {
2509 match opt.stability {
2510 OptionStability::Unstable => {
2512 "the option `{}` is only accepted on the \
2516 early_error(ErrorOutputType::default(), &msg);
2518 OptionStability::Stable => {}
2524 impl fmt::Display for CrateType {
2525 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2527 CrateType::Executable => "bin".fmt(f),
2528 CrateType::Dylib => "dylib".fmt(f),
2529 CrateType::Rlib => "rlib".fmt(f),
2530 CrateType::Staticlib => "staticlib".fmt(f),
2531 CrateType::Cdylib => "cdylib".fmt(f),
2532 CrateType::ProcMacro => "proc-macro".fmt(f),
2537 /// Command-line arguments passed to the compiler have to be incorporated with
2538 /// the dependency tracking system for incremental compilation. This module
2539 /// provides some utilities to make this more convenient.
2541 /// The values of all command-line arguments that are relevant for dependency
2542 /// tracking are hashed into a single value that determines whether the
2543 /// incremental compilation cache can be re-used or not. This hashing is done
2544 /// via the DepTrackingHash trait defined below, since the standard Hash
2545 /// implementation might not be suitable (e.g., arguments are stored in a Vec,
2546 /// the hash of which is order dependent, but we might not want the order of
2547 /// arguments to make a difference for the hash).
2549 /// However, since the value provided by Hash::hash often *is* suitable,
2550 /// especially for primitive types, there is the
2551 /// impl_dep_tracking_hash_via_hash!() macro that allows to simply reuse the
2552 /// Hash implementation for DepTrackingHash. It's important though that
2553 /// we have an opt-in scheme here, so one is hopefully forced to think about
2554 /// how the hash should be calculated when adding a new command-line argument.
2557 use crate::middle::cstore;
2558 use std::collections::BTreeMap;
2559 use std::hash::Hash;
2560 use std::path::PathBuf;
2561 use std::collections::hash_map::DefaultHasher;
2562 use super::{CrateType, DebugInfo, ErrorOutputType, OptLevel, OutputTypes,
2563 Passes, Sanitizer, LtoCli, LinkerPluginLto, SwitchWithOptPath};
2564 use syntax::feature_gate::UnstableFeatures;
2565 use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel, TargetTriple};
2566 use syntax::edition::Edition;
2568 pub trait DepTrackingHash {
2569 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);
2572 macro_rules! impl_dep_tracking_hash_via_hash {
2574 impl DepTrackingHash for $t {
2575 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
2576 Hash::hash(self, hasher);
2582 macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
2584 impl DepTrackingHash for Vec<$t> {
2585 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2586 let mut elems: Vec<&$t> = self.iter().collect();
2588 Hash::hash(&elems.len(), hasher);
2589 for (index, elem) in elems.iter().enumerate() {
2590 Hash::hash(&index, hasher);
2591 DepTrackingHash::hash(*elem, hasher, error_format);
2598 impl_dep_tracking_hash_via_hash!(bool);
2599 impl_dep_tracking_hash_via_hash!(usize);
2600 impl_dep_tracking_hash_via_hash!(u64);
2601 impl_dep_tracking_hash_via_hash!(String);
2602 impl_dep_tracking_hash_via_hash!(PathBuf);
2603 impl_dep_tracking_hash_via_hash!(lint::Level);
2604 impl_dep_tracking_hash_via_hash!(Option<bool>);
2605 impl_dep_tracking_hash_via_hash!(Option<usize>);
2606 impl_dep_tracking_hash_via_hash!(Option<String>);
2607 impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
2608 impl_dep_tracking_hash_via_hash!(Option<Vec<String>>);
2609 impl_dep_tracking_hash_via_hash!(Option<MergeFunctions>);
2610 impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
2611 impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
2612 impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
2613 impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
2614 impl_dep_tracking_hash_via_hash!(Option<cstore::NativeLibraryKind>);
2615 impl_dep_tracking_hash_via_hash!(CrateType);
2616 impl_dep_tracking_hash_via_hash!(MergeFunctions);
2617 impl_dep_tracking_hash_via_hash!(PanicStrategy);
2618 impl_dep_tracking_hash_via_hash!(RelroLevel);
2619 impl_dep_tracking_hash_via_hash!(Passes);
2620 impl_dep_tracking_hash_via_hash!(OptLevel);
2621 impl_dep_tracking_hash_via_hash!(LtoCli);
2622 impl_dep_tracking_hash_via_hash!(DebugInfo);
2623 impl_dep_tracking_hash_via_hash!(UnstableFeatures);
2624 impl_dep_tracking_hash_via_hash!(OutputTypes);
2625 impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
2626 impl_dep_tracking_hash_via_hash!(Sanitizer);
2627 impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
2628 impl_dep_tracking_hash_via_hash!(TargetTriple);
2629 impl_dep_tracking_hash_via_hash!(Edition);
2630 impl_dep_tracking_hash_via_hash!(LinkerPluginLto);
2631 impl_dep_tracking_hash_via_hash!(SwitchWithOptPath);
2633 impl_dep_tracking_hash_for_sortable_vec_of!(String);
2634 impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
2635 impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
2636 impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
2637 impl_dep_tracking_hash_for_sortable_vec_of!((
2640 Option<cstore::NativeLibraryKind>
2642 impl_dep_tracking_hash_for_sortable_vec_of!((String, u64));
2644 impl<T1, T2> DepTrackingHash for (T1, T2)
2646 T1: DepTrackingHash,
2647 T2: DepTrackingHash,
2649 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2650 Hash::hash(&0, hasher);
2651 DepTrackingHash::hash(&self.0, hasher, error_format);
2652 Hash::hash(&1, hasher);
2653 DepTrackingHash::hash(&self.1, hasher, error_format);
2657 impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
2659 T1: DepTrackingHash,
2660 T2: DepTrackingHash,
2661 T3: DepTrackingHash,
2663 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2664 Hash::hash(&0, hasher);
2665 DepTrackingHash::hash(&self.0, hasher, error_format);
2666 Hash::hash(&1, hasher);
2667 DepTrackingHash::hash(&self.1, hasher, error_format);
2668 Hash::hash(&2, hasher);
2669 DepTrackingHash::hash(&self.2, hasher, error_format);
2673 // This is a stable hash because BTreeMap is a sorted container
2675 sub_hashes: BTreeMap<&'static str, &dyn DepTrackingHash>,
2676 hasher: &mut DefaultHasher,
2677 error_format: ErrorOutputType,
2679 for (key, sub_hash) in sub_hashes {
2680 // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
2681 // the keys, as they are just plain strings
2682 Hash::hash(&key.len(), hasher);
2683 Hash::hash(key, hasher);
2684 sub_hash.hash(hasher, error_format);
2693 use crate::middle::cstore;
2694 use crate::session::config::{
2695 build_configuration,
2696 build_session_options_and_crate_config,
2699 use crate::session::config::{LtoCli, LinkerPluginLto, SwitchWithOptPath, ExternEntry};
2700 use crate::session::build_session;
2701 use crate::session::search_paths::SearchPath;
2702 use std::collections::{BTreeMap, BTreeSet};
2703 use std::iter::FromIterator;
2704 use std::path::PathBuf;
2705 use super::{Externs, OutputType, OutputTypes};
2706 use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel};
2707 use syntax::symbol::sym;
2708 use syntax::edition::{Edition, DEFAULT_EDITION};
2713 fn new_public<S: Into<String>,
2714 I: IntoIterator<Item = Option<S>>>(locations: I) -> ExternEntry {
2715 let locations: BTreeSet<_> = locations.into_iter().map(|o| o.map(|s| s.into()))
2720 is_private_dep: false
2725 fn optgroups() -> getopts::Options {
2726 let mut opts = getopts::Options::new();
2727 for group in super::rustc_optgroups() {
2728 (group.apply)(&mut opts);
2733 fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
2734 BTreeMap::from_iter(entries.into_iter())
2737 // When the user supplies --test we should implicitly supply --cfg test
2739 fn test_switch_implies_cfg_test() {
2740 syntax::with_default_globals(|| {
2741 let matches = &match optgroups().parse(&["--test".to_string()]) {
2743 Err(f) => panic!("test_switch_implies_cfg_test: {}", f),
2745 let registry = errors::registry::Registry::new(&[]);
2746 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2747 let sess = build_session(sessopts, None, registry);
2748 let cfg = build_configuration(&sess, to_crate_config(cfg));
2749 assert!(cfg.contains(&(sym::test, None)));
2753 // When the user supplies --test and --cfg test, don't implicitly add
2754 // another --cfg test
2756 fn test_switch_implies_cfg_test_unless_cfg_test() {
2757 syntax::with_default_globals(|| {
2758 let matches = &match optgroups().parse(&["--test".to_string(),
2759 "--cfg=test".to_string()]) {
2761 Err(f) => panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f),
2763 let registry = errors::registry::Registry::new(&[]);
2764 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2765 let sess = build_session(sessopts, None, registry);
2766 let cfg = build_configuration(&sess, to_crate_config(cfg));
2767 let mut test_items = cfg.iter().filter(|&&(name, _)| name == sym::test);
2768 assert!(test_items.next().is_some());
2769 assert!(test_items.next().is_none());
2774 fn test_can_print_warnings() {
2775 syntax::with_default_globals(|| {
2776 let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
2777 let registry = errors::registry::Registry::new(&[]);
2778 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2779 let sess = build_session(sessopts, None, registry);
2780 assert!(!sess.diagnostic().flags.can_emit_warnings);
2783 syntax::with_default_globals(|| {
2784 let matches = optgroups()
2785 .parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()])
2787 let registry = errors::registry::Registry::new(&[]);
2788 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2789 let sess = build_session(sessopts, None, registry);
2790 assert!(sess.diagnostic().flags.can_emit_warnings);
2793 syntax::with_default_globals(|| {
2794 let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
2795 let registry = errors::registry::Registry::new(&[]);
2796 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2797 let sess = build_session(sessopts, None, registry);
2798 assert!(sess.diagnostic().flags.can_emit_warnings);
2803 fn test_output_types_tracking_hash_different_paths() {
2804 let mut v1 = Options::default();
2805 let mut v2 = Options::default();
2806 let mut v3 = Options::default();
2809 OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("./some/thing")))]);
2811 OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("/some/thing")))]);
2812 v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
2814 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2815 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2816 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2819 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2820 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2821 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2825 fn test_output_types_tracking_hash_different_construction_order() {
2826 let mut v1 = Options::default();
2827 let mut v2 = Options::default();
2829 v1.output_types = OutputTypes::new(&[
2830 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2831 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2834 v2.output_types = OutputTypes::new(&[
2835 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2836 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2839 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2842 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2846 fn test_externs_tracking_hash_different_construction_order() {
2847 let mut v1 = Options::default();
2848 let mut v2 = Options::default();
2849 let mut v3 = Options::default();
2851 v1.externs = Externs::new(mk_map(vec![
2854 ExternEntry::new_public(vec![Some("b"), Some("c")])
2858 ExternEntry::new_public(vec![Some("e"), Some("f")])
2862 v2.externs = Externs::new(mk_map(vec![
2865 ExternEntry::new_public(vec![Some("e"), Some("f")])
2869 ExternEntry::new_public(vec![Some("b"), Some("c")])
2873 v3.externs = Externs::new(mk_map(vec![
2876 ExternEntry::new_public(vec![Some("b"), Some("c")])
2880 ExternEntry::new_public(vec![Some("f"), Some("e")])
2884 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2885 assert_eq!(v1.dep_tracking_hash(), v3.dep_tracking_hash());
2886 assert_eq!(v2.dep_tracking_hash(), v3.dep_tracking_hash());
2889 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2890 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2891 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2895 fn test_lints_tracking_hash_different_values() {
2896 let mut v1 = Options::default();
2897 let mut v2 = Options::default();
2898 let mut v3 = Options::default();
2900 v1.lint_opts = vec![
2901 (String::from("a"), lint::Allow),
2902 (String::from("b"), lint::Warn),
2903 (String::from("c"), lint::Deny),
2904 (String::from("d"), lint::Forbid),
2907 v2.lint_opts = vec![
2908 (String::from("a"), lint::Allow),
2909 (String::from("b"), lint::Warn),
2910 (String::from("X"), lint::Deny),
2911 (String::from("d"), lint::Forbid),
2914 v3.lint_opts = vec![
2915 (String::from("a"), lint::Allow),
2916 (String::from("b"), lint::Warn),
2917 (String::from("c"), lint::Forbid),
2918 (String::from("d"), lint::Deny),
2921 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2922 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2923 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2926 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2927 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2928 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2932 fn test_lints_tracking_hash_different_construction_order() {
2933 let mut v1 = Options::default();
2934 let mut v2 = Options::default();
2936 v1.lint_opts = vec![
2937 (String::from("a"), lint::Allow),
2938 (String::from("b"), lint::Warn),
2939 (String::from("c"), lint::Deny),
2940 (String::from("d"), lint::Forbid),
2943 v2.lint_opts = vec![
2944 (String::from("a"), lint::Allow),
2945 (String::from("c"), lint::Deny),
2946 (String::from("b"), lint::Warn),
2947 (String::from("d"), lint::Forbid),
2950 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2953 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2954 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2958 fn test_search_paths_tracking_hash_different_order() {
2959 let mut v1 = Options::default();
2960 let mut v2 = Options::default();
2961 let mut v3 = Options::default();
2962 let mut v4 = Options::default();
2964 const JSON: super::ErrorOutputType = super::ErrorOutputType::Json {
2966 json_rendered: super::HumanReadableErrorType::Default(super::ColorConfig::Never),
2971 .push(SearchPath::from_cli_opt("native=abc", JSON));
2973 .push(SearchPath::from_cli_opt("crate=def", JSON));
2975 .push(SearchPath::from_cli_opt("dependency=ghi", JSON));
2977 .push(SearchPath::from_cli_opt("framework=jkl", JSON));
2979 .push(SearchPath::from_cli_opt("all=mno", JSON));
2982 .push(SearchPath::from_cli_opt("native=abc", JSON));
2984 .push(SearchPath::from_cli_opt("dependency=ghi", JSON));
2986 .push(SearchPath::from_cli_opt("crate=def", JSON));
2988 .push(SearchPath::from_cli_opt("framework=jkl", JSON));
2990 .push(SearchPath::from_cli_opt("all=mno", JSON));
2993 .push(SearchPath::from_cli_opt("crate=def", JSON));
2995 .push(SearchPath::from_cli_opt("framework=jkl", JSON));
2997 .push(SearchPath::from_cli_opt("native=abc", JSON));
2999 .push(SearchPath::from_cli_opt("dependency=ghi", JSON));
3001 .push(SearchPath::from_cli_opt("all=mno", JSON));
3004 .push(SearchPath::from_cli_opt("all=mno", JSON));
3006 .push(SearchPath::from_cli_opt("native=abc", JSON));
3008 .push(SearchPath::from_cli_opt("crate=def", JSON));
3010 .push(SearchPath::from_cli_opt("dependency=ghi", JSON));
3012 .push(SearchPath::from_cli_opt("framework=jkl", JSON));
3014 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
3015 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
3016 assert!(v1.dep_tracking_hash() == v4.dep_tracking_hash());
3019 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
3020 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
3021 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
3022 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
3026 fn test_native_libs_tracking_hash_different_values() {
3027 let mut v1 = Options::default();
3028 let mut v2 = Options::default();
3029 let mut v3 = Options::default();
3030 let mut v4 = Options::default();
3034 (String::from("a"), None, Some(cstore::NativeStatic)),
3035 (String::from("b"), None, Some(cstore::NativeFramework)),
3036 (String::from("c"), None, Some(cstore::NativeUnknown)),
3041 (String::from("a"), None, Some(cstore::NativeStatic)),
3042 (String::from("X"), None, Some(cstore::NativeFramework)),
3043 (String::from("c"), None, Some(cstore::NativeUnknown)),
3048 (String::from("a"), None, Some(cstore::NativeStatic)),
3049 (String::from("b"), None, Some(cstore::NativeStatic)),
3050 (String::from("c"), None, Some(cstore::NativeUnknown)),
3055 (String::from("a"), None, Some(cstore::NativeStatic)),
3058 Some(String::from("X")),
3059 Some(cstore::NativeFramework),
3061 (String::from("c"), None, Some(cstore::NativeUnknown)),
3064 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
3065 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
3066 assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
3069 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
3070 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
3071 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
3072 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
3076 fn test_native_libs_tracking_hash_different_order() {
3077 let mut v1 = Options::default();
3078 let mut v2 = Options::default();
3079 let mut v3 = Options::default();
3083 (String::from("a"), None, Some(cstore::NativeStatic)),
3084 (String::from("b"), None, Some(cstore::NativeFramework)),
3085 (String::from("c"), None, Some(cstore::NativeUnknown)),
3089 (String::from("b"), None, Some(cstore::NativeFramework)),
3090 (String::from("a"), None, Some(cstore::NativeStatic)),
3091 (String::from("c"), None, Some(cstore::NativeUnknown)),
3095 (String::from("c"), None, Some(cstore::NativeUnknown)),
3096 (String::from("a"), None, Some(cstore::NativeStatic)),
3097 (String::from("b"), None, Some(cstore::NativeFramework)),
3100 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
3101 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
3102 assert!(v2.dep_tracking_hash() == v3.dep_tracking_hash());
3105 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
3106 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
3107 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
3111 fn test_codegen_options_tracking_hash() {
3112 let reference = Options::default();
3113 let mut opts = Options::default();
3115 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
3116 opts.cg.ar = Some(String::from("abc"));
3117 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3119 opts.cg.linker = Some(PathBuf::from("linker"));
3120 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3122 opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
3123 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3125 opts.cg.link_dead_code = true;
3126 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3128 opts.cg.rpath = true;
3129 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3131 opts.cg.extra_filename = String::from("extra-filename");
3132 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3134 opts.cg.codegen_units = Some(42);
3135 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3137 opts.cg.remark = super::Passes::Some(vec![String::from("pass1"), String::from("pass2")]);
3138 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3140 opts.cg.save_temps = true;
3141 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3143 opts.cg.incremental = Some(String::from("abc"));
3144 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3146 // Make sure changing a [TRACKED] option changes the hash
3147 opts = reference.clone();
3148 opts.cg.lto = LtoCli::Fat;
3149 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3151 opts = reference.clone();
3152 opts.cg.target_cpu = Some(String::from("abc"));
3153 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3155 opts = reference.clone();
3156 opts.cg.target_feature = String::from("all the features, all of them");
3157 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3159 opts = reference.clone();
3160 opts.cg.passes = vec![String::from("1"), String::from("2")];
3161 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3163 opts = reference.clone();
3164 opts.cg.llvm_args = vec![String::from("1"), String::from("2")];
3165 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3167 opts = reference.clone();
3168 opts.cg.overflow_checks = Some(true);
3169 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3171 opts = reference.clone();
3172 opts.cg.no_prepopulate_passes = true;
3173 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3175 opts = reference.clone();
3176 opts.cg.no_vectorize_loops = true;
3177 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3179 opts = reference.clone();
3180 opts.cg.no_vectorize_slp = true;
3181 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3183 opts = reference.clone();
3184 opts.cg.soft_float = true;
3185 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3187 opts = reference.clone();
3188 opts.cg.prefer_dynamic = true;
3189 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3191 opts = reference.clone();
3192 opts.cg.no_integrated_as = true;
3193 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3195 opts = reference.clone();
3196 opts.cg.no_redzone = Some(true);
3197 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3199 opts = reference.clone();
3200 opts.cg.relocation_model = Some(String::from("relocation model"));
3201 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3203 opts = reference.clone();
3204 opts.cg.code_model = Some(String::from("code model"));
3205 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3207 opts = reference.clone();
3208 opts.debugging_opts.tls_model = Some(String::from("tls model"));
3209 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3211 opts = reference.clone();
3212 opts.debugging_opts.pgo_gen = SwitchWithOptPath::Enabled(None);
3213 assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3215 opts = reference.clone();
3216 opts.debugging_opts.pgo_use = Some(PathBuf::from("abc"));
3217 assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3219 opts = reference.clone();
3220 opts.cg.metadata = vec![String::from("A"), String::from("B")];
3221 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3223 opts = reference.clone();
3224 opts.cg.debuginfo = Some(0xdeadbeef);
3225 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3227 opts = reference.clone();
3228 opts.cg.debuginfo = Some(0xba5eba11);
3229 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3231 opts = reference.clone();
3232 opts.cg.force_frame_pointers = Some(false);
3233 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3235 opts = reference.clone();
3236 opts.cg.debug_assertions = Some(true);
3237 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3239 opts = reference.clone();
3240 opts.cg.inline_threshold = Some(0xf007ba11);
3241 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3243 opts = reference.clone();
3244 opts.cg.panic = Some(PanicStrategy::Abort);
3245 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3247 opts = reference.clone();
3248 opts.cg.linker_plugin_lto = LinkerPluginLto::LinkerPluginAuto;
3249 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3253 fn test_debugging_options_tracking_hash() {
3254 let reference = Options::default();
3255 let mut opts = Options::default();
3257 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
3258 opts.debugging_opts.verbose = true;
3259 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3260 opts.debugging_opts.time_passes = true;
3261 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3262 opts.debugging_opts.count_llvm_insns = true;
3263 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3264 opts.debugging_opts.time_llvm_passes = true;
3265 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3266 opts.debugging_opts.input_stats = true;
3267 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3268 opts.debugging_opts.codegen_stats = true;
3269 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3270 opts.debugging_opts.borrowck_stats = true;
3271 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3272 opts.debugging_opts.meta_stats = true;
3273 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3274 opts.debugging_opts.print_link_args = true;
3275 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3276 opts.debugging_opts.print_llvm_passes = true;
3277 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3278 opts.debugging_opts.ast_json = true;
3279 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3280 opts.debugging_opts.ast_json_noexpand = true;
3281 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3282 opts.debugging_opts.ls = true;
3283 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3284 opts.debugging_opts.save_analysis = true;
3285 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3286 opts.debugging_opts.flowgraph_print_loans = true;
3287 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3288 opts.debugging_opts.flowgraph_print_moves = true;
3289 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3290 opts.debugging_opts.flowgraph_print_assigns = true;
3291 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3292 opts.debugging_opts.flowgraph_print_all = true;
3293 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3294 opts.debugging_opts.print_region_graph = true;
3295 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3296 opts.debugging_opts.parse_only = true;
3297 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3298 opts.debugging_opts.incremental = Some(String::from("abc"));
3299 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3300 opts.debugging_opts.dump_dep_graph = true;
3301 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3302 opts.debugging_opts.query_dep_graph = true;
3303 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3304 opts.debugging_opts.no_analysis = true;
3305 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3306 opts.debugging_opts.unstable_options = true;
3307 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3308 opts.debugging_opts.trace_macros = true;
3309 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3310 opts.debugging_opts.keep_hygiene_data = true;
3311 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3312 opts.debugging_opts.keep_ast = true;
3313 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3314 opts.debugging_opts.print_mono_items = Some(String::from("abc"));
3315 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3316 opts.debugging_opts.dump_mir = Some(String::from("abc"));
3317 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3318 opts.debugging_opts.dump_mir_dir = String::from("abc");
3319 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3320 opts.debugging_opts.dump_mir_graphviz = true;
3321 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3323 // Make sure changing a [TRACKED] option changes the hash
3324 opts = reference.clone();
3325 opts.debugging_opts.asm_comments = true;
3326 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3328 opts = reference.clone();
3329 opts.debugging_opts.verify_llvm_ir = true;
3330 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3332 opts = reference.clone();
3333 opts.debugging_opts.no_landing_pads = true;
3334 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3336 opts = reference.clone();
3337 opts.debugging_opts.fewer_names = true;
3338 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3340 opts = reference.clone();
3341 opts.debugging_opts.no_codegen = true;
3342 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3344 opts = reference.clone();
3345 opts.debugging_opts.treat_err_as_bug = Some(1);
3346 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3348 opts = reference.clone();
3349 opts.debugging_opts.report_delayed_bugs = true;
3350 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3352 opts = reference.clone();
3353 opts.debugging_opts.continue_parse_after_error = true;
3354 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3356 opts = reference.clone();
3357 opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
3358 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3360 opts = reference.clone();
3361 opts.debugging_opts.force_overflow_checks = Some(true);
3362 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3364 opts = reference.clone();
3365 opts.debugging_opts.show_span = Some(String::from("abc"));
3366 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3368 opts = reference.clone();
3369 opts.debugging_opts.mir_opt_level = 3;
3370 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3372 opts = reference.clone();
3373 opts.debugging_opts.relro_level = Some(RelroLevel::Full);
3374 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3376 opts = reference.clone();
3377 opts.debugging_opts.merge_functions = Some(MergeFunctions::Disabled);
3378 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3380 opts = reference.clone();
3381 opts.debugging_opts.allow_features = Some(vec![String::from("lang_items")]);
3382 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3386 fn test_edition_parsing() {
3387 // test default edition
3388 let options = Options::default();
3389 assert!(options.edition == DEFAULT_EDITION);
3391 let matches = optgroups()
3392 .parse(&["--edition=2018".to_string()])
3394 let (sessopts, _) = build_session_options_and_crate_config(&matches);
3395 assert!(sessopts.edition == Edition::Edition2018)