1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Contains infrastructure for configuring the compiler, including parsing
12 //! command line options.
14 use std::str::FromStr;
16 use session::{early_error, early_warn, Session};
17 use session::search_paths::SearchPaths;
19 use rustc_target::spec::{LinkerFlavor, PanicStrategy, RelroLevel};
20 use rustc_target::spec::{Target, TargetTriple};
24 use syntax::ast::{self, IntTy, UintTy, MetaItemKind};
25 use syntax::source_map::{FileName, FilePathMapping};
26 use syntax::edition::{Edition, EDITION_NAME_LIST, DEFAULT_EDITION};
27 use syntax::parse::token;
29 use syntax::symbol::Symbol;
30 use syntax::feature_gate::UnstableFeatures;
32 use errors::{ColorConfig, FatalError, Handler};
35 use std::collections::{BTreeMap, BTreeSet};
36 use std::collections::btree_map::Iter as BTreeMapIter;
37 use std::collections::btree_map::Keys as BTreeMapKeysIter;
38 use std::collections::btree_map::Values as BTreeMapValuesIter;
40 use rustc_data_structures::fx::FxHashSet;
42 use std::hash::Hasher;
43 use std::collections::hash_map::DefaultHasher;
44 use std::iter::FromIterator;
45 use std::path::{Path, PathBuf};
53 #[derive(Clone, Hash, Debug)]
61 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
71 /// This is what the `LtoCli` values get mapped to after resolving defaults and
72 /// and taking other command line options into account.
73 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
75 /// Don't do any LTO whatsoever
78 /// Do a full crate graph LTO with ThinLTO
81 /// Do a local graph LTO with ThinLTO (only relevant for multiple codegen
85 /// Do a full crate graph LTO with "fat" LTO
89 /// The different settings that the `-C lto` flag can have.
90 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
102 /// No `-C lto` flag passed
106 #[derive(Clone, PartialEq, Hash)]
107 pub enum CrossLangLto {
108 LinkerPlugin(PathBuf),
114 pub fn enabled(&self) -> bool {
116 CrossLangLto::LinkerPlugin(_) |
117 CrossLangLto::LinkerPluginAuto => true,
118 CrossLangLto::Disabled => false,
123 #[derive(Clone, Copy, PartialEq, Hash)]
130 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
131 pub enum OutputType {
142 impl_stable_hash_via_hash!(OutputType);
145 fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
147 OutputType::Exe | OutputType::DepInfo => true,
149 | OutputType::Assembly
150 | OutputType::LlvmAssembly
153 | OutputType::Metadata => false,
157 fn shorthand(&self) -> &'static str {
159 OutputType::Bitcode => "llvm-bc",
160 OutputType::Assembly => "asm",
161 OutputType::LlvmAssembly => "llvm-ir",
162 OutputType::Mir => "mir",
163 OutputType::Object => "obj",
164 OutputType::Metadata => "metadata",
165 OutputType::Exe => "link",
166 OutputType::DepInfo => "dep-info",
170 fn from_shorthand(shorthand: &str) -> Option<Self> {
171 Some(match shorthand {
172 "asm" => OutputType::Assembly,
173 "llvm-ir" => OutputType::LlvmAssembly,
174 "mir" => OutputType::Mir,
175 "llvm-bc" => OutputType::Bitcode,
176 "obj" => OutputType::Object,
177 "metadata" => OutputType::Metadata,
178 "link" => OutputType::Exe,
179 "dep-info" => OutputType::DepInfo,
184 fn shorthands_display() -> String {
186 "`{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`",
187 OutputType::Bitcode.shorthand(),
188 OutputType::Assembly.shorthand(),
189 OutputType::LlvmAssembly.shorthand(),
190 OutputType::Mir.shorthand(),
191 OutputType::Object.shorthand(),
192 OutputType::Metadata.shorthand(),
193 OutputType::Exe.shorthand(),
194 OutputType::DepInfo.shorthand(),
198 pub fn extension(&self) -> &'static str {
200 OutputType::Bitcode => "bc",
201 OutputType::Assembly => "s",
202 OutputType::LlvmAssembly => "ll",
203 OutputType::Mir => "mir",
204 OutputType::Object => "o",
205 OutputType::Metadata => "rmeta",
206 OutputType::DepInfo => "d",
207 OutputType::Exe => "",
212 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
213 pub enum ErrorOutputType {
214 HumanReadable(ColorConfig),
219 impl Default for ErrorOutputType {
220 fn default() -> ErrorOutputType {
221 ErrorOutputType::HumanReadable(ColorConfig::Auto)
225 // Use tree-based collections to cheaply get a deterministic Hash implementation.
226 // DO NOT switch BTreeMap out for an unsorted container type! That would break
227 // dependency tracking for commandline arguments.
228 #[derive(Clone, Hash)]
229 pub struct OutputTypes(BTreeMap<OutputType, Option<PathBuf>>);
231 impl_stable_hash_via_hash!(OutputTypes);
234 pub fn new(entries: &[(OutputType, Option<PathBuf>)]) -> OutputTypes {
235 OutputTypes(BTreeMap::from_iter(
236 entries.iter().map(|&(k, ref v)| (k, v.clone())),
240 pub fn get(&self, key: &OutputType) -> Option<&Option<PathBuf>> {
244 pub fn contains_key(&self, key: &OutputType) -> bool {
245 self.0.contains_key(key)
248 pub fn keys<'a>(&'a self) -> BTreeMapKeysIter<'a, OutputType, Option<PathBuf>> {
252 pub fn values<'a>(&'a self) -> BTreeMapValuesIter<'a, OutputType, Option<PathBuf>> {
256 pub fn len(&self) -> usize {
260 // True if any of the output types require codegen or linking.
261 pub fn should_codegen(&self) -> bool {
262 self.0.keys().any(|k| match *k {
264 | OutputType::Assembly
265 | OutputType::LlvmAssembly
268 | OutputType::Exe => true,
269 OutputType::Metadata | OutputType::DepInfo => false,
274 // Use tree-based collections to cheaply get a deterministic Hash implementation.
275 // DO NOT switch BTreeMap or BTreeSet out for an unsorted container type! That
276 // would break dependency tracking for commandline arguments.
277 #[derive(Clone, Hash)]
278 pub struct Externs(BTreeMap<String, BTreeSet<Option<String>>>);
281 pub fn new(data: BTreeMap<String, BTreeSet<Option<String>>>) -> Externs {
285 pub fn get(&self, key: &str) -> Option<&BTreeSet<Option<String>>> {
289 pub fn iter<'a>(&'a self) -> BTreeMapIter<'a, String, BTreeSet<Option<String>>> {
294 macro_rules! hash_option {
295 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [UNTRACKED]) => ({});
296 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({
297 if $sub_hashes.insert(stringify!($opt_name),
298 $opt_expr as &dyn dep_tracking::DepTrackingHash).is_some() {
299 bug!("Duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
305 [UNTRACKED_WITH_WARNING $warn_val:expr, $warn_text:expr, $error_format:expr]) => ({
306 if *$opt_expr == $warn_val {
307 early_warn($error_format, $warn_text)
312 macro_rules! top_level_options {
313 (pub struct Options { $(
314 $opt:ident : $t:ty [$dep_tracking_marker:ident $($warn_val:expr, $warn_text:expr)*],
322 pub fn dep_tracking_hash(&self) -> u64 {
323 let mut sub_hashes = BTreeMap::new();
328 [$dep_tracking_marker $($warn_val,
330 self.error_format)*]);
332 let mut hasher = DefaultHasher::new();
333 dep_tracking::stable_hash(sub_hashes,
342 // The top-level commandline options struct
344 // For each option, one has to specify how it behaves with regard to the
345 // dependency tracking system of incremental compilation. This is done via the
346 // square-bracketed directive after the field type. The options are:
349 // A change in the given field will cause the compiler to completely clear the
350 // incremental compilation cache before proceeding.
353 // Incremental compilation is not influenced by this option.
355 // [UNTRACKED_WITH_WARNING(val, warning)]
356 // The option is incompatible with incremental compilation in some way. If it
357 // has the value `val`, the string `warning` is emitted as a warning.
359 // If you add a new option to this struct or one of the sub-structs like
360 // CodegenOptions, think about how it influences incremental compilation. If in
361 // doubt, specify [TRACKED], which is always "correct" but might lead to
362 // unnecessary re-compilation.
365 // The crate config requested for the session, which may be combined
366 // with additional crate configurations during the compile process
367 crate_types: Vec<CrateType> [TRACKED],
368 optimize: OptLevel [TRACKED],
369 // Include the debug_assertions flag into dependency tracking, since it
370 // can influence whether overflow checks are done or not.
371 debug_assertions: bool [TRACKED],
372 debuginfo: DebugInfo [TRACKED],
373 lint_opts: Vec<(String, lint::Level)> [TRACKED],
374 lint_cap: Option<lint::Level> [TRACKED],
375 describe_lints: bool [UNTRACKED],
376 output_types: OutputTypes [TRACKED],
377 search_paths: SearchPaths [UNTRACKED],
378 libs: Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> [TRACKED],
379 maybe_sysroot: Option<PathBuf> [TRACKED],
381 target_triple: TargetTriple [TRACKED],
383 test: bool [TRACKED],
384 error_format: ErrorOutputType [UNTRACKED],
386 // if Some, enable incremental compilation, using the given
387 // directory to store intermediate results
388 incremental: Option<PathBuf> [UNTRACKED],
390 debugging_opts: DebuggingOptions [TRACKED],
391 prints: Vec<PrintRequest> [UNTRACKED],
392 // Determines which borrow checker(s) to run. This is the parsed, sanitized
393 // version of `debugging_opts.borrowck`, which is just a plain string.
394 borrowck_mode: BorrowckMode [UNTRACKED],
395 cg: CodegenOptions [TRACKED],
396 externs: Externs [UNTRACKED],
397 crate_name: Option<String> [TRACKED],
398 // An optional name to use as the crate for std during std injection,
399 // written `extern crate name as std`. Defaults to `std`. Used by
400 // out-of-tree drivers.
401 alt_std_name: Option<String> [TRACKED],
402 // Indicates how the compiler should treat unstable features
403 unstable_features: UnstableFeatures [TRACKED],
405 // Indicates whether this run of the compiler is actually rustdoc. This
406 // is currently just a hack and will be removed eventually, so please
407 // try to not rely on this too much.
408 actually_rustdoc: bool [TRACKED],
410 // Specifications of codegen units / ThinLTO which are forced as a
411 // result of parsing command line options. These are not necessarily
412 // what rustc was invoked with, but massaged a bit to agree with
413 // commands like `--emit llvm-ir` which they're often incompatible with
414 // if we otherwise use the defaults of rustc.
415 cli_forced_codegen_units: Option<usize> [UNTRACKED],
416 cli_forced_thinlto_off: bool [UNTRACKED],
418 // Remap source path prefixes in all output (messages, object files, debug, etc)
419 remap_path_prefix: Vec<(PathBuf, PathBuf)> [UNTRACKED],
421 edition: Edition [TRACKED],
425 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
426 pub enum PrintRequest {
441 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
442 pub enum BorrowckMode {
450 /// Should we run the MIR-based borrow check, but also fall back
451 /// on the AST borrow check if the MIR-based one errors.
452 pub fn migrate(self) -> bool {
454 BorrowckMode::Ast => false,
455 BorrowckMode::Compare => false,
456 BorrowckMode::Mir => false,
457 BorrowckMode::Migrate => true,
461 /// Should we emit the AST-based borrow checker errors?
462 pub fn use_ast(self) -> bool {
464 BorrowckMode::Ast => true,
465 BorrowckMode::Compare => true,
466 BorrowckMode::Mir => false,
467 BorrowckMode::Migrate => false,
470 /// Should we emit the MIR-based borrow checker errors?
471 pub fn use_mir(self) -> bool {
473 BorrowckMode::Ast => false,
474 BorrowckMode::Compare => true,
475 BorrowckMode::Mir => true,
476 BorrowckMode::Migrate => true,
482 /// Load source from file
485 /// String that is shown in place of a filename
487 /// Anonymous source string
493 pub fn filestem(&self) -> String {
495 Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap().to_string(),
496 Input::Str { .. } => "rust_out".to_string(),
500 pub fn get_input(&mut self) -> Option<&mut String> {
502 Input::File(_) => None,
503 Input::Str { ref mut input, .. } => Some(input),
508 #[derive(Clone, Hash)]
509 pub struct OutputFilenames {
510 pub out_directory: PathBuf,
511 pub out_filestem: String,
512 pub single_output_file: Option<PathBuf>,
514 pub outputs: OutputTypes,
517 impl_stable_hash_via_hash!(OutputFilenames);
519 pub const RUST_CGU_EXT: &str = "rcgu";
521 impl OutputFilenames {
522 pub fn path(&self, flavor: OutputType) -> PathBuf {
525 .and_then(|p| p.to_owned())
526 .or_else(|| self.single_output_file.clone())
527 .unwrap_or_else(|| self.temp_path(flavor, None))
530 /// Get the path where a compilation artifact of the given type for the
531 /// given codegen unit should be placed on disk. If codegen_unit_name is
532 /// None, a path distinct from those of any codegen unit will be generated.
533 pub fn temp_path(&self, flavor: OutputType, codegen_unit_name: Option<&str>) -> PathBuf {
534 let extension = flavor.extension();
535 self.temp_path_ext(extension, codegen_unit_name)
538 /// Like temp_path, but also supports things where there is no corresponding
539 /// OutputType, like no-opt-bitcode or lto-bitcode.
540 pub fn temp_path_ext(&self, ext: &str, codegen_unit_name: Option<&str>) -> PathBuf {
541 let base = self.out_directory.join(&self.filestem());
543 let mut extension = String::new();
545 if let Some(codegen_unit_name) = codegen_unit_name {
546 extension.push_str(codegen_unit_name);
550 if !extension.is_empty() {
551 extension.push_str(".");
552 extension.push_str(RUST_CGU_EXT);
553 extension.push_str(".");
556 extension.push_str(ext);
559 let path = base.with_extension(&extension[..]);
563 pub fn with_extension(&self, extension: &str) -> PathBuf {
565 .join(&self.filestem())
566 .with_extension(extension)
569 pub fn filestem(&self) -> String {
570 format!("{}{}", self.out_filestem, self.extra)
574 pub fn host_triple() -> &'static str {
575 // Get the host triple out of the build environment. This ensures that our
576 // idea of the host triple is the same as for the set of libraries we've
577 // actually built. We can't just take LLVM's host triple because they
578 // normalize all ix86 architectures to i386.
580 // Instead of grabbing the host triple (for the current host), we grab (at
581 // compile time) the target triple that this rustc is built with and
582 // calling that (at runtime) the host triple.
583 (option_env!("CFG_COMPILER_HOST_TRIPLE")).expect("CFG_COMPILER_HOST_TRIPLE")
586 impl Default for Options {
587 fn default() -> Options {
589 crate_types: Vec::new(),
590 optimize: OptLevel::No,
591 debuginfo: DebugInfo::None,
592 lint_opts: Vec::new(),
594 describe_lints: false,
595 output_types: OutputTypes(BTreeMap::new()),
596 search_paths: SearchPaths::new(),
598 target_triple: TargetTriple::from_triple(host_triple()),
601 debugging_opts: basic_debugging_options(),
603 borrowck_mode: BorrowckMode::Ast,
604 cg: basic_codegen_options(),
605 error_format: ErrorOutputType::default(),
606 externs: Externs(BTreeMap::new()),
610 unstable_features: UnstableFeatures::Disallow,
611 debug_assertions: true,
612 actually_rustdoc: false,
613 cli_forced_codegen_units: None,
614 cli_forced_thinlto_off: false,
615 remap_path_prefix: Vec::new(),
616 edition: DEFAULT_EDITION,
622 /// True if there is a reason to build the dep graph.
623 pub fn build_dep_graph(&self) -> bool {
624 self.incremental.is_some() || self.debugging_opts.dump_dep_graph
625 || self.debugging_opts.query_dep_graph
629 pub fn enable_dep_node_debug_strs(&self) -> bool {
630 cfg!(debug_assertions)
631 && (self.debugging_opts.query_dep_graph || self.debugging_opts.incremental_info)
634 pub fn file_path_mapping(&self) -> FilePathMapping {
635 FilePathMapping::new(self.remap_path_prefix.clone())
638 /// True if there will be an output file generated
639 pub fn will_create_output_file(&self) -> bool {
640 !self.debugging_opts.parse_only && // The file is just being parsed
641 !self.debugging_opts.ls // The file is just being queried
645 pub fn share_generics(&self) -> bool {
646 match self.debugging_opts.share_generics {
647 Some(setting) => setting,
649 match self.optimize {
653 OptLevel::SizeMin => true,
655 OptLevel::Aggressive => false,
662 // The type of entry function, so
663 // users can have their own entry
665 #[derive(Copy, Clone, PartialEq)]
666 pub enum EntryFnType {
671 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
681 #[derive(Clone, Hash)]
688 pub fn is_empty(&self) -> bool {
690 Passes::Some(ref v) => v.is_empty(),
691 Passes::All => false,
696 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
697 /// at once. The goal of this macro is to define an interface that can be
698 /// programmatically used by the option parser in order to initialize the struct
699 /// without hardcoding field names all over the place.
701 /// The goal is to invoke this macro once with the correct fields, and then this
702 /// macro generates all necessary code. The main gotcha of this macro is the
703 /// cgsetters module which is a bunch of generated code to parse an option into
704 /// its respective field in the struct. There are a few hand-written parsers for
705 /// parsing specific types of values in this module.
706 macro_rules! options {
707 ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
708 $buildfn:ident, $prefix:expr, $outputname:expr,
709 $stat:ident, $mod_desc:ident, $mod_set:ident,
710 $($opt:ident : $t:ty = (
713 [$dep_tracking_marker:ident $(($dep_warn_val:expr, $dep_warn_text:expr))*],
718 pub struct $struct_name { $(pub $opt: $t),* }
720 pub fn $defaultfn() -> $struct_name {
721 $struct_name { $($opt: $init),* }
724 pub fn $buildfn(matches: &getopts::Matches, error_format: ErrorOutputType) -> $struct_name
726 let mut op = $defaultfn();
727 for option in matches.opt_strs($prefix) {
728 let mut iter = option.splitn(2, '=');
729 let key = iter.next().unwrap();
730 let value = iter.next();
731 let option_to_lookup = key.replace("-", "_");
732 let mut found = false;
733 for &(candidate, setter, opt_type_desc, _) in $stat {
734 if option_to_lookup != candidate { continue }
735 if !setter(&mut op, value) {
736 match (value, opt_type_desc) {
737 (Some(..), None) => {
738 early_error(error_format, &format!("{} option `{}` takes no \
739 value", $outputname, key))
741 (None, Some(type_desc)) => {
742 early_error(error_format, &format!("{0} option `{1}` requires \
743 {2} ({3} {1}=<value>)",
747 (Some(value), Some(type_desc)) => {
748 early_error(error_format, &format!("incorrect value `{}` for {} \
749 option `{}` - {} was expected",
753 (None, None) => bug!()
760 early_error(error_format, &format!("unknown {} option: `{}`",
767 impl<'a> dep_tracking::DepTrackingHash for $struct_name {
769 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
770 let mut sub_hashes = BTreeMap::new();
775 [$dep_tracking_marker $($dep_warn_val,
779 dep_tracking::stable_hash(sub_hashes, hasher, error_format);
783 pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
784 pub const $stat: &'static [(&'static str, $setter_name,
785 Option<&'static str>, &'static str)] =
786 &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
788 #[allow(non_upper_case_globals, dead_code)]
790 pub const parse_bool: Option<&'static str> = None;
791 pub const parse_opt_bool: Option<&'static str> =
792 Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
793 pub const parse_string: Option<&'static str> = Some("a string");
794 pub const parse_string_push: Option<&'static str> = Some("a string");
795 pub const parse_pathbuf_push: Option<&'static str> = Some("a path");
796 pub const parse_opt_string: Option<&'static str> = Some("a string");
797 pub const parse_opt_pathbuf: Option<&'static str> = Some("a path");
798 pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
799 pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
800 pub const parse_uint: Option<&'static str> = Some("a number");
801 pub const parse_passes: Option<&'static str> =
802 Some("a space-separated list of passes, or `all`");
803 pub const parse_opt_uint: Option<&'static str> =
805 pub const parse_panic_strategy: Option<&'static str> =
806 Some("either `panic` or `abort`");
807 pub const parse_relro_level: Option<&'static str> =
808 Some("one of: `full`, `partial`, or `off`");
809 pub const parse_sanitizer: Option<&'static str> =
810 Some("one of: `address`, `leak`, `memory` or `thread`");
811 pub const parse_linker_flavor: Option<&'static str> =
812 Some(::rustc_target::spec::LinkerFlavor::one_of());
813 pub const parse_optimization_fuel: Option<&'static str> =
814 Some("crate=integer");
815 pub const parse_unpretty: Option<&'static str> =
816 Some("`string` or `string=string`");
817 pub const parse_lto: Option<&'static str> =
818 Some("either a boolean (`yes`, `no`, `on`, `off`, etc), `thin`, \
820 pub const parse_cross_lang_lto: Option<&'static str> =
821 Some("either a boolean (`yes`, `no`, `on`, `off`, etc), \
822 or the path to the linker plugin");
827 use super::{$struct_name, Passes, Sanitizer, LtoCli, CrossLangLto};
828 use rustc_target::spec::{LinkerFlavor, PanicStrategy, RelroLevel};
829 use std::path::PathBuf;
832 pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
833 $parse(&mut cg.$opt, v)
837 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
840 None => { *slot = true; true }
844 fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
848 "n" | "no" | "off" => {
851 "y" | "yes" | "on" => {
854 _ => { return false; }
859 None => { *slot = Some(true); true }
863 fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
865 Some(s) => { *slot = Some(s.to_string()); true },
870 fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
872 Some(s) => { *slot = Some(PathBuf::from(s)); true },
877 fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
879 Some(s) => { *slot = s.to_string(); true },
884 fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
886 Some(s) => { slot.push(s.to_string()); true },
891 fn parse_pathbuf_push(slot: &mut Vec<PathBuf>, v: Option<&str>) -> bool {
893 Some(s) => { slot.push(PathBuf::from(s)); true },
898 fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
902 slot.extend(s.split_whitespace().map(|s| s.to_string()));
909 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
913 let v = s.split_whitespace().map(|s| s.to_string()).collect();
921 fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
922 match v.and_then(|s| s.parse().ok()) {
923 Some(i) => { *slot = i; true },
928 fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
930 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
931 None => { *slot = None; false }
935 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
942 let mut passes = vec![];
943 if parse_list(&mut passes, v) {
944 *slot = Passes::Some(passes);
953 fn parse_panic_strategy(slot: &mut Option<PanicStrategy>, v: Option<&str>) -> bool {
955 Some("unwind") => *slot = Some(PanicStrategy::Unwind),
956 Some("abort") => *slot = Some(PanicStrategy::Abort),
962 fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
965 match s.parse::<RelroLevel>() {
966 Ok(level) => *slot = Some(level),
975 fn parse_sanitizer(slote: &mut Option<Sanitizer>, v: Option<&str>) -> bool {
977 Some("address") => *slote = Some(Sanitizer::Address),
978 Some("leak") => *slote = Some(Sanitizer::Leak),
979 Some("memory") => *slote = Some(Sanitizer::Memory),
980 Some("thread") => *slote = Some(Sanitizer::Thread),
986 fn parse_linker_flavor(slote: &mut Option<LinkerFlavor>, v: Option<&str>) -> bool {
987 match v.and_then(LinkerFlavor::from_str) {
988 Some(lf) => *slote = Some(lf),
994 fn parse_optimization_fuel(slot: &mut Option<(String, u64)>, v: Option<&str>) -> bool {
998 let parts = s.split('=').collect::<Vec<_>>();
999 if parts.len() != 2 { return false; }
1000 let crate_name = parts[0].to_string();
1001 let fuel = parts[1].parse::<u64>();
1002 if fuel.is_err() { return false; }
1003 *slot = Some((crate_name, fuel.unwrap()));
1009 fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
1012 Some(s) if s.split('=').count() <= 2 => {
1013 *slot = Some(s.to_string());
1020 fn parse_lto(slot: &mut LtoCli, v: Option<&str>) -> bool {
1022 let mut bool_arg = None;
1023 if parse_opt_bool(&mut bool_arg, v) {
1024 *slot = if bool_arg.unwrap() {
1034 None => LtoCli::NoParam,
1035 Some("thin") => LtoCli::Thin,
1036 Some("fat") => LtoCli::Fat,
1037 Some(_) => return false,
1042 fn parse_cross_lang_lto(slot: &mut CrossLangLto, v: Option<&str>) -> bool {
1044 let mut bool_arg = None;
1045 if parse_opt_bool(&mut bool_arg, v) {
1046 *slot = if bool_arg.unwrap() {
1047 CrossLangLto::LinkerPluginAuto
1049 CrossLangLto::Disabled
1056 None => CrossLangLto::LinkerPluginAuto,
1057 Some(path) => CrossLangLto::LinkerPlugin(PathBuf::from(path)),
1064 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
1065 build_codegen_options, "C", "codegen",
1066 CG_OPTIONS, cg_type_desc, cgsetters,
1067 ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
1068 "this option is deprecated and does nothing"),
1069 linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
1070 "system linker to link outputs with"),
1071 link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1072 "a single extra argument to append to the linker invocation (can be used several times)"),
1073 link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1074 "extra arguments to append to the linker invocation (space separated)"),
1075 link_dead_code: bool = (false, parse_bool, [UNTRACKED],
1076 "don't let linker strip dead code (turning it on can be used for code coverage)"),
1077 lto: LtoCli = (LtoCli::Unspecified, parse_lto, [TRACKED],
1078 "perform LLVM link-time optimizations"),
1079 target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
1080 "select target processor (rustc --print target-cpus for details)"),
1081 target_feature: String = (String::new(), parse_string, [TRACKED],
1082 "target specific attributes (rustc --print target-features for details)"),
1083 passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1084 "a list of extra LLVM passes to run (space separated)"),
1085 llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1086 "a list of arguments to pass to llvm (space separated)"),
1087 save_temps: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1088 "`-C save-temps` might not produce all requested temporary products \
1089 when incremental compilation is enabled.")],
1090 "save all temporary output files during compilation"),
1091 rpath: bool = (false, parse_bool, [UNTRACKED],
1092 "set rpath values in libs/exes"),
1093 overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1094 "use overflow checks for integer arithmetic"),
1095 no_prepopulate_passes: bool = (false, parse_bool, [TRACKED],
1096 "don't pre-populate the pass manager with a list of passes"),
1097 no_vectorize_loops: bool = (false, parse_bool, [TRACKED],
1098 "don't run the loop vectorization optimization passes"),
1099 no_vectorize_slp: bool = (false, parse_bool, [TRACKED],
1100 "don't run LLVM's SLP vectorization pass"),
1101 soft_float: bool = (false, parse_bool, [TRACKED],
1102 "use soft float ABI (*eabihf targets only)"),
1103 prefer_dynamic: bool = (false, parse_bool, [TRACKED],
1104 "prefer dynamic linking to static linking"),
1105 no_integrated_as: bool = (false, parse_bool, [TRACKED],
1106 "use an external assembler rather than LLVM's integrated one"),
1107 no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
1108 "disable the use of the redzone"),
1109 relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
1110 "choose the relocation model to use (rustc --print relocation-models for details)"),
1111 code_model: Option<String> = (None, parse_opt_string, [TRACKED],
1112 "choose the code model to use (rustc --print code-models for details)"),
1113 metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1114 "metadata to mangle symbol names with"),
1115 extra_filename: String = (String::new(), parse_string, [UNTRACKED],
1116 "extra data to put in each output filename"),
1117 codegen_units: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1118 "divide crate into N units to optimize in parallel"),
1119 remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
1120 "print remarks for these optimization passes (space separated, or \"all\")"),
1121 no_stack_check: bool = (false, parse_bool, [UNTRACKED],
1122 "the --no-stack-check flag is deprecated and does nothing"),
1123 debuginfo: Option<usize> = (None, parse_opt_uint, [TRACKED],
1124 "debug info emission level, 0 = no debug info, 1 = line tables only, \
1125 2 = full debug info with variable and type information"),
1126 opt_level: Option<String> = (None, parse_opt_string, [TRACKED],
1127 "optimize with possible levels 0-3, s, or z"),
1128 force_frame_pointers: Option<bool> = (None, parse_opt_bool, [TRACKED],
1129 "force use of the frame pointers"),
1130 debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
1131 "explicitly enable the cfg(debug_assertions) directive"),
1132 inline_threshold: Option<usize> = (None, parse_opt_uint, [TRACKED],
1133 "set the threshold for inlining a function (default: 225)"),
1134 panic: Option<PanicStrategy> = (None, parse_panic_strategy,
1135 [TRACKED], "panic strategy to compile crate with"),
1136 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1137 "enable incremental compilation"),
1140 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
1141 build_debugging_options, "Z", "debugging",
1142 DB_OPTIONS, db_type_desc, dbsetters,
1143 codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
1144 "the backend to use"),
1145 verbose: bool = (false, parse_bool, [UNTRACKED],
1146 "in general, enable more debug printouts"),
1147 span_free_formats: bool = (false, parse_bool, [UNTRACKED],
1148 "when debug-printing compiler state, do not include spans"), // o/w tests have closure@path
1149 identify_regions: bool = (false, parse_bool, [UNTRACKED],
1150 "make unnamed regions display as '# (where # is some non-ident unique id)"),
1151 emit_end_regions: bool = (false, parse_bool, [UNTRACKED],
1152 "emit EndRegion as part of MIR; enable transforms that solely process EndRegion"),
1153 borrowck: Option<String> = (None, parse_opt_string, [UNTRACKED],
1154 "select which borrowck is used (`ast`, `mir`, `migrate`, or `compare`)"),
1155 two_phase_borrows: bool = (false, parse_bool, [UNTRACKED],
1156 "use two-phase reserved/active distinction for `&mut` borrows in MIR borrowck"),
1157 two_phase_beyond_autoref: bool = (false, parse_bool, [UNTRACKED],
1158 "when using two-phase-borrows, allow two phases even for non-autoref `&mut` borrows"),
1159 time_passes: bool = (false, parse_bool, [UNTRACKED],
1160 "measure time of each rustc pass"),
1161 count_llvm_insns: bool = (false, parse_bool,
1162 [UNTRACKED_WITH_WARNING(true,
1163 "The output generated by `-Z count_llvm_insns` might not be reliable \
1164 when used with incremental compilation")],
1165 "count where LLVM instrs originate"),
1166 time_llvm_passes: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1167 "The output of `-Z time-llvm-passes` will only reflect timings of \
1168 re-codegened modules when used with incremental compilation" )],
1169 "measure time of each LLVM pass"),
1170 input_stats: bool = (false, parse_bool, [UNTRACKED],
1171 "gather statistics about the input"),
1172 codegen_stats: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1173 "The output of `-Z codegen-stats` might not be accurate when incremental \
1174 compilation is enabled")],
1175 "gather codegen statistics"),
1176 asm_comments: bool = (false, parse_bool, [TRACKED],
1177 "generate comments into the assembly (may change behavior)"),
1178 verify_llvm_ir: bool = (false, parse_bool, [TRACKED],
1180 borrowck_stats: bool = (false, parse_bool, [UNTRACKED],
1181 "gather borrowck statistics"),
1182 no_landing_pads: bool = (false, parse_bool, [TRACKED],
1183 "omit landing pads for unwinding"),
1184 fewer_names: bool = (false, parse_bool, [TRACKED],
1185 "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR)"),
1186 meta_stats: bool = (false, parse_bool, [UNTRACKED],
1187 "gather metadata statistics"),
1188 print_link_args: bool = (false, parse_bool, [UNTRACKED],
1189 "print the arguments passed to the linker"),
1190 print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1191 "prints the llvm optimization passes being run"),
1192 ast_json: bool = (false, parse_bool, [UNTRACKED],
1193 "print the AST as JSON and halt"),
1194 query_threads: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1195 "execute queries on a thread pool with N threads"),
1196 ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
1197 "print the pre-expansion AST as JSON and halt"),
1198 ls: bool = (false, parse_bool, [UNTRACKED],
1199 "list the symbols defined by a library crate"),
1200 save_analysis: bool = (false, parse_bool, [UNTRACKED],
1201 "write syntax and type analysis (in JSON format) information, in \
1202 addition to normal output"),
1203 flowgraph_print_loans: bool = (false, parse_bool, [UNTRACKED],
1204 "include loan analysis data in -Z unpretty flowgraph output"),
1205 flowgraph_print_moves: bool = (false, parse_bool, [UNTRACKED],
1206 "include move analysis data in -Z unpretty flowgraph output"),
1207 flowgraph_print_assigns: bool = (false, parse_bool, [UNTRACKED],
1208 "include assignment analysis data in -Z unpretty flowgraph output"),
1209 flowgraph_print_all: bool = (false, parse_bool, [UNTRACKED],
1210 "include all dataflow analysis data in -Z unpretty flowgraph output"),
1211 print_region_graph: bool = (false, parse_bool, [UNTRACKED],
1212 "prints region inference graph. \
1213 Use with RUST_REGION_GRAPH=help for more info"),
1214 parse_only: bool = (false, parse_bool, [UNTRACKED],
1215 "parse only; do not compile, assemble, or link"),
1216 no_codegen: bool = (false, parse_bool, [TRACKED],
1217 "run all passes except codegen; no output"),
1218 treat_err_as_bug: bool = (false, parse_bool, [TRACKED],
1219 "treat all errors that occur as bugs"),
1220 report_delayed_bugs: bool = (false, parse_bool, [TRACKED],
1221 "immediately print bugs registered with `delay_span_bug`"),
1222 external_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1223 "show macro backtraces even for non-local macros"),
1224 teach: bool = (false, parse_bool, [TRACKED],
1225 "show extended diagnostic help"),
1226 continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
1227 "attempt to recover from parse errors (experimental)"),
1228 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1229 "enable incremental compilation (experimental)"),
1230 incremental_queries: bool = (true, parse_bool, [UNTRACKED],
1231 "enable incremental compilation support for queries (experimental)"),
1232 incremental_info: bool = (false, parse_bool, [UNTRACKED],
1233 "print high-level information about incremental reuse (or the lack thereof)"),
1234 incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
1235 "dump hash information in textual format to stdout"),
1236 incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
1237 "verify incr. comp. hashes of green query instances"),
1238 incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
1239 "ignore spans during ICH computation -- used for testing"),
1240 dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1241 "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
1242 query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1243 "enable queries of the dependency graph for regression testing"),
1244 profile_queries: bool = (false, parse_bool, [UNTRACKED],
1245 "trace and profile the queries of the incremental compilation framework"),
1246 profile_queries_and_keys: bool = (false, parse_bool, [UNTRACKED],
1247 "trace and profile the queries and keys of the incremental compilation framework"),
1248 no_analysis: bool = (false, parse_bool, [UNTRACKED],
1249 "parse and expand the source, but run no analysis"),
1250 extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1251 "load extra plugins"),
1252 unstable_options: bool = (false, parse_bool, [UNTRACKED],
1253 "adds unstable command line options to rustc interface"),
1254 force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1255 "force overflow checks on or off"),
1256 trace_macros: bool = (false, parse_bool, [UNTRACKED],
1257 "for every macro invocation, print its name and arguments"),
1258 debug_macros: bool = (false, parse_bool, [TRACKED],
1259 "emit line numbers debug info inside macros"),
1260 keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
1261 "don't clear the hygiene data after analysis"),
1262 keep_ast: bool = (false, parse_bool, [UNTRACKED],
1263 "keep the AST after lowering it to HIR"),
1264 show_span: Option<String> = (None, parse_opt_string, [TRACKED],
1265 "show spans for compiler debugging (expr|pat|ty)"),
1266 print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
1267 "print layout information for each type encountered"),
1268 print_mono_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
1269 "print the result of the monomorphization collection pass"),
1270 mir_opt_level: usize = (1, parse_uint, [TRACKED],
1271 "set the MIR optimization level (0-3, default: 1)"),
1272 mutable_noalias: Option<bool> = (None, parse_opt_bool, [TRACKED],
1273 "emit noalias metadata for mutable references (default: yes on LLVM >= 6)"),
1274 arg_align_attributes: bool = (false, parse_bool, [TRACKED],
1275 "emit align metadata for reference arguments"),
1276 dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1277 "dump MIR state at various points in transforms"),
1278 dump_mir_dir: String = (String::from("mir_dump"), parse_string, [UNTRACKED],
1279 "the directory the MIR is dumped into"),
1280 dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
1281 "in addition to `.mir` files, create graphviz `.dot` files"),
1282 dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
1283 "if set, exclude the pass number when dumping MIR (used in tests)"),
1284 mir_emit_validate: usize = (0, parse_uint, [TRACKED],
1285 "emit Validate MIR statements, interpreted e.g. by miri (0: do not emit; 1: if function \
1286 contains unsafe block, only validate arguments; 2: always emit full validation)"),
1287 perf_stats: bool = (false, parse_bool, [UNTRACKED],
1288 "print some performance-related statistics"),
1289 hir_stats: bool = (false, parse_bool, [UNTRACKED],
1290 "print some statistics about AST and HIR"),
1291 mir_stats: bool = (false, parse_bool, [UNTRACKED],
1292 "print some statistics about MIR"),
1293 always_encode_mir: bool = (false, parse_bool, [TRACKED],
1294 "encode MIR of all functions into the crate metadata"),
1295 osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
1296 "pass `-install_name @rpath/...` to the macOS linker"),
1297 sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
1299 linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
1301 fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
1302 "set the optimization fuel quota for a crate"),
1303 print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
1304 "make Rustc print the total optimization fuel used by a crate"),
1305 force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
1306 "force all crates to be `rustc_private` unstable"),
1307 pre_link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1308 "a single extra argument to prepend the linker invocation (can be used several times)"),
1309 pre_link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1310 "extra arguments to prepend to the linker invocation (space separated)"),
1311 profile: bool = (false, parse_bool, [TRACKED],
1312 "insert profiling code"),
1313 pgo_gen: Option<String> = (None, parse_opt_string, [TRACKED],
1314 "Generate PGO profile data, to a given file, or to the default \
1315 location if it's empty."),
1316 pgo_use: String = (String::new(), parse_string, [TRACKED],
1317 "Use PGO profile data from the given profile file."),
1318 disable_instrumentation_preinliner: bool =
1319 (false, parse_bool, [TRACKED], "Disable the instrumentation pre-inliner, \
1320 useful for profiling / PGO."),
1321 relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
1322 "choose which RELRO level to use"),
1323 disable_ast_check_for_mutation_in_guard: bool = (false, parse_bool, [UNTRACKED],
1324 "skip AST-based mutation-in-guard check (mir-borrowck provides more precise check)"),
1325 nll_subminimal_causes: bool = (false, parse_bool, [UNTRACKED],
1326 "when tracking region error causes, accept subminimal results for faster execution."),
1327 nll_facts: bool = (false, parse_bool, [UNTRACKED],
1328 "dump facts from NLL analysis into side files"),
1329 disable_nll_user_type_assert: bool = (false, parse_bool, [UNTRACKED],
1330 "disable user provided type assertion in NLL"),
1331 nll_dont_emit_read_for_match: bool = (false, parse_bool, [UNTRACKED],
1332 "in match codegen, do not include FakeRead statements (used by mir-borrowck)"),
1333 dont_buffer_diagnostics: bool = (false, parse_bool, [UNTRACKED],
1334 "emit diagnostics rather than buffering (breaks NLL error downgrading, sorting)."),
1335 polonius: bool = (false, parse_bool, [UNTRACKED],
1336 "enable polonius-based borrow-checker"),
1337 codegen_time_graph: bool = (false, parse_bool, [UNTRACKED],
1338 "generate a graphical HTML report of time spent in codegen and LLVM"),
1339 thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
1340 "enable ThinLTO when possible"),
1341 inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
1342 "control whether #[inline] functions are in all cgus"),
1343 tls_model: Option<String> = (None, parse_opt_string, [TRACKED],
1344 "choose the TLS model to use (rustc --print tls-models for details)"),
1345 saturating_float_casts: bool = (false, parse_bool, [TRACKED],
1346 "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
1347 the max/min integer respectively, and NaN is mapped to 0"),
1348 lower_128bit_ops: Option<bool> = (None, parse_opt_bool, [TRACKED],
1349 "rewrite operators on i128 and u128 into lang item calls (typically provided \
1350 by compiler-builtins) so codegen doesn't need to support them,
1351 overriding the default for the current target"),
1352 human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
1353 "generate human-readable, predictable names for codegen units"),
1354 dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
1355 "in dep-info output, omit targets for tracking dependencies of the dep-info files \
1357 unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
1358 "Present the input source, unstable (and less-pretty) variants;
1359 valid types are any of the types for `--pretty`, as well as:
1360 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
1361 `everybody_loops` (all function bodies replaced with `loop {}`),
1362 `hir` (the HIR), `hir,identified`, or
1363 `hir,typed` (HIR with types for each node)."),
1364 run_dsymutil: Option<bool> = (None, parse_opt_bool, [TRACKED],
1365 "run `dsymutil` and delete intermediate object files"),
1366 ui_testing: bool = (false, parse_bool, [UNTRACKED],
1367 "format compiler diagnostics in a way that's better suitable for UI testing"),
1368 embed_bitcode: bool = (false, parse_bool, [TRACKED],
1369 "embed LLVM bitcode in object files"),
1370 strip_debuginfo_if_disabled: Option<bool> = (None, parse_opt_bool, [TRACKED],
1371 "tell the linker to strip debuginfo when building without debuginfo enabled."),
1372 share_generics: Option<bool> = (None, parse_opt_bool, [TRACKED],
1373 "make the current crate share its generic instantiations"),
1374 chalk: bool = (false, parse_bool, [TRACKED],
1375 "enable the experimental Chalk-based trait solving engine"),
1376 cross_lang_lto: CrossLangLto = (CrossLangLto::Disabled, parse_cross_lang_lto, [TRACKED],
1377 "generate build artifacts that are compatible with linker-based LTO."),
1378 no_parallel_llvm: bool = (false, parse_bool, [UNTRACKED],
1379 "don't run LLVM in parallel (while keeping codegen-units and ThinLTO)"),
1380 no_leak_check: bool = (false, parse_bool, [UNTRACKED],
1381 "disables the 'leak check' for subtyping; unsound, but useful for tests"),
1382 crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],
1383 "inject the given attribute in the crate"),
1384 self_profile: bool = (false, parse_bool, [UNTRACKED],
1385 "run the self profiler"),
1386 profile_json: bool = (false, parse_bool, [UNTRACKED],
1387 "output a json file with profiler results"),
1388 emit_stack_sizes: bool = (false, parse_bool, [UNTRACKED],
1389 "emits a section containing stack size metadata"),
1392 pub fn default_lib_output() -> CrateType {
1396 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
1397 let end = &sess.target.target.target_endian;
1398 let arch = &sess.target.target.arch;
1399 let wordsz = &sess.target.target.target_pointer_width;
1400 let os = &sess.target.target.target_os;
1401 let env = &sess.target.target.target_env;
1402 let vendor = &sess.target.target.target_vendor;
1403 let min_atomic_width = sess.target.target.min_atomic_width();
1404 let max_atomic_width = sess.target.target.max_atomic_width();
1405 let atomic_cas = sess.target.target.options.atomic_cas;
1407 let mut ret = FxHashSet::default();
1409 ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
1410 if let Some(ref fam) = sess.target.target.options.target_family {
1411 ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam))));
1412 if fam == "windows" || fam == "unix" {
1413 ret.insert((Symbol::intern(fam), None));
1416 ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
1417 ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
1419 Symbol::intern("target_pointer_width"),
1420 Some(Symbol::intern(wordsz)),
1422 ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
1424 Symbol::intern("target_vendor"),
1425 Some(Symbol::intern(vendor)),
1427 if sess.target.target.options.has_elf_tls {
1428 ret.insert((Symbol::intern("target_thread_local"), None));
1430 for &i in &[8, 16, 32, 64, 128] {
1431 if i >= min_atomic_width && i <= max_atomic_width {
1432 let s = i.to_string();
1434 Symbol::intern("target_has_atomic"),
1435 Some(Symbol::intern(&s)),
1439 Symbol::intern("target_has_atomic"),
1440 Some(Symbol::intern("ptr")),
1446 ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern("cas"))));
1448 if sess.opts.debug_assertions {
1449 ret.insert((Symbol::intern("debug_assertions"), None));
1451 if sess.opts.crate_types.contains(&CrateType::ProcMacro) {
1452 ret.insert((Symbol::intern("proc_macro"), None));
1457 pub fn build_configuration(sess: &Session, mut user_cfg: ast::CrateConfig) -> ast::CrateConfig {
1458 // Combine the configuration requested by the session (command line) with
1459 // some default and generated configuration items
1460 let default_cfg = default_configuration(sess);
1461 // If the user wants a test runner, then add the test cfg
1463 user_cfg.insert((Symbol::intern("test"), None));
1465 user_cfg.extend(default_cfg.iter().cloned());
1469 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
1470 let target = match Target::search(&opts.target_triple) {
1473 sp.struct_fatal(&format!("Error loading target specification: {}", e))
1474 .help("Use `--print target-list` for a list of built-in targets")
1480 let (isize_ty, usize_ty) = match &target.target_pointer_width[..] {
1481 "16" => (ast::IntTy::I16, ast::UintTy::U16),
1482 "32" => (ast::IntTy::I32, ast::UintTy::U32),
1483 "64" => (ast::IntTy::I64, ast::UintTy::U64),
1484 w => sp.fatal(&format!(
1485 "target specification was invalid: \
1486 unrecognized target-pointer-width {}",
1498 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1499 pub enum OptionStability {
1505 pub struct RustcOptGroup {
1506 pub apply: Box<dyn Fn(&mut getopts::Options) -> &mut getopts::Options>,
1507 pub name: &'static str,
1508 pub stability: OptionStability,
1511 impl RustcOptGroup {
1512 pub fn is_stable(&self) -> bool {
1513 self.stability == OptionStability::Stable
1516 pub fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
1518 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1523 stability: OptionStability::Stable,
1527 pub fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
1529 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1534 stability: OptionStability::Unstable,
1539 // The `opt` local module holds wrappers around the `getopts` API that
1540 // adds extra rustc-specific metadata to each option; such metadata
1541 // is exposed by . The public
1542 // functions below ending with `_u` are the functions that return
1543 // *unstable* options, i.e. options that are only enabled when the
1544 // user also passes the `-Z unstable-options` debugging flag.
1546 // The `fn opt_u` etc below are written so that we can use them
1547 // in the future; do not warn about them not being used right now.
1548 #![allow(dead_code)]
1551 use super::RustcOptGroup;
1553 pub type R = RustcOptGroup;
1554 pub type S = &'static str;
1556 fn stable<F>(name: S, f: F) -> R
1558 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1560 RustcOptGroup::stable(name, f)
1563 fn unstable<F>(name: S, f: F) -> R
1565 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1567 RustcOptGroup::unstable(name, f)
1570 fn longer(a: S, b: S) -> S {
1571 if a.len() > b.len() {
1578 pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
1579 stable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1581 pub fn multi_s(a: S, b: S, c: S, d: S) -> R {
1582 stable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1584 pub fn flag_s(a: S, b: S, c: S) -> R {
1585 stable(longer(a, b), move |opts| opts.optflag(a, b, c))
1587 pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R {
1588 stable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1590 pub fn flagmulti_s(a: S, b: S, c: S) -> R {
1591 stable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1594 pub fn opt(a: S, b: S, c: S, d: S) -> R {
1595 unstable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1597 pub fn multi(a: S, b: S, c: S, d: S) -> R {
1598 unstable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1600 pub fn flag(a: S, b: S, c: S) -> R {
1601 unstable(longer(a, b), move |opts| opts.optflag(a, b, c))
1603 pub fn flagopt(a: S, b: S, c: S, d: S) -> R {
1604 unstable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1606 pub fn flagmulti(a: S, b: S, c: S) -> R {
1607 unstable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1611 /// Returns the "short" subset of the rustc command line options,
1612 /// including metadata for each option, such as whether the option is
1613 /// part of the stable long-term interface for rustc.
1614 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
1616 opt::flag_s("h", "help", "Display this message"),
1617 opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
1621 "Add a directory to the library search path. The
1622 optional KIND can be one of dependency, crate, native,
1623 framework or all (the default).",
1629 "Link the generated crate(s) to the specified native
1630 library NAME. The optional KIND can be one of
1631 static, dylib, or framework. If omitted, dylib is
1638 "Comma separated list of types of crates
1639 for the compiler to emit",
1640 "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]",
1645 "Specify the name of the crate being built",
1651 "Comma separated list of types of output for \
1652 the compiler to emit",
1653 "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]",
1658 "Comma separated list of compiler information to \
1660 "[crate-name|file-names|sysroot|cfg|target-list|\
1661 target-cpus|target-features|relocation-models|\
1662 code-models|tls-models|target-spec-json|native-static-libs]",
1664 opt::flagmulti_s("g", "", "Equivalent to -C debuginfo=2"),
1665 opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
1666 opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
1670 "Write output to compiler-chosen filename \
1677 "Provide a detailed explanation of an error \
1681 opt::flag_s("", "test", "Build a test harness"),
1685 "Target triple for which the code is compiled",
1688 opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
1689 opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
1690 opt::multi_s("D", "deny", "Set lint denied", "OPT"),
1691 opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
1695 "Set the most restrictive lint level. \
1696 More restrictive lints are capped at this \
1700 opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
1701 opt::flag_s("V", "version", "Print version info and exit"),
1702 opt::flag_s("v", "verbose", "Use verbose output"),
1706 /// Returns all rustc command line options, including metadata for
1707 /// each option, such as whether the option is part of the stable
1708 /// long-term interface for rustc.
1709 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
1710 let mut opts = rustc_short_optgroups();
1715 "Specify where an external rust library is located",
1718 opt::opt_s("", "sysroot", "Override the system root", "PATH"),
1719 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
1723 "How errors and other messages are produced",
1729 "Configure coloring of output:
1730 auto = colorize, if output goes to a tty (default);
1731 always = always colorize output;
1732 never = never colorize output",
1733 "auto|always|never",
1738 "Pretty-print the input instead of compiling;
1739 valid types are: `normal` (un-annotated source),
1740 `expanded` (crates expanded), or
1741 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
1747 "Specify which edition of the compiler to use when compiling code.",
1752 "remap-path-prefix",
1753 "Remap source names in all output (compiler messages and output files)",
1760 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
1761 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> ast::CrateConfig {
1765 let sess = parse::ParseSess::new(FilePathMapping::empty());
1767 parse::new_parser_from_source_str(&sess, FileName::CfgSpec, s.to_string());
1769 macro_rules! error {($reason: expr) => {
1770 early_error(ErrorOutputType::default(),
1771 &format!(concat!("invalid `--cfg` argument: `{}` (", $reason, ")"), s));
1774 match &mut parser.parse_meta_item() {
1775 Ok(meta_item) if parser.token == token::Eof => {
1776 if meta_item.ident.segments.len() != 1 {
1777 error!("argument key must be an identifier");
1779 match &meta_item.node {
1780 MetaItemKind::List(..) => {
1781 error!(r#"expected `key` or `key="value"`"#);
1783 MetaItemKind::NameValue(lit) if !lit.node.is_str() => {
1784 error!("argument value must be a string");
1786 MetaItemKind::NameValue(..) | MetaItemKind::Word => {
1787 return (meta_item.name(), meta_item.value_str());
1792 Err(err) => err.cancel(),
1795 error!(r#"expected `key` or `key="value"`"#);
1797 .collect::<ast::CrateConfig>()
1800 pub fn get_cmd_lint_options(matches: &getopts::Matches,
1801 error_format: ErrorOutputType)
1802 -> (Vec<(String, lint::Level)>, bool, Option<lint::Level>) {
1803 let mut lint_opts = vec![];
1804 let mut describe_lints = false;
1806 for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
1807 for lint_name in matches.opt_strs(level.as_str()) {
1808 if lint_name == "help" {
1809 describe_lints = true;
1811 lint_opts.push((lint_name.replace("-", "_"), level));
1816 let lint_cap = matches.opt_str("cap-lints").map(|cap| {
1817 lint::Level::from_str(&cap)
1818 .unwrap_or_else(|| early_error(error_format, &format!("unknown lint level: `{}`", cap)))
1820 (lint_opts, describe_lints, lint_cap)
1823 pub fn build_session_options_and_crate_config(
1824 matches: &getopts::Matches,
1825 ) -> (Options, ast::CrateConfig) {
1826 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
1827 Some("auto") => ColorConfig::Auto,
1828 Some("always") => ColorConfig::Always,
1829 Some("never") => ColorConfig::Never,
1831 None => ColorConfig::Auto,
1833 Some(arg) => early_error(
1834 ErrorOutputType::default(),
1836 "argument for --color must be auto, \
1837 always or never (instead was `{}`)",
1843 let edition = match matches.opt_str("edition") {
1844 Some(arg) => match Edition::from_str(&arg){
1845 Ok(edition) => edition,
1846 Err(_) => early_error(
1847 ErrorOutputType::default(),
1849 "argument for --edition must be one of: \
1850 {}. (instead was `{}`)",
1856 None => DEFAULT_EDITION,
1859 if !edition.is_stable() && !nightly_options::is_nightly_build() {
1861 ErrorOutputType::default(),
1863 "Edition {} is unstable and only \
1864 available for nightly builds of rustc.",
1871 // We need the opts_present check because the driver will send us Matches
1872 // with only stable options if no unstable options are used. Since error-format
1873 // is unstable, it will not be present. We have to use opts_present not
1874 // opt_present because the latter will panic.
1875 let error_format = if matches.opts_present(&["error-format".to_owned()]) {
1876 match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
1877 Some("human") => ErrorOutputType::HumanReadable(color),
1878 Some("json") => ErrorOutputType::Json(false),
1879 Some("pretty-json") => ErrorOutputType::Json(true),
1880 Some("short") => ErrorOutputType::Short(color),
1881 None => ErrorOutputType::HumanReadable(color),
1883 Some(arg) => early_error(
1884 ErrorOutputType::HumanReadable(color),
1886 "argument for --error-format must be `human`, `json` or \
1887 `short` (instead was `{}`)",
1893 ErrorOutputType::HumanReadable(color)
1896 let unparsed_crate_types = matches.opt_strs("crate-type");
1897 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
1898 .unwrap_or_else(|e| early_error(error_format, &e[..]));
1900 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
1902 let mut debugging_opts = build_debugging_options(matches, error_format);
1904 if !debugging_opts.unstable_options && error_format == ErrorOutputType::Json(true) {
1906 ErrorOutputType::Json(false),
1907 "--error-format=pretty-json is unstable",
1911 if debugging_opts.pgo_gen.is_some() && !debugging_opts.pgo_use.is_empty() {
1914 "options `-Z pgo-gen` and `-Z pgo-use` are exclusive",
1918 let mut output_types = BTreeMap::new();
1919 if !debugging_opts.parse_only {
1920 for list in matches.opt_strs("emit") {
1921 for output_type in list.split(',') {
1922 let mut parts = output_type.splitn(2, '=');
1923 let shorthand = parts.next().unwrap();
1924 let output_type = match OutputType::from_shorthand(shorthand) {
1925 Some(output_type) => output_type,
1926 None => early_error(
1929 "unknown emission type: `{}` - expected one of: {}",
1931 OutputType::shorthands_display(),
1935 let path = parts.next().map(PathBuf::from);
1936 output_types.insert(output_type, path);
1940 if output_types.is_empty() {
1941 output_types.insert(OutputType::Exe, None);
1944 let mut cg = build_codegen_options(matches, error_format);
1945 let mut codegen_units = cg.codegen_units;
1946 let mut disable_thinlto = false;
1948 // Issue #30063: if user requests llvm-related output to one
1949 // particular path, disable codegen-units.
1950 let incompatible: Vec<_> = output_types
1952 .map(|ot_path| ot_path.0)
1953 .filter(|ot| !ot.is_compatible_with_codegen_units_and_single_output_file())
1954 .map(|ot| ot.shorthand())
1956 if !incompatible.is_empty() {
1957 match codegen_units {
1958 Some(n) if n > 1 => {
1959 if matches.opt_present("o") {
1960 for ot in &incompatible {
1964 "--emit={} with -o incompatible with \
1965 -C codegen-units=N for N > 1",
1970 early_warn(error_format, "resetting to default -C codegen-units=1");
1971 codegen_units = Some(1);
1972 disable_thinlto = true;
1976 codegen_units = Some(1);
1977 disable_thinlto = true;
1982 if debugging_opts.query_threads == Some(0) {
1985 "Value for query threads must be a positive nonzero integer",
1989 if debugging_opts.query_threads.unwrap_or(1) > 1 && debugging_opts.fuel.is_some() {
1992 "Optimization fuel is incompatible with multiple query threads",
1996 if codegen_units == Some(0) {
1999 "Value for codegen units must be a positive nonzero integer",
2003 let incremental = match (&debugging_opts.incremental, &cg.incremental) {
2004 (&Some(ref path1), &Some(ref path2)) => {
2009 "conflicting paths for `-Z incremental` and \
2010 `-C incremental` specified: {} versus {}",
2018 (&Some(ref path), &None) => Some(path),
2019 (&None, &Some(ref path)) => Some(path),
2020 (&None, &None) => None,
2021 }.map(|m| PathBuf::from(m));
2023 if debugging_opts.profile && incremental.is_some() {
2026 "can't instrument with gcov profiling when compiling incrementally",
2030 let mut prints = Vec::<PrintRequest>::new();
2031 if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
2032 prints.push(PrintRequest::TargetCPUs);
2033 cg.target_cpu = None;
2035 if cg.target_feature == "help" {
2036 prints.push(PrintRequest::TargetFeatures);
2037 cg.target_feature = String::new();
2039 if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
2040 prints.push(PrintRequest::RelocationModels);
2041 cg.relocation_model = None;
2043 if cg.code_model.as_ref().map_or(false, |s| s == "help") {
2044 prints.push(PrintRequest::CodeModels);
2045 cg.code_model = None;
2050 .map_or(false, |s| s == "help")
2052 prints.push(PrintRequest::TlsModels);
2053 debugging_opts.tls_model = None;
2058 let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
2059 let target_triple = if let Some(target) = matches.opt_str("target") {
2060 if target.ends_with(".json") {
2061 let path = Path::new(&target);
2062 match TargetTriple::from_path(&path) {
2063 Ok(triple) => triple,
2065 early_error(error_format, &format!("target file {:?} does not exist", path))
2069 TargetTriple::TargetTriple(target)
2072 TargetTriple::from_triple(host_triple())
2075 if matches.opt_present("O") {
2076 if cg.opt_level.is_some() {
2077 early_error(error_format, "-O and -C opt-level both provided");
2081 match cg.opt_level.as_ref().map(String::as_ref) {
2082 None => OptLevel::No,
2083 Some("0") => OptLevel::No,
2084 Some("1") => OptLevel::Less,
2085 Some("2") => OptLevel::Default,
2086 Some("3") => OptLevel::Aggressive,
2087 Some("s") => OptLevel::Size,
2088 Some("z") => OptLevel::SizeMin,
2093 "optimization level needs to be \
2094 between 0-3 (instead was `{}`)",
2102 let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
2103 let debuginfo = if matches.opt_present("g") {
2104 if cg.debuginfo.is_some() {
2105 early_error(error_format, "-g and -C debuginfo both provided");
2109 match cg.debuginfo {
2110 None | Some(0) => DebugInfo::None,
2111 Some(1) => DebugInfo::Limited,
2112 Some(2) => DebugInfo::Full,
2117 "debug info level needs to be between \
2118 0-2 (instead was `{}`)",
2126 let mut search_paths = SearchPaths::new();
2127 for s in &matches.opt_strs("L") {
2128 search_paths.add_path(&s[..], error_format);
2135 // Parse string of the form "[KIND=]lib[:new_name]",
2136 // where KIND is one of "dylib", "framework", "static".
2137 let mut parts = s.splitn(2, '=');
2138 let kind = parts.next().unwrap();
2139 let (name, kind) = match (parts.next(), kind) {
2140 (None, name) => (name, None),
2141 (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
2142 (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
2143 (Some(name), "static") => (name, Some(cstore::NativeStatic)),
2144 (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
2149 "unknown library kind `{}`, expected \
2150 one of dylib, framework, or static",
2156 if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
2160 "the library kind 'static-nobundle' is only \
2161 accepted on the nightly compiler"
2165 let mut name_parts = name.splitn(2, ':');
2166 let name = name_parts.next().unwrap();
2167 let new_name = name_parts.next();
2168 (name.to_string(), new_name.map(|n| n.to_string()), kind)
2172 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
2173 let test = matches.opt_present("test");
2175 let is_unstable_enabled = nightly_options::is_unstable_enabled(matches);
2177 prints.extend(matches.opt_strs("print").into_iter().map(|s| match &*s {
2178 "crate-name" => PrintRequest::CrateName,
2179 "file-names" => PrintRequest::FileNames,
2180 "sysroot" => PrintRequest::Sysroot,
2181 "cfg" => PrintRequest::Cfg,
2182 "target-list" => PrintRequest::TargetList,
2183 "target-cpus" => PrintRequest::TargetCPUs,
2184 "target-features" => PrintRequest::TargetFeatures,
2185 "relocation-models" => PrintRequest::RelocationModels,
2186 "code-models" => PrintRequest::CodeModels,
2187 "tls-models" => PrintRequest::TlsModels,
2188 "native-static-libs" => PrintRequest::NativeStaticLibs,
2189 "target-spec-json" => {
2190 if is_unstable_enabled {
2191 PrintRequest::TargetSpec
2195 "the `-Z unstable-options` flag must also be passed to \
2196 enable the target-spec-json print option",
2200 req => early_error(error_format, &format!("unknown print request `{}`", req)),
2203 let borrowck_mode = match debugging_opts.borrowck.as_ref().map(|s| &s[..]) {
2204 None | Some("ast") => BorrowckMode::Ast,
2205 Some("mir") => BorrowckMode::Mir,
2206 Some("compare") => BorrowckMode::Compare,
2207 Some("migrate") => BorrowckMode::Migrate,
2208 Some(m) => early_error(error_format, &format!("unknown borrowck mode `{}`", m)),
2211 if !cg.remark.is_empty() && debuginfo == DebugInfo::None {
2214 "-C remark will not show source locations without \
2219 let mut externs: BTreeMap<_, BTreeSet<_>> = BTreeMap::new();
2220 for arg in &matches.opt_strs("extern") {
2221 let mut parts = arg.splitn(2, '=');
2222 let name = match parts.next() {
2224 None => early_error(error_format, "--extern value must not be empty"),
2226 let location = parts.next().map(|s| s.to_string());
2227 if location.is_none() && !is_unstable_enabled {
2230 "the `-Z unstable-options` flag must also be passed to \
2231 enable `--extern crate_name` without `=path`",
2236 .entry(name.to_string())
2241 let crate_name = matches.opt_str("crate-name");
2243 let remap_path_prefix = matches
2244 .opt_strs("remap-path-prefix")
2247 let mut parts = remap.rsplitn(2, '='); // reverse iterator
2248 let to = parts.next();
2249 let from = parts.next();
2251 (Some(from), Some(to)) => (PathBuf::from(from), PathBuf::from(to)),
2254 "--remap-path-prefix must contain '=' between FROM and TO",
2263 optimize: opt_level,
2268 output_types: OutputTypes(output_types),
2270 maybe_sysroot: sysroot_opt,
2279 externs: Externs(externs),
2283 unstable_features: UnstableFeatures::from_environment(),
2285 actually_rustdoc: false,
2286 cli_forced_codegen_units: codegen_units,
2287 cli_forced_thinlto_off: disable_thinlto,
2295 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
2296 let mut crate_types: Vec<CrateType> = Vec::new();
2297 for unparsed_crate_type in &list_list {
2298 for part in unparsed_crate_type.split(',') {
2299 let new_part = match part {
2300 "lib" => default_lib_output(),
2301 "rlib" => CrateType::Rlib,
2302 "staticlib" => CrateType::Staticlib,
2303 "dylib" => CrateType::Dylib,
2304 "cdylib" => CrateType::Cdylib,
2305 "bin" => CrateType::Executable,
2306 "proc-macro" => CrateType::ProcMacro,
2308 return Err(format!("unknown crate type: `{}`", part));
2311 if !crate_types.contains(&new_part) {
2312 crate_types.push(new_part)
2320 pub mod nightly_options {
2322 use syntax::feature_gate::UnstableFeatures;
2323 use super::{ErrorOutputType, OptionStability, RustcOptGroup};
2324 use session::early_error;
2326 pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
2331 .any(|x| *x == "unstable-options")
2334 pub fn is_nightly_build() -> bool {
2335 UnstableFeatures::from_environment().is_nightly_build()
2338 pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
2339 let has_z_unstable_option = matches
2342 .any(|x| *x == "unstable-options");
2343 let really_allows_unstable_options =
2344 UnstableFeatures::from_environment().is_nightly_build();
2346 for opt in flags.iter() {
2347 if opt.stability == OptionStability::Stable {
2350 if !matches.opt_present(opt.name) {
2353 if opt.name != "Z" && !has_z_unstable_option {
2355 ErrorOutputType::default(),
2357 "the `-Z unstable-options` flag must also be passed to enable \
2363 if really_allows_unstable_options {
2366 match opt.stability {
2367 OptionStability::Unstable => {
2369 "the option `{}` is only accepted on the \
2373 early_error(ErrorOutputType::default(), &msg);
2375 OptionStability::Stable => {}
2381 impl fmt::Display for CrateType {
2382 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2384 CrateType::Executable => "bin".fmt(f),
2385 CrateType::Dylib => "dylib".fmt(f),
2386 CrateType::Rlib => "rlib".fmt(f),
2387 CrateType::Staticlib => "staticlib".fmt(f),
2388 CrateType::Cdylib => "cdylib".fmt(f),
2389 CrateType::ProcMacro => "proc-macro".fmt(f),
2394 /// Commandline arguments passed to the compiler have to be incorporated with
2395 /// the dependency tracking system for incremental compilation. This module
2396 /// provides some utilities to make this more convenient.
2398 /// The values of all commandline arguments that are relevant for dependency
2399 /// tracking are hashed into a single value that determines whether the
2400 /// incremental compilation cache can be re-used or not. This hashing is done
2401 /// via the DepTrackingHash trait defined below, since the standard Hash
2402 /// implementation might not be suitable (e.g. arguments are stored in a Vec,
2403 /// the hash of which is order dependent, but we might not want the order of
2404 /// arguments to make a difference for the hash).
2406 /// However, since the value provided by Hash::hash often *is* suitable,
2407 /// especially for primitive types, there is the
2408 /// impl_dep_tracking_hash_via_hash!() macro that allows to simply reuse the
2409 /// Hash implementation for DepTrackingHash. It's important though that
2410 /// we have an opt-in scheme here, so one is hopefully forced to think about
2411 /// how the hash should be calculated when adding a new commandline argument.
2415 use std::collections::BTreeMap;
2416 use std::hash::Hash;
2417 use std::path::PathBuf;
2418 use std::collections::hash_map::DefaultHasher;
2419 use super::{CrateType, DebugInfo, ErrorOutputType, OptLevel, OutputTypes,
2420 Passes, Sanitizer, LtoCli, CrossLangLto};
2421 use syntax::feature_gate::UnstableFeatures;
2422 use rustc_target::spec::{PanicStrategy, RelroLevel, TargetTriple};
2423 use syntax::edition::Edition;
2425 pub trait DepTrackingHash {
2426 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);
2429 macro_rules! impl_dep_tracking_hash_via_hash {
2431 impl DepTrackingHash for $t {
2432 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
2433 Hash::hash(self, hasher);
2439 macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
2441 impl DepTrackingHash for Vec<$t> {
2442 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2443 let mut elems: Vec<&$t> = self.iter().collect();
2445 Hash::hash(&elems.len(), hasher);
2446 for (index, elem) in elems.iter().enumerate() {
2447 Hash::hash(&index, hasher);
2448 DepTrackingHash::hash(*elem, hasher, error_format);
2455 impl_dep_tracking_hash_via_hash!(bool);
2456 impl_dep_tracking_hash_via_hash!(usize);
2457 impl_dep_tracking_hash_via_hash!(u64);
2458 impl_dep_tracking_hash_via_hash!(String);
2459 impl_dep_tracking_hash_via_hash!(PathBuf);
2460 impl_dep_tracking_hash_via_hash!(lint::Level);
2461 impl_dep_tracking_hash_via_hash!(Option<bool>);
2462 impl_dep_tracking_hash_via_hash!(Option<usize>);
2463 impl_dep_tracking_hash_via_hash!(Option<String>);
2464 impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
2465 impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
2466 impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
2467 impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
2468 impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
2469 impl_dep_tracking_hash_via_hash!(Option<cstore::NativeLibraryKind>);
2470 impl_dep_tracking_hash_via_hash!(CrateType);
2471 impl_dep_tracking_hash_via_hash!(PanicStrategy);
2472 impl_dep_tracking_hash_via_hash!(RelroLevel);
2473 impl_dep_tracking_hash_via_hash!(Passes);
2474 impl_dep_tracking_hash_via_hash!(OptLevel);
2475 impl_dep_tracking_hash_via_hash!(LtoCli);
2476 impl_dep_tracking_hash_via_hash!(DebugInfo);
2477 impl_dep_tracking_hash_via_hash!(UnstableFeatures);
2478 impl_dep_tracking_hash_via_hash!(OutputTypes);
2479 impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
2480 impl_dep_tracking_hash_via_hash!(Sanitizer);
2481 impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
2482 impl_dep_tracking_hash_via_hash!(TargetTriple);
2483 impl_dep_tracking_hash_via_hash!(Edition);
2484 impl_dep_tracking_hash_via_hash!(CrossLangLto);
2486 impl_dep_tracking_hash_for_sortable_vec_of!(String);
2487 impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
2488 impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
2489 impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
2490 impl_dep_tracking_hash_for_sortable_vec_of!((
2493 Option<cstore::NativeLibraryKind>
2495 impl_dep_tracking_hash_for_sortable_vec_of!((String, u64));
2497 impl<T1, T2> DepTrackingHash for (T1, T2)
2499 T1: DepTrackingHash,
2500 T2: DepTrackingHash,
2502 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2503 Hash::hash(&0, hasher);
2504 DepTrackingHash::hash(&self.0, hasher, error_format);
2505 Hash::hash(&1, hasher);
2506 DepTrackingHash::hash(&self.1, hasher, error_format);
2510 impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
2512 T1: DepTrackingHash,
2513 T2: DepTrackingHash,
2514 T3: DepTrackingHash,
2516 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2517 Hash::hash(&0, hasher);
2518 DepTrackingHash::hash(&self.0, hasher, error_format);
2519 Hash::hash(&1, hasher);
2520 DepTrackingHash::hash(&self.1, hasher, error_format);
2521 Hash::hash(&2, hasher);
2522 DepTrackingHash::hash(&self.2, hasher, error_format);
2526 // This is a stable hash because BTreeMap is a sorted container
2528 sub_hashes: BTreeMap<&'static str, &dyn DepTrackingHash>,
2529 hasher: &mut DefaultHasher,
2530 error_format: ErrorOutputType,
2532 for (key, sub_hash) in sub_hashes {
2533 // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
2534 // the keys, as they are just plain strings
2535 Hash::hash(&key.len(), hasher);
2536 Hash::hash(key, hasher);
2537 sub_hash.hash(hasher, error_format);
2548 use session::config::{build_configuration, build_session_options_and_crate_config};
2549 use session::config::{LtoCli, CrossLangLto};
2550 use session::build_session;
2551 use std::collections::{BTreeMap, BTreeSet};
2552 use std::iter::FromIterator;
2553 use std::path::PathBuf;
2554 use super::{Externs, OutputType, OutputTypes};
2555 use rustc_target::spec::{PanicStrategy, RelroLevel};
2556 use syntax::symbol::Symbol;
2557 use syntax::edition::{Edition, DEFAULT_EDITION};
2561 fn optgroups() -> getopts::Options {
2562 let mut opts = getopts::Options::new();
2563 for group in super::rustc_optgroups() {
2564 (group.apply)(&mut opts);
2569 fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
2570 BTreeMap::from_iter(entries.into_iter())
2573 fn mk_set<V: Ord>(entries: Vec<V>) -> BTreeSet<V> {
2574 BTreeSet::from_iter(entries.into_iter())
2577 // When the user supplies --test we should implicitly supply --cfg test
2579 fn test_switch_implies_cfg_test() {
2580 syntax::with_globals(|| {
2581 let matches = &match optgroups().parse(&["--test".to_string()]) {
2583 Err(f) => panic!("test_switch_implies_cfg_test: {}", f),
2585 let registry = errors::registry::Registry::new(&[]);
2586 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2587 let sess = build_session(sessopts, None, registry);
2588 let cfg = build_configuration(&sess, cfg);
2589 assert!(cfg.contains(&(Symbol::intern("test"), None)));
2593 // When the user supplies --test and --cfg test, don't implicitly add
2594 // another --cfg test
2596 fn test_switch_implies_cfg_test_unless_cfg_test() {
2597 syntax::with_globals(|| {
2598 let matches = &match optgroups().parse(&["--test".to_string(),
2599 "--cfg=test".to_string()]) {
2601 Err(f) => panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f),
2603 let registry = errors::registry::Registry::new(&[]);
2604 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2605 let sess = build_session(sessopts, None, registry);
2606 let cfg = build_configuration(&sess, cfg);
2607 let mut test_items = cfg.iter().filter(|&&(name, _)| name == "test");
2608 assert!(test_items.next().is_some());
2609 assert!(test_items.next().is_none());
2614 fn test_can_print_warnings() {
2615 syntax::with_globals(|| {
2616 let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
2617 let registry = errors::registry::Registry::new(&[]);
2618 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2619 let sess = build_session(sessopts, None, registry);
2620 assert!(!sess.diagnostic().flags.can_emit_warnings);
2623 syntax::with_globals(|| {
2624 let matches = optgroups()
2625 .parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()])
2627 let registry = errors::registry::Registry::new(&[]);
2628 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2629 let sess = build_session(sessopts, None, registry);
2630 assert!(sess.diagnostic().flags.can_emit_warnings);
2633 syntax::with_globals(|| {
2634 let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
2635 let registry = errors::registry::Registry::new(&[]);
2636 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2637 let sess = build_session(sessopts, None, registry);
2638 assert!(sess.diagnostic().flags.can_emit_warnings);
2643 fn test_output_types_tracking_hash_different_paths() {
2644 let mut v1 = Options::default();
2645 let mut v2 = Options::default();
2646 let mut v3 = Options::default();
2649 OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("./some/thing")))]);
2651 OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("/some/thing")))]);
2652 v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
2654 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2655 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2656 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2659 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2660 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2661 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2665 fn test_output_types_tracking_hash_different_construction_order() {
2666 let mut v1 = Options::default();
2667 let mut v2 = Options::default();
2669 v1.output_types = OutputTypes::new(&[
2670 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2671 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2674 v2.output_types = OutputTypes::new(&[
2675 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2676 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2679 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2682 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2686 fn test_externs_tracking_hash_different_construction_order() {
2687 let mut v1 = Options::default();
2688 let mut v2 = Options::default();
2689 let mut v3 = Options::default();
2691 v1.externs = Externs::new(mk_map(vec![
2694 mk_set(vec![Some(String::from("b")), Some(String::from("c"))]),
2698 mk_set(vec![Some(String::from("e")), Some(String::from("f"))]),
2702 v2.externs = Externs::new(mk_map(vec![
2705 mk_set(vec![Some(String::from("e")), Some(String::from("f"))]),
2709 mk_set(vec![Some(String::from("b")), Some(String::from("c"))]),
2713 v3.externs = Externs::new(mk_map(vec![
2716 mk_set(vec![Some(String::from("b")), Some(String::from("c"))]),
2720 mk_set(vec![Some(String::from("f")), Some(String::from("e"))]),
2724 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2725 assert_eq!(v1.dep_tracking_hash(), v3.dep_tracking_hash());
2726 assert_eq!(v2.dep_tracking_hash(), v3.dep_tracking_hash());
2729 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2730 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2731 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2735 fn test_lints_tracking_hash_different_values() {
2736 let mut v1 = Options::default();
2737 let mut v2 = Options::default();
2738 let mut v3 = Options::default();
2740 v1.lint_opts = vec![
2741 (String::from("a"), lint::Allow),
2742 (String::from("b"), lint::Warn),
2743 (String::from("c"), lint::Deny),
2744 (String::from("d"), lint::Forbid),
2747 v2.lint_opts = vec![
2748 (String::from("a"), lint::Allow),
2749 (String::from("b"), lint::Warn),
2750 (String::from("X"), lint::Deny),
2751 (String::from("d"), lint::Forbid),
2754 v3.lint_opts = vec![
2755 (String::from("a"), lint::Allow),
2756 (String::from("b"), lint::Warn),
2757 (String::from("c"), lint::Forbid),
2758 (String::from("d"), lint::Deny),
2761 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2762 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2763 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2766 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2767 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2768 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2772 fn test_lints_tracking_hash_different_construction_order() {
2773 let mut v1 = Options::default();
2774 let mut v2 = Options::default();
2776 v1.lint_opts = vec![
2777 (String::from("a"), lint::Allow),
2778 (String::from("b"), lint::Warn),
2779 (String::from("c"), lint::Deny),
2780 (String::from("d"), lint::Forbid),
2783 v2.lint_opts = vec![
2784 (String::from("a"), lint::Allow),
2785 (String::from("c"), lint::Deny),
2786 (String::from("b"), lint::Warn),
2787 (String::from("d"), lint::Forbid),
2790 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2793 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2794 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2798 fn test_search_paths_tracking_hash_different_order() {
2799 let mut v1 = Options::default();
2800 let mut v2 = Options::default();
2801 let mut v3 = Options::default();
2802 let mut v4 = Options::default();
2806 .add_path("native=abc", super::ErrorOutputType::Json(false));
2808 .add_path("crate=def", super::ErrorOutputType::Json(false));
2810 .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2812 .add_path("framework=jkl", super::ErrorOutputType::Json(false));
2814 .add_path("all=mno", super::ErrorOutputType::Json(false));
2817 .add_path("native=abc", super::ErrorOutputType::Json(false));
2819 .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2821 .add_path("crate=def", super::ErrorOutputType::Json(false));
2823 .add_path("framework=jkl", super::ErrorOutputType::Json(false));
2825 .add_path("all=mno", super::ErrorOutputType::Json(false));
2828 .add_path("crate=def", super::ErrorOutputType::Json(false));
2830 .add_path("framework=jkl", super::ErrorOutputType::Json(false));
2832 .add_path("native=abc", super::ErrorOutputType::Json(false));
2834 .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2836 .add_path("all=mno", super::ErrorOutputType::Json(false));
2839 .add_path("all=mno", super::ErrorOutputType::Json(false));
2841 .add_path("native=abc", super::ErrorOutputType::Json(false));
2843 .add_path("crate=def", super::ErrorOutputType::Json(false));
2845 .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2847 .add_path("framework=jkl", super::ErrorOutputType::Json(false));
2849 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2850 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2851 assert!(v1.dep_tracking_hash() == v4.dep_tracking_hash());
2854 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2855 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2856 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2857 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2861 fn test_native_libs_tracking_hash_different_values() {
2862 let mut v1 = Options::default();
2863 let mut v2 = Options::default();
2864 let mut v3 = Options::default();
2865 let mut v4 = Options::default();
2869 (String::from("a"), None, Some(cstore::NativeStatic)),
2870 (String::from("b"), None, Some(cstore::NativeFramework)),
2871 (String::from("c"), None, Some(cstore::NativeUnknown)),
2876 (String::from("a"), None, Some(cstore::NativeStatic)),
2877 (String::from("X"), None, Some(cstore::NativeFramework)),
2878 (String::from("c"), None, Some(cstore::NativeUnknown)),
2883 (String::from("a"), None, Some(cstore::NativeStatic)),
2884 (String::from("b"), None, Some(cstore::NativeStatic)),
2885 (String::from("c"), None, Some(cstore::NativeUnknown)),
2890 (String::from("a"), None, Some(cstore::NativeStatic)),
2893 Some(String::from("X")),
2894 Some(cstore::NativeFramework),
2896 (String::from("c"), None, Some(cstore::NativeUnknown)),
2899 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2900 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2901 assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
2904 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2905 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2906 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2907 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2911 fn test_native_libs_tracking_hash_different_order() {
2912 let mut v1 = Options::default();
2913 let mut v2 = Options::default();
2914 let mut v3 = Options::default();
2918 (String::from("a"), None, Some(cstore::NativeStatic)),
2919 (String::from("b"), None, Some(cstore::NativeFramework)),
2920 (String::from("c"), None, Some(cstore::NativeUnknown)),
2924 (String::from("b"), None, Some(cstore::NativeFramework)),
2925 (String::from("a"), None, Some(cstore::NativeStatic)),
2926 (String::from("c"), None, Some(cstore::NativeUnknown)),
2930 (String::from("c"), None, Some(cstore::NativeUnknown)),
2931 (String::from("a"), None, Some(cstore::NativeStatic)),
2932 (String::from("b"), None, Some(cstore::NativeFramework)),
2935 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2936 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2937 assert!(v2.dep_tracking_hash() == v3.dep_tracking_hash());
2940 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2941 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2942 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2946 fn test_codegen_options_tracking_hash() {
2947 let reference = Options::default();
2948 let mut opts = Options::default();
2950 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2951 opts.cg.ar = Some(String::from("abc"));
2952 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2954 opts.cg.linker = Some(PathBuf::from("linker"));
2955 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2957 opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
2958 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2960 opts.cg.link_dead_code = true;
2961 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2963 opts.cg.rpath = true;
2964 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2966 opts.cg.extra_filename = String::from("extra-filename");
2967 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2969 opts.cg.codegen_units = Some(42);
2970 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2972 opts.cg.remark = super::Passes::Some(vec![String::from("pass1"), String::from("pass2")]);
2973 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2975 opts.cg.save_temps = true;
2976 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2978 opts.cg.incremental = Some(String::from("abc"));
2979 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2981 // Make sure changing a [TRACKED] option changes the hash
2982 opts = reference.clone();
2983 opts.cg.lto = LtoCli::Fat;
2984 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2986 opts = reference.clone();
2987 opts.cg.target_cpu = Some(String::from("abc"));
2988 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2990 opts = reference.clone();
2991 opts.cg.target_feature = String::from("all the features, all of them");
2992 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2994 opts = reference.clone();
2995 opts.cg.passes = vec![String::from("1"), String::from("2")];
2996 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2998 opts = reference.clone();
2999 opts.cg.llvm_args = vec![String::from("1"), String::from("2")];
3000 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3002 opts = reference.clone();
3003 opts.cg.overflow_checks = Some(true);
3004 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3006 opts = reference.clone();
3007 opts.cg.no_prepopulate_passes = true;
3008 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3010 opts = reference.clone();
3011 opts.cg.no_vectorize_loops = true;
3012 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3014 opts = reference.clone();
3015 opts.cg.no_vectorize_slp = true;
3016 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3018 opts = reference.clone();
3019 opts.cg.soft_float = true;
3020 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3022 opts = reference.clone();
3023 opts.cg.prefer_dynamic = true;
3024 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3026 opts = reference.clone();
3027 opts.cg.no_integrated_as = true;
3028 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3030 opts = reference.clone();
3031 opts.cg.no_redzone = Some(true);
3032 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3034 opts = reference.clone();
3035 opts.cg.relocation_model = Some(String::from("relocation model"));
3036 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3038 opts = reference.clone();
3039 opts.cg.code_model = Some(String::from("code model"));
3040 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3042 opts = reference.clone();
3043 opts.debugging_opts.tls_model = Some(String::from("tls model"));
3044 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3046 opts = reference.clone();
3047 opts.debugging_opts.pgo_gen = Some(String::from("abc"));
3048 assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3050 opts = reference.clone();
3051 opts.debugging_opts.pgo_use = String::from("abc");
3052 assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3054 opts = reference.clone();
3055 opts.cg.metadata = vec![String::from("A"), String::from("B")];
3056 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3058 opts = reference.clone();
3059 opts.cg.debuginfo = Some(0xdeadbeef);
3060 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3062 opts = reference.clone();
3063 opts.cg.debuginfo = Some(0xba5eba11);
3064 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3066 opts = reference.clone();
3067 opts.cg.force_frame_pointers = Some(false);
3068 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3070 opts = reference.clone();
3071 opts.cg.debug_assertions = Some(true);
3072 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3074 opts = reference.clone();
3075 opts.cg.inline_threshold = Some(0xf007ba11);
3076 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3078 opts = reference.clone();
3079 opts.cg.panic = Some(PanicStrategy::Abort);
3080 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3084 fn test_debugging_options_tracking_hash() {
3085 let reference = Options::default();
3086 let mut opts = Options::default();
3088 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
3089 opts.debugging_opts.verbose = true;
3090 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3091 opts.debugging_opts.time_passes = true;
3092 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3093 opts.debugging_opts.count_llvm_insns = true;
3094 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3095 opts.debugging_opts.time_llvm_passes = true;
3096 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3097 opts.debugging_opts.input_stats = true;
3098 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3099 opts.debugging_opts.codegen_stats = true;
3100 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3101 opts.debugging_opts.borrowck_stats = true;
3102 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3103 opts.debugging_opts.meta_stats = true;
3104 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3105 opts.debugging_opts.print_link_args = true;
3106 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3107 opts.debugging_opts.print_llvm_passes = true;
3108 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3109 opts.debugging_opts.ast_json = true;
3110 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3111 opts.debugging_opts.ast_json_noexpand = true;
3112 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3113 opts.debugging_opts.ls = true;
3114 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3115 opts.debugging_opts.save_analysis = true;
3116 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3117 opts.debugging_opts.flowgraph_print_loans = true;
3118 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3119 opts.debugging_opts.flowgraph_print_moves = true;
3120 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3121 opts.debugging_opts.flowgraph_print_assigns = true;
3122 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3123 opts.debugging_opts.flowgraph_print_all = true;
3124 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3125 opts.debugging_opts.print_region_graph = true;
3126 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3127 opts.debugging_opts.parse_only = true;
3128 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3129 opts.debugging_opts.incremental = Some(String::from("abc"));
3130 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3131 opts.debugging_opts.dump_dep_graph = true;
3132 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3133 opts.debugging_opts.query_dep_graph = true;
3134 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3135 opts.debugging_opts.no_analysis = true;
3136 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3137 opts.debugging_opts.unstable_options = true;
3138 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3139 opts.debugging_opts.trace_macros = true;
3140 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3141 opts.debugging_opts.keep_hygiene_data = true;
3142 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3143 opts.debugging_opts.keep_ast = true;
3144 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3145 opts.debugging_opts.print_mono_items = Some(String::from("abc"));
3146 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3147 opts.debugging_opts.dump_mir = Some(String::from("abc"));
3148 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3149 opts.debugging_opts.dump_mir_dir = String::from("abc");
3150 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3151 opts.debugging_opts.dump_mir_graphviz = true;
3152 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3154 // Make sure changing a [TRACKED] option changes the hash
3155 opts = reference.clone();
3156 opts.debugging_opts.asm_comments = true;
3157 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3159 opts = reference.clone();
3160 opts.debugging_opts.verify_llvm_ir = true;
3161 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3163 opts = reference.clone();
3164 opts.debugging_opts.no_landing_pads = true;
3165 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3167 opts = reference.clone();
3168 opts.debugging_opts.fewer_names = true;
3169 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3171 opts = reference.clone();
3172 opts.debugging_opts.no_codegen = true;
3173 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3175 opts = reference.clone();
3176 opts.debugging_opts.treat_err_as_bug = true;
3177 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3179 opts = reference.clone();
3180 opts.debugging_opts.report_delayed_bugs = true;
3181 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3183 opts = reference.clone();
3184 opts.debugging_opts.continue_parse_after_error = true;
3185 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3187 opts = reference.clone();
3188 opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
3189 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3191 opts = reference.clone();
3192 opts.debugging_opts.force_overflow_checks = Some(true);
3193 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3195 opts = reference.clone();
3196 opts.debugging_opts.show_span = Some(String::from("abc"));
3197 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3199 opts = reference.clone();
3200 opts.debugging_opts.mir_opt_level = 3;
3201 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3203 opts = reference.clone();
3204 opts.debugging_opts.relro_level = Some(RelroLevel::Full);
3205 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3207 opts = reference.clone();
3208 opts.debugging_opts.cross_lang_lto = CrossLangLto::LinkerPluginAuto;
3209 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3213 fn test_edition_parsing() {
3214 // test default edition
3215 let options = Options::default();
3216 assert!(options.edition == DEFAULT_EDITION);
3218 let matches = optgroups()
3219 .parse(&["--edition=2018".to_string()])
3221 let (sessopts, _) = build_session_options_and_crate_config(&matches);
3222 assert!(sessopts.edition == Edition::Edition2018)