1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Contains infrastructure for configuring the compiler, including parsing
12 //! command line options.
14 pub use self::EntryFnType::*;
15 pub use self::CrateType::*;
16 pub use self::Passes::*;
17 pub use self::DebugInfoLevel::*;
19 use std::str::FromStr;
21 use session::{early_error, early_warn, Session};
22 use session::search_paths::SearchPaths;
24 use ich::StableHashingContext;
25 use rustc_target::spec::{LinkerFlavor, PanicStrategy, RelroLevel};
26 use rustc_target::spec::{Target, TargetTriple};
27 use rustc_data_structures::stable_hasher::ToStableHashKey;
31 use syntax::ast::{self, IntTy, UintTy};
32 use syntax::codemap::{FileName, FilePathMapping};
33 use syntax::edition::{Edition, EDITION_NAME_LIST, DEFAULT_EDITION};
34 use syntax::parse::token;
36 use syntax::symbol::Symbol;
37 use syntax::feature_gate::UnstableFeatures;
39 use errors::{ColorConfig, FatalError, Handler};
42 use std::collections::{BTreeMap, BTreeSet};
43 use std::collections::btree_map::Iter as BTreeMapIter;
44 use std::collections::btree_map::Keys as BTreeMapKeysIter;
45 use std::collections::btree_map::Values as BTreeMapValuesIter;
48 use std::hash::Hasher;
49 use std::collections::hash_map::DefaultHasher;
50 use std::collections::HashSet;
51 use std::iter::FromIterator;
52 use std::path::{Path, PathBuf};
60 #[derive(Clone, Hash, Debug)]
68 #[derive(Clone, Copy, PartialEq, Hash)]
78 #[derive(Clone, Copy, PartialEq, Hash)]
80 /// Don't do any LTO whatsoever
83 /// Do a full crate graph LTO. The flavor is determined by the compiler
84 /// (currently the default is "fat").
87 /// Do a full crate graph LTO with ThinLTO
90 /// Do a local graph LTO with ThinLTO (only relevant for multiple codegen
94 /// Do a full crate graph LTO with "fat" LTO
98 #[derive(Clone, PartialEq, Hash)]
99 pub enum CrossLangLto {
100 LinkerPlugin(PathBuf),
106 pub fn enabled(&self) -> bool {
108 CrossLangLto::LinkerPlugin(_) |
109 CrossLangLto::LinkerPluginAuto => true,
110 CrossLangLto::Disabled => false,
115 #[derive(Clone, Copy, PartialEq, Hash)]
116 pub enum DebugInfoLevel {
122 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
123 pub enum OutputType {
135 impl_stable_hash_for!(enum self::OutputType {
146 impl<'a, 'tcx> ToStableHashKey<StableHashingContext<'a>> for OutputType {
147 type KeyType = OutputType;
149 fn to_stable_hash_key(&self, _: &StableHashingContext<'a>) -> Self::KeyType {
155 fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
157 OutputType::Exe | OutputType::DepInfo => true,
159 | OutputType::Assembly
160 | OutputType::LlvmAssembly
163 | OutputType::Metadata => false,
167 fn shorthand(&self) -> &'static str {
169 OutputType::Bitcode => "llvm-bc",
170 OutputType::Assembly => "asm",
171 OutputType::LlvmAssembly => "llvm-ir",
172 OutputType::Mir => "mir",
173 OutputType::Object => "obj",
174 OutputType::Metadata => "metadata",
175 OutputType::Exe => "link",
176 OutputType::DepInfo => "dep-info",
180 fn from_shorthand(shorthand: &str) -> Option<Self> {
181 Some(match shorthand {
182 "asm" => OutputType::Assembly,
183 "llvm-ir" => OutputType::LlvmAssembly,
184 "mir" => OutputType::Mir,
185 "llvm-bc" => OutputType::Bitcode,
186 "obj" => OutputType::Object,
187 "metadata" => OutputType::Metadata,
188 "link" => OutputType::Exe,
189 "dep-info" => OutputType::DepInfo,
194 fn shorthands_display() -> String {
196 "`{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`",
197 OutputType::Bitcode.shorthand(),
198 OutputType::Assembly.shorthand(),
199 OutputType::LlvmAssembly.shorthand(),
200 OutputType::Mir.shorthand(),
201 OutputType::Object.shorthand(),
202 OutputType::Metadata.shorthand(),
203 OutputType::Exe.shorthand(),
204 OutputType::DepInfo.shorthand(),
208 pub fn extension(&self) -> &'static str {
210 OutputType::Bitcode => "bc",
211 OutputType::Assembly => "s",
212 OutputType::LlvmAssembly => "ll",
213 OutputType::Mir => "mir",
214 OutputType::Object => "o",
215 OutputType::Metadata => "rmeta",
216 OutputType::DepInfo => "d",
217 OutputType::Exe => "",
222 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
223 pub enum ErrorOutputType {
224 HumanReadable(ColorConfig),
229 impl Default for ErrorOutputType {
230 fn default() -> ErrorOutputType {
231 ErrorOutputType::HumanReadable(ColorConfig::Auto)
235 // Use tree-based collections to cheaply get a deterministic Hash implementation.
236 // DO NOT switch BTreeMap out for an unsorted container type! That would break
237 // dependency tracking for commandline arguments.
238 #[derive(Clone, Hash)]
239 pub struct OutputTypes(BTreeMap<OutputType, Option<PathBuf>>);
241 impl_stable_hash_for!(tuple_struct self::OutputTypes {
246 pub fn new(entries: &[(OutputType, Option<PathBuf>)]) -> OutputTypes {
247 OutputTypes(BTreeMap::from_iter(
248 entries.iter().map(|&(k, ref v)| (k, v.clone())),
252 pub fn get(&self, key: &OutputType) -> Option<&Option<PathBuf>> {
256 pub fn contains_key(&self, key: &OutputType) -> bool {
257 self.0.contains_key(key)
260 pub fn keys<'a>(&'a self) -> BTreeMapKeysIter<'a, OutputType, Option<PathBuf>> {
264 pub fn values<'a>(&'a self) -> BTreeMapValuesIter<'a, OutputType, Option<PathBuf>> {
268 pub fn len(&self) -> usize {
272 // True if any of the output types require codegen or linking.
273 pub fn should_codegen(&self) -> bool {
274 self.0.keys().any(|k| match *k {
276 | OutputType::Assembly
277 | OutputType::LlvmAssembly
280 | OutputType::Exe => true,
281 OutputType::Metadata | OutputType::DepInfo => false,
286 // Use tree-based collections to cheaply get a deterministic Hash implementation.
287 // DO NOT switch BTreeMap or BTreeSet out for an unsorted container type! That
288 // would break dependency tracking for commandline arguments.
289 #[derive(Clone, Hash)]
290 pub struct Externs(BTreeMap<String, BTreeSet<String>>);
293 pub fn new(data: BTreeMap<String, BTreeSet<String>>) -> Externs {
297 pub fn get(&self, key: &str) -> Option<&BTreeSet<String>> {
301 pub fn iter<'a>(&'a self) -> BTreeMapIter<'a, String, BTreeSet<String>> {
306 macro_rules! hash_option {
307 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [UNTRACKED]) => ({});
308 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({
309 if $sub_hashes.insert(stringify!($opt_name),
310 $opt_expr as &dyn dep_tracking::DepTrackingHash).is_some() {
311 bug!("Duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
317 [UNTRACKED_WITH_WARNING $warn_val:expr, $warn_text:expr, $error_format:expr]) => ({
318 if *$opt_expr == $warn_val {
319 early_warn($error_format, $warn_text)
324 macro_rules! top_level_options {
325 (pub struct Options { $(
326 $opt:ident : $t:ty [$dep_tracking_marker:ident $($warn_val:expr, $warn_text:expr)*],
334 pub fn dep_tracking_hash(&self) -> u64 {
335 let mut sub_hashes = BTreeMap::new();
340 [$dep_tracking_marker $($warn_val,
342 self.error_format)*]);
344 let mut hasher = DefaultHasher::new();
345 dep_tracking::stable_hash(sub_hashes,
354 // The top-level commandline options struct
356 // For each option, one has to specify how it behaves with regard to the
357 // dependency tracking system of incremental compilation. This is done via the
358 // square-bracketed directive after the field type. The options are:
361 // A change in the given field will cause the compiler to completely clear the
362 // incremental compilation cache before proceeding.
365 // Incremental compilation is not influenced by this option.
367 // [UNTRACKED_WITH_WARNING(val, warning)]
368 // The option is incompatible with incremental compilation in some way. If it
369 // has the value `val`, the string `warning` is emitted as a warning.
371 // If you add a new option to this struct or one of the sub-structs like
372 // CodegenOptions, think about how it influences incremental compilation. If in
373 // doubt, specify [TRACKED], which is always "correct" but might lead to
374 // unnecessary re-compilation.
377 // The crate config requested for the session, which may be combined
378 // with additional crate configurations during the compile process
379 crate_types: Vec<CrateType> [TRACKED],
380 optimize: OptLevel [TRACKED],
381 // Include the debug_assertions flag into dependency tracking, since it
382 // can influence whether overflow checks are done or not.
383 debug_assertions: bool [TRACKED],
384 debuginfo: DebugInfoLevel [TRACKED],
385 lint_opts: Vec<(String, lint::Level)> [TRACKED],
386 lint_cap: Option<lint::Level> [TRACKED],
387 describe_lints: bool [UNTRACKED],
388 output_types: OutputTypes [TRACKED],
389 search_paths: SearchPaths [UNTRACKED],
390 libs: Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> [TRACKED],
391 maybe_sysroot: Option<PathBuf> [TRACKED],
393 target_triple: TargetTriple [TRACKED],
395 test: bool [TRACKED],
396 error_format: ErrorOutputType [UNTRACKED],
398 // if Some, enable incremental compilation, using the given
399 // directory to store intermediate results
400 incremental: Option<PathBuf> [UNTRACKED],
402 debugging_opts: DebuggingOptions [TRACKED],
403 prints: Vec<PrintRequest> [UNTRACKED],
404 // Determines which borrow checker(s) to run. This is the parsed, sanitized
405 // version of `debugging_opts.borrowck`, which is just a plain string.
406 borrowck_mode: BorrowckMode [UNTRACKED],
407 cg: CodegenOptions [TRACKED],
408 externs: Externs [UNTRACKED],
409 crate_name: Option<String> [TRACKED],
410 // An optional name to use as the crate for std during std injection,
411 // written `extern crate name as std`. Defaults to `std`. Used by
412 // out-of-tree drivers.
413 alt_std_name: Option<String> [TRACKED],
414 // Indicates how the compiler should treat unstable features
415 unstable_features: UnstableFeatures [TRACKED],
417 // Indicates whether this run of the compiler is actually rustdoc. This
418 // is currently just a hack and will be removed eventually, so please
419 // try to not rely on this too much.
420 actually_rustdoc: bool [TRACKED],
422 // Specifications of codegen units / ThinLTO which are forced as a
423 // result of parsing command line options. These are not necessarily
424 // what rustc was invoked with, but massaged a bit to agree with
425 // commands like `--emit llvm-ir` which they're often incompatible with
426 // if we otherwise use the defaults of rustc.
427 cli_forced_codegen_units: Option<usize> [UNTRACKED],
428 cli_forced_thinlto_off: bool [UNTRACKED],
430 // Remap source path prefixes in all output (messages, object files, debug, etc)
431 remap_path_prefix: Vec<(PathBuf, PathBuf)> [UNTRACKED],
433 edition: Edition [TRACKED],
437 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
438 pub enum PrintRequest {
453 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
454 pub enum BorrowckMode {
462 /// Should we run the MIR-based borrow check, but also fall back
463 /// on the AST borrow check if the MIR-based one errors.
464 pub fn migrate(self) -> bool {
466 BorrowckMode::Ast => false,
467 BorrowckMode::Compare => false,
468 BorrowckMode::Mir => false,
469 BorrowckMode::Migrate => true,
473 /// Should we emit the AST-based borrow checker errors?
474 pub fn use_ast(self) -> bool {
476 BorrowckMode::Ast => true,
477 BorrowckMode::Compare => true,
478 BorrowckMode::Mir => false,
479 BorrowckMode::Migrate => false,
482 /// Should we emit the MIR-based borrow checker errors?
483 pub fn use_mir(self) -> bool {
485 BorrowckMode::Ast => false,
486 BorrowckMode::Compare => true,
487 BorrowckMode::Mir => true,
488 BorrowckMode::Migrate => true,
494 /// Load source from file
497 /// String that is shown in place of a filename
499 /// Anonymous source string
505 pub fn filestem(&self) -> String {
507 Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap().to_string(),
508 Input::Str { .. } => "rust_out".to_string(),
512 pub fn get_input(&mut self) -> Option<&mut String> {
514 Input::File(_) => None,
515 Input::Str { ref mut input, .. } => Some(input),
521 pub struct OutputFilenames {
522 pub out_directory: PathBuf,
523 pub out_filestem: String,
524 pub single_output_file: Option<PathBuf>,
526 pub outputs: OutputTypes,
529 impl_stable_hash_for!(struct self::OutputFilenames {
537 pub const RUST_CGU_EXT: &str = "rcgu";
539 impl OutputFilenames {
540 pub fn path(&self, flavor: OutputType) -> PathBuf {
543 .and_then(|p| p.to_owned())
544 .or_else(|| self.single_output_file.clone())
545 .unwrap_or_else(|| self.temp_path(flavor, None))
548 /// Get the path where a compilation artifact of the given type for the
549 /// given codegen unit should be placed on disk. If codegen_unit_name is
550 /// None, a path distinct from those of any codegen unit will be generated.
551 pub fn temp_path(&self, flavor: OutputType, codegen_unit_name: Option<&str>) -> PathBuf {
552 let extension = flavor.extension();
553 self.temp_path_ext(extension, codegen_unit_name)
556 /// Like temp_path, but also supports things where there is no corresponding
557 /// OutputType, like no-opt-bitcode or lto-bitcode.
558 pub fn temp_path_ext(&self, ext: &str, codegen_unit_name: Option<&str>) -> PathBuf {
559 let base = self.out_directory.join(&self.filestem());
561 let mut extension = String::new();
563 if let Some(codegen_unit_name) = codegen_unit_name {
564 extension.push_str(codegen_unit_name);
568 if !extension.is_empty() {
569 extension.push_str(".");
570 extension.push_str(RUST_CGU_EXT);
571 extension.push_str(".");
574 extension.push_str(ext);
577 let path = base.with_extension(&extension[..]);
581 pub fn with_extension(&self, extension: &str) -> PathBuf {
583 .join(&self.filestem())
584 .with_extension(extension)
587 pub fn filestem(&self) -> String {
588 format!("{}{}", self.out_filestem, self.extra)
592 pub fn host_triple() -> &'static str {
593 // Get the host triple out of the build environment. This ensures that our
594 // idea of the host triple is the same as for the set of libraries we've
595 // actually built. We can't just take LLVM's host triple because they
596 // normalize all ix86 architectures to i386.
598 // Instead of grabbing the host triple (for the current host), we grab (at
599 // compile time) the target triple that this rustc is built with and
600 // calling that (at runtime) the host triple.
601 (option_env!("CFG_COMPILER_HOST_TRIPLE")).expect("CFG_COMPILER_HOST_TRIPLE")
604 /// Some reasonable defaults
605 pub fn basic_options() -> Options {
607 crate_types: Vec::new(),
608 optimize: OptLevel::No,
609 debuginfo: NoDebugInfo,
610 lint_opts: Vec::new(),
612 describe_lints: false,
613 output_types: OutputTypes(BTreeMap::new()),
614 search_paths: SearchPaths::new(),
616 target_triple: TargetTriple::from_triple(host_triple()),
619 debugging_opts: basic_debugging_options(),
621 borrowck_mode: BorrowckMode::Ast,
622 cg: basic_codegen_options(),
623 error_format: ErrorOutputType::default(),
624 externs: Externs(BTreeMap::new()),
628 unstable_features: UnstableFeatures::Disallow,
629 debug_assertions: true,
630 actually_rustdoc: false,
631 cli_forced_codegen_units: None,
632 cli_forced_thinlto_off: false,
633 remap_path_prefix: Vec::new(),
634 edition: DEFAULT_EDITION,
639 /// True if there is a reason to build the dep graph.
640 pub fn build_dep_graph(&self) -> bool {
641 self.incremental.is_some() || self.debugging_opts.dump_dep_graph
642 || self.debugging_opts.query_dep_graph
646 pub fn enable_dep_node_debug_strs(&self) -> bool {
647 cfg!(debug_assertions)
648 && (self.debugging_opts.query_dep_graph || self.debugging_opts.incremental_info)
651 pub fn file_path_mapping(&self) -> FilePathMapping {
652 FilePathMapping::new(self.remap_path_prefix.clone())
655 /// True if there will be an output file generated
656 pub fn will_create_output_file(&self) -> bool {
657 !self.debugging_opts.parse_only && // The file is just being parsed
658 !self.debugging_opts.ls // The file is just being queried
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)]
683 SomePasses(Vec<String>),
688 pub fn is_empty(&self) -> bool {
690 SomePasses(ref v) => v.is_empty(),
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("one of `thin`, `fat`, or omitted");
819 pub const parse_cross_lang_lto: Option<&'static str> =
820 Some("either a boolean (`yes`, `no`, `on`, `off`, etc), `no-link`, \
821 or the path to the linker plugin");
826 use super::{$struct_name, Passes, SomePasses, AllPasses, Sanitizer, Lto,
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 for s in s.split_whitespace() {
903 slot.push(s.to_string());
911 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
915 let v = s.split_whitespace().map(|s| s.to_string()).collect();
923 fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
924 match v.and_then(|s| s.parse().ok()) {
925 Some(i) => { *slot = i; true },
930 fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
932 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
933 None => { *slot = None; false }
937 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
944 let mut passes = vec![];
945 if parse_list(&mut passes, v) {
946 *slot = SomePasses(passes);
955 fn parse_panic_strategy(slot: &mut Option<PanicStrategy>, v: Option<&str>) -> bool {
957 Some("unwind") => *slot = Some(PanicStrategy::Unwind),
958 Some("abort") => *slot = Some(PanicStrategy::Abort),
964 fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
967 match s.parse::<RelroLevel>() {
968 Ok(level) => *slot = Some(level),
977 fn parse_sanitizer(slote: &mut Option<Sanitizer>, v: Option<&str>) -> bool {
979 Some("address") => *slote = Some(Sanitizer::Address),
980 Some("leak") => *slote = Some(Sanitizer::Leak),
981 Some("memory") => *slote = Some(Sanitizer::Memory),
982 Some("thread") => *slote = Some(Sanitizer::Thread),
988 fn parse_linker_flavor(slote: &mut Option<LinkerFlavor>, v: Option<&str>) -> bool {
989 match v.and_then(LinkerFlavor::from_str) {
990 Some(lf) => *slote = Some(lf),
996 fn parse_optimization_fuel(slot: &mut Option<(String, u64)>, v: Option<&str>) -> bool {
1000 let parts = s.split('=').collect::<Vec<_>>();
1001 if parts.len() != 2 { return false; }
1002 let crate_name = parts[0].to_string();
1003 let fuel = parts[1].parse::<u64>();
1004 if fuel.is_err() { return false; }
1005 *slot = Some((crate_name, fuel.unwrap()));
1011 fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
1014 Some(s) if s.split('=').count() <= 2 => {
1015 *slot = Some(s.to_string());
1022 fn parse_lto(slot: &mut Lto, v: Option<&str>) -> bool {
1025 Some("thin") => Lto::Thin,
1026 Some("fat") => Lto::Fat,
1027 Some(_) => return false,
1032 fn parse_cross_lang_lto(slot: &mut CrossLangLto, v: Option<&str>) -> bool {
1034 let mut bool_arg = None;
1035 if parse_opt_bool(&mut bool_arg, v) {
1036 *slot = if bool_arg.unwrap() {
1037 CrossLangLto::LinkerPluginAuto
1039 CrossLangLto::Disabled
1046 None => CrossLangLto::LinkerPluginAuto,
1047 Some(path) => CrossLangLto::LinkerPlugin(PathBuf::from(path)),
1054 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
1055 build_codegen_options, "C", "codegen",
1056 CG_OPTIONS, cg_type_desc, cgsetters,
1057 ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
1058 "this option is deprecated and does nothing"),
1059 linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
1060 "system linker to link outputs with"),
1061 link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1062 "a single extra argument to append to the linker invocation (can be used several times)"),
1063 link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1064 "extra arguments to append to the linker invocation (space separated)"),
1065 link_dead_code: bool = (false, parse_bool, [UNTRACKED],
1066 "don't let linker strip dead code (turning it on can be used for code coverage)"),
1067 lto: Lto = (Lto::No, parse_lto, [TRACKED],
1068 "perform LLVM link-time optimizations"),
1069 target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
1070 "select target processor (rustc --print target-cpus for details)"),
1071 target_feature: String = ("".to_string(), parse_string, [TRACKED],
1072 "target specific attributes (rustc --print target-features for details)"),
1073 passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1074 "a list of extra LLVM passes to run (space separated)"),
1075 llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1076 "a list of arguments to pass to llvm (space separated)"),
1077 save_temps: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1078 "`-C save-temps` might not produce all requested temporary products \
1079 when incremental compilation is enabled.")],
1080 "save all temporary output files during compilation"),
1081 rpath: bool = (false, parse_bool, [UNTRACKED],
1082 "set rpath values in libs/exes"),
1083 overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1084 "use overflow checks for integer arithmetic"),
1085 no_prepopulate_passes: bool = (false, parse_bool, [TRACKED],
1086 "don't pre-populate the pass manager with a list of passes"),
1087 no_vectorize_loops: bool = (false, parse_bool, [TRACKED],
1088 "don't run the loop vectorization optimization passes"),
1089 no_vectorize_slp: bool = (false, parse_bool, [TRACKED],
1090 "don't run LLVM's SLP vectorization pass"),
1091 soft_float: bool = (false, parse_bool, [TRACKED],
1092 "use soft float ABI (*eabihf targets only)"),
1093 prefer_dynamic: bool = (false, parse_bool, [TRACKED],
1094 "prefer dynamic linking to static linking"),
1095 no_integrated_as: bool = (false, parse_bool, [TRACKED],
1096 "use an external assembler rather than LLVM's integrated one"),
1097 no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
1098 "disable the use of the redzone"),
1099 relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
1100 "choose the relocation model to use (rustc --print relocation-models for details)"),
1101 code_model: Option<String> = (None, parse_opt_string, [TRACKED],
1102 "choose the code model to use (rustc --print code-models for details)"),
1103 metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1104 "metadata to mangle symbol names with"),
1105 extra_filename: String = ("".to_string(), parse_string, [UNTRACKED],
1106 "extra data to put in each output filename"),
1107 codegen_units: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1108 "divide crate into N units to optimize in parallel"),
1109 remark: Passes = (SomePasses(Vec::new()), parse_passes, [UNTRACKED],
1110 "print remarks for these optimization passes (space separated, or \"all\")"),
1111 no_stack_check: bool = (false, parse_bool, [UNTRACKED],
1112 "the --no-stack-check flag is deprecated and does nothing"),
1113 debuginfo: Option<usize> = (None, parse_opt_uint, [TRACKED],
1114 "debug info emission level, 0 = no debug info, 1 = line tables only, \
1115 2 = full debug info with variable and type information"),
1116 opt_level: Option<String> = (None, parse_opt_string, [TRACKED],
1117 "optimize with possible levels 0-3, s, or z"),
1118 force_frame_pointers: Option<bool> = (None, parse_opt_bool, [TRACKED],
1119 "force use of the frame pointers"),
1120 debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
1121 "explicitly enable the cfg(debug_assertions) directive"),
1122 inline_threshold: Option<usize> = (None, parse_opt_uint, [TRACKED],
1123 "set the threshold for inlining a function (default: 225)"),
1124 panic: Option<PanicStrategy> = (None, parse_panic_strategy,
1125 [TRACKED], "panic strategy to compile crate with"),
1126 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1127 "enable incremental compilation"),
1130 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
1131 build_debugging_options, "Z", "debugging",
1132 DB_OPTIONS, db_type_desc, dbsetters,
1133 codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
1134 "the backend to use"),
1135 verbose: bool = (false, parse_bool, [UNTRACKED],
1136 "in general, enable more debug printouts"),
1137 span_free_formats: bool = (false, parse_bool, [UNTRACKED],
1138 "when debug-printing compiler state, do not include spans"), // o/w tests have closure@path
1139 identify_regions: bool = (false, parse_bool, [UNTRACKED],
1140 "make unnamed regions display as '# (where # is some non-ident unique id)"),
1141 emit_end_regions: bool = (false, parse_bool, [UNTRACKED],
1142 "emit EndRegion as part of MIR; enable transforms that solely process EndRegion"),
1143 borrowck: Option<String> = (None, parse_opt_string, [UNTRACKED],
1144 "select which borrowck is used (`ast`, `mir`, `migrate`, or `compare`)"),
1145 two_phase_borrows: bool = (false, parse_bool, [UNTRACKED],
1146 "use two-phase reserved/active distinction for `&mut` borrows in MIR borrowck"),
1147 two_phase_beyond_autoref: bool = (false, parse_bool, [UNTRACKED],
1148 "when using two-phase-borrows, allow two phases even for non-autoref `&mut` borrows"),
1149 time_passes: bool = (false, parse_bool, [UNTRACKED],
1150 "measure time of each rustc pass"),
1151 count_llvm_insns: bool = (false, parse_bool,
1152 [UNTRACKED_WITH_WARNING(true,
1153 "The output generated by `-Z count_llvm_insns` might not be reliable \
1154 when used with incremental compilation")],
1155 "count where LLVM instrs originate"),
1156 time_llvm_passes: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1157 "The output of `-Z time-llvm-passes` will only reflect timings of \
1158 re-codegened modules when used with incremental compilation" )],
1159 "measure time of each LLVM pass"),
1160 input_stats: bool = (false, parse_bool, [UNTRACKED],
1161 "gather statistics about the input"),
1162 codegen_stats: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
1163 "The output of `-Z codegen-stats` might not be accurate when incremental \
1164 compilation is enabled")],
1165 "gather codegen statistics"),
1166 asm_comments: bool = (false, parse_bool, [TRACKED],
1167 "generate comments into the assembly (may change behavior)"),
1168 verify_llvm_ir: bool = (false, parse_bool, [TRACKED],
1170 borrowck_stats: bool = (false, parse_bool, [UNTRACKED],
1171 "gather borrowck statistics"),
1172 no_landing_pads: bool = (false, parse_bool, [TRACKED],
1173 "omit landing pads for unwinding"),
1174 fewer_names: bool = (false, parse_bool, [TRACKED],
1175 "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR)"),
1176 meta_stats: bool = (false, parse_bool, [UNTRACKED],
1177 "gather metadata statistics"),
1178 print_link_args: bool = (false, parse_bool, [UNTRACKED],
1179 "print the arguments passed to the linker"),
1180 print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1181 "prints the llvm optimization passes being run"),
1182 ast_json: bool = (false, parse_bool, [UNTRACKED],
1183 "print the AST as JSON and halt"),
1184 query_threads: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1185 "execute queries on a thread pool with N threads"),
1186 ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
1187 "print the pre-expansion AST as JSON and halt"),
1188 ls: bool = (false, parse_bool, [UNTRACKED],
1189 "list the symbols defined by a library crate"),
1190 save_analysis: bool = (false, parse_bool, [UNTRACKED],
1191 "write syntax and type analysis (in JSON format) information, in \
1192 addition to normal output"),
1193 flowgraph_print_loans: bool = (false, parse_bool, [UNTRACKED],
1194 "include loan analysis data in -Z unpretty flowgraph output"),
1195 flowgraph_print_moves: bool = (false, parse_bool, [UNTRACKED],
1196 "include move analysis data in -Z unpretty flowgraph output"),
1197 flowgraph_print_assigns: bool = (false, parse_bool, [UNTRACKED],
1198 "include assignment analysis data in -Z unpretty flowgraph output"),
1199 flowgraph_print_all: bool = (false, parse_bool, [UNTRACKED],
1200 "include all dataflow analysis data in -Z unpretty flowgraph output"),
1201 print_region_graph: bool = (false, parse_bool, [UNTRACKED],
1202 "prints region inference graph. \
1203 Use with RUST_REGION_GRAPH=help for more info"),
1204 parse_only: bool = (false, parse_bool, [UNTRACKED],
1205 "parse only; do not compile, assemble, or link"),
1206 no_codegen: bool = (false, parse_bool, [TRACKED],
1207 "run all passes except codegen; no output"),
1208 treat_err_as_bug: bool = (false, parse_bool, [TRACKED],
1209 "treat all errors that occur as bugs"),
1210 report_delayed_bugs: bool = (false, parse_bool, [TRACKED],
1211 "immediately print bugs registered with `delay_span_bug`"),
1212 external_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1213 "show macro backtraces even for non-local macros"),
1214 teach: bool = (false, parse_bool, [TRACKED],
1215 "show extended diagnostic help"),
1216 continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
1217 "attempt to recover from parse errors (experimental)"),
1218 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1219 "enable incremental compilation (experimental)"),
1220 incremental_queries: bool = (true, parse_bool, [UNTRACKED],
1221 "enable incremental compilation support for queries (experimental)"),
1222 incremental_info: bool = (false, parse_bool, [UNTRACKED],
1223 "print high-level information about incremental reuse (or the lack thereof)"),
1224 incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
1225 "dump hash information in textual format to stdout"),
1226 incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
1227 "verify incr. comp. hashes of green query instances"),
1228 incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
1229 "ignore spans during ICH computation -- used for testing"),
1230 dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1231 "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
1232 query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1233 "enable queries of the dependency graph for regression testing"),
1234 profile_queries: bool = (false, parse_bool, [UNTRACKED],
1235 "trace and profile the queries of the incremental compilation framework"),
1236 profile_queries_and_keys: bool = (false, parse_bool, [UNTRACKED],
1237 "trace and profile the queries and keys of the incremental compilation framework"),
1238 no_analysis: bool = (false, parse_bool, [UNTRACKED],
1239 "parse and expand the source, but run no analysis"),
1240 extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1241 "load extra plugins"),
1242 unstable_options: bool = (false, parse_bool, [UNTRACKED],
1243 "adds unstable command line options to rustc interface"),
1244 force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1245 "force overflow checks on or off"),
1246 trace_macros: bool = (false, parse_bool, [UNTRACKED],
1247 "for every macro invocation, print its name and arguments"),
1248 debug_macros: bool = (false, parse_bool, [TRACKED],
1249 "emit line numbers debug info inside macros"),
1250 keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
1251 "don't clear the hygiene data after analysis"),
1252 keep_ast: bool = (false, parse_bool, [UNTRACKED],
1253 "keep the AST after lowering it to HIR"),
1254 show_span: Option<String> = (None, parse_opt_string, [TRACKED],
1255 "show spans for compiler debugging (expr|pat|ty)"),
1256 print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
1257 "print layout information for each type encountered"),
1258 print_mono_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
1259 "print the result of the monomorphization collection pass"),
1260 mir_opt_level: usize = (1, parse_uint, [TRACKED],
1261 "set the MIR optimization level (0-3, default: 1)"),
1262 mutable_noalias: Option<bool> = (None, parse_opt_bool, [TRACKED],
1263 "emit noalias metadata for mutable references (default: yes on LLVM >= 6)"),
1264 arg_align_attributes: bool = (false, parse_bool, [TRACKED],
1265 "emit align metadata for reference arguments"),
1266 dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1267 "dump MIR state at various points in transforms"),
1268 dump_mir_dir: String = (String::from("mir_dump"), parse_string, [UNTRACKED],
1269 "the directory the MIR is dumped into"),
1270 dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
1271 "in addition to `.mir` files, create graphviz `.dot` files"),
1272 dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
1273 "if set, exclude the pass number when dumping MIR (used in tests)"),
1274 mir_emit_validate: usize = (0, parse_uint, [TRACKED],
1275 "emit Validate MIR statements, interpreted e.g. by miri (0: do not emit; 1: if function \
1276 contains unsafe block, only validate arguments; 2: always emit full validation)"),
1277 perf_stats: bool = (false, parse_bool, [UNTRACKED],
1278 "print some performance-related statistics"),
1279 hir_stats: bool = (false, parse_bool, [UNTRACKED],
1280 "print some statistics about AST and HIR"),
1281 mir_stats: bool = (false, parse_bool, [UNTRACKED],
1282 "print some statistics about MIR"),
1283 always_encode_mir: bool = (false, parse_bool, [TRACKED],
1284 "encode MIR of all functions into the crate metadata"),
1285 osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
1286 "pass `-install_name @rpath/...` to the macOS linker"),
1287 sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
1289 linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
1291 fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
1292 "set the optimization fuel quota for a crate"),
1293 print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
1294 "make Rustc print the total optimization fuel used by a crate"),
1295 force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
1296 "force all crates to be `rustc_private` unstable"),
1297 pre_link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1298 "a single extra argument to prepend the linker invocation (can be used several times)"),
1299 pre_link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1300 "extra arguments to prepend to the linker invocation (space separated)"),
1301 profile: bool = (false, parse_bool, [TRACKED],
1302 "insert profiling code"),
1303 pgo_gen: Option<String> = (None, parse_opt_string, [TRACKED],
1304 "Generate PGO profile data, to a given file, or to the default \
1305 location if it's empty."),
1306 pgo_use: String = (String::new(), parse_string, [TRACKED],
1307 "Use PGO profile data from the given profile file."),
1308 disable_instrumentation_preinliner: bool =
1309 (false, parse_bool, [TRACKED], "Disable the instrumentation pre-inliner, \
1310 useful for profiling / PGO."),
1311 relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
1312 "choose which RELRO level to use"),
1313 disable_ast_check_for_mutation_in_guard: bool = (false, parse_bool, [UNTRACKED],
1314 "skip AST-based mutation-in-guard check (mir-borrowck provides more precise check)"),
1315 nll_subminimal_causes: bool = (false, parse_bool, [UNTRACKED],
1316 "when tracking region error causes, accept subminimal results for faster execution."),
1317 nll_facts: bool = (false, parse_bool, [UNTRACKED],
1318 "dump facts from NLL analysis into side files"),
1319 disable_nll_user_type_assert: bool = (false, parse_bool, [UNTRACKED],
1320 "disable user provided type assertion in NLL"),
1321 nll_dont_emit_read_for_match: bool = (false, parse_bool, [UNTRACKED],
1322 "in match codegen, do not include ReadForMatch statements (used by mir-borrowck)"),
1323 polonius: bool = (false, parse_bool, [UNTRACKED],
1324 "enable polonius-based borrow-checker"),
1325 codegen_time_graph: bool = (false, parse_bool, [UNTRACKED],
1326 "generate a graphical HTML report of time spent in codegen and LLVM"),
1327 thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
1328 "enable ThinLTO when possible"),
1329 inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
1330 "control whether #[inline] functions are in all cgus"),
1331 tls_model: Option<String> = (None, parse_opt_string, [TRACKED],
1332 "choose the TLS model to use (rustc --print tls-models for details)"),
1333 saturating_float_casts: bool = (false, parse_bool, [TRACKED],
1334 "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
1335 the max/min integer respectively, and NaN is mapped to 0"),
1336 lower_128bit_ops: Option<bool> = (None, parse_opt_bool, [TRACKED],
1337 "rewrite operators on i128 and u128 into lang item calls (typically provided \
1338 by compiler-builtins) so codegen doesn't need to support them,
1339 overriding the default for the current target"),
1340 human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
1341 "generate human-readable, predictable names for codegen units"),
1342 dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
1343 "in dep-info output, omit targets for tracking dependencies of the dep-info files \
1345 unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
1346 "Present the input source, unstable (and less-pretty) variants;
1347 valid types are any of the types for `--pretty`, as well as:
1348 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
1349 `everybody_loops` (all function bodies replaced with `loop {}`),
1350 `hir` (the HIR), `hir,identified`, or
1351 `hir,typed` (HIR with types for each node)."),
1352 run_dsymutil: Option<bool> = (None, parse_opt_bool, [TRACKED],
1353 "run `dsymutil` and delete intermediate object files"),
1354 ui_testing: bool = (false, parse_bool, [UNTRACKED],
1355 "format compiler diagnostics in a way that's better suitable for UI testing"),
1356 embed_bitcode: bool = (false, parse_bool, [TRACKED],
1357 "embed LLVM bitcode in object files"),
1358 strip_debuginfo_if_disabled: Option<bool> = (None, parse_opt_bool, [TRACKED],
1359 "tell the linker to strip debuginfo when building without debuginfo enabled."),
1360 share_generics: Option<bool> = (None, parse_opt_bool, [TRACKED],
1361 "make the current crate share its generic instantiations"),
1362 chalk: bool = (false, parse_bool, [TRACKED],
1363 "enable the experimental Chalk-based trait solving engine"),
1364 cross_lang_lto: CrossLangLto = (CrossLangLto::Disabled, parse_cross_lang_lto, [TRACKED],
1365 "generate build artifacts that are compatible with linker-based LTO."),
1366 no_parallel_llvm: bool = (false, parse_bool, [UNTRACKED],
1367 "don't run LLVM in parallel (while keeping codegen-units and ThinLTO)"),
1368 no_leak_check: bool = (false, parse_bool, [UNTRACKED],
1369 "disables the 'leak check' for subtyping; unsound, but useful for tests"),
1372 pub fn default_lib_output() -> CrateType {
1376 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
1377 let end = &sess.target.target.target_endian;
1378 let arch = &sess.target.target.arch;
1379 let wordsz = &sess.target.target.target_pointer_width;
1380 let os = &sess.target.target.target_os;
1381 let env = &sess.target.target.target_env;
1382 let vendor = &sess.target.target.target_vendor;
1383 let min_atomic_width = sess.target.target.min_atomic_width();
1384 let max_atomic_width = sess.target.target.max_atomic_width();
1385 let atomic_cas = sess.target.target.options.atomic_cas;
1387 let mut ret = HashSet::new();
1389 ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
1390 if let Some(ref fam) = sess.target.target.options.target_family {
1391 ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam))));
1392 if fam == "windows" || fam == "unix" {
1393 ret.insert((Symbol::intern(fam), None));
1396 ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
1397 ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
1399 Symbol::intern("target_pointer_width"),
1400 Some(Symbol::intern(wordsz)),
1402 ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
1404 Symbol::intern("target_vendor"),
1405 Some(Symbol::intern(vendor)),
1407 if sess.target.target.options.has_elf_tls {
1408 ret.insert((Symbol::intern("target_thread_local"), None));
1410 for &i in &[8, 16, 32, 64, 128] {
1411 if i >= min_atomic_width && i <= max_atomic_width {
1412 let s = i.to_string();
1414 Symbol::intern("target_has_atomic"),
1415 Some(Symbol::intern(&s)),
1419 Symbol::intern("target_has_atomic"),
1420 Some(Symbol::intern("ptr")),
1426 ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern("cas"))));
1428 if sess.opts.debug_assertions {
1429 ret.insert((Symbol::intern("debug_assertions"), None));
1431 if sess.opts.crate_types.contains(&CrateTypeProcMacro) {
1432 ret.insert((Symbol::intern("proc_macro"), None));
1437 pub fn build_configuration(sess: &Session, mut user_cfg: ast::CrateConfig) -> ast::CrateConfig {
1438 // Combine the configuration requested by the session (command line) with
1439 // some default and generated configuration items
1440 let default_cfg = default_configuration(sess);
1441 // If the user wants a test runner, then add the test cfg
1443 user_cfg.insert((Symbol::intern("test"), None));
1445 user_cfg.extend(default_cfg.iter().cloned());
1449 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
1450 let target = match Target::search(&opts.target_triple) {
1453 sp.struct_fatal(&format!("Error loading target specification: {}", e))
1454 .help("Use `--print target-list` for a list of built-in targets")
1460 let (isize_ty, usize_ty) = match &target.target_pointer_width[..] {
1461 "16" => (ast::IntTy::I16, ast::UintTy::U16),
1462 "32" => (ast::IntTy::I32, ast::UintTy::U32),
1463 "64" => (ast::IntTy::I64, ast::UintTy::U64),
1464 w => sp.fatal(&format!(
1465 "target specification was invalid: \
1466 unrecognized target-pointer-width {}",
1478 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1479 pub enum OptionStability {
1485 pub struct RustcOptGroup {
1486 pub apply: Box<dyn Fn(&mut getopts::Options) -> &mut getopts::Options>,
1487 pub name: &'static str,
1488 pub stability: OptionStability,
1491 impl RustcOptGroup {
1492 pub fn is_stable(&self) -> bool {
1493 self.stability == OptionStability::Stable
1496 pub fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
1498 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1503 stability: OptionStability::Stable,
1507 pub fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
1509 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1514 stability: OptionStability::Unstable,
1519 // The `opt` local module holds wrappers around the `getopts` API that
1520 // adds extra rustc-specific metadata to each option; such metadata
1521 // is exposed by . The public
1522 // functions below ending with `_u` are the functions that return
1523 // *unstable* options, i.e. options that are only enabled when the
1524 // user also passes the `-Z unstable-options` debugging flag.
1526 // The `fn opt_u` etc below are written so that we can use them
1527 // in the future; do not warn about them not being used right now.
1528 #![allow(dead_code)]
1531 use super::RustcOptGroup;
1533 pub type R = RustcOptGroup;
1534 pub type S = &'static str;
1536 fn stable<F>(name: S, f: F) -> R
1538 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1540 RustcOptGroup::stable(name, f)
1543 fn unstable<F>(name: S, f: F) -> R
1545 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1547 RustcOptGroup::unstable(name, f)
1550 fn longer(a: S, b: S) -> S {
1551 if a.len() > b.len() {
1558 pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
1559 stable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1561 pub fn multi_s(a: S, b: S, c: S, d: S) -> R {
1562 stable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1564 pub fn flag_s(a: S, b: S, c: S) -> R {
1565 stable(longer(a, b), move |opts| opts.optflag(a, b, c))
1567 pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R {
1568 stable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1570 pub fn flagmulti_s(a: S, b: S, c: S) -> R {
1571 stable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1574 pub fn opt(a: S, b: S, c: S, d: S) -> R {
1575 unstable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1577 pub fn multi(a: S, b: S, c: S, d: S) -> R {
1578 unstable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1580 pub fn flag(a: S, b: S, c: S) -> R {
1581 unstable(longer(a, b), move |opts| opts.optflag(a, b, c))
1583 pub fn flagopt(a: S, b: S, c: S, d: S) -> R {
1584 unstable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1586 pub fn flagmulti(a: S, b: S, c: S) -> R {
1587 unstable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1591 /// Returns the "short" subset of the rustc command line options,
1592 /// including metadata for each option, such as whether the option is
1593 /// part of the stable long-term interface for rustc.
1594 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
1596 opt::flag_s("h", "help", "Display this message"),
1597 opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
1601 "Add a directory to the library search path. The
1602 optional KIND can be one of dependency, crate, native,
1603 framework or all (the default).",
1609 "Link the generated crate(s) to the specified native
1610 library NAME. The optional KIND can be one of
1611 static, dylib, or framework. If omitted, dylib is
1618 "Comma separated list of types of crates
1619 for the compiler to emit",
1620 "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]",
1625 "Specify the name of the crate being built",
1631 "Comma separated list of types of output for \
1632 the compiler to emit",
1633 "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]",
1638 "Comma separated list of compiler information to \
1640 "[crate-name|file-names|sysroot|cfg|target-list|\
1641 target-cpus|target-features|relocation-models|\
1642 code-models|tls-models|target-spec-json|native-static-libs]",
1644 opt::flagmulti_s("g", "", "Equivalent to -C debuginfo=2"),
1645 opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
1646 opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
1650 "Write output to compiler-chosen filename \
1657 "Provide a detailed explanation of an error \
1661 opt::flag_s("", "test", "Build a test harness"),
1665 "Target triple for which the code is compiled",
1668 opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
1669 opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
1670 opt::multi_s("D", "deny", "Set lint denied", "OPT"),
1671 opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
1675 "Set the most restrictive lint level. \
1676 More restrictive lints are capped at this \
1680 opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
1681 opt::flag_s("V", "version", "Print version info and exit"),
1682 opt::flag_s("v", "verbose", "Use verbose output"),
1686 /// Returns all rustc command line options, including metadata for
1687 /// each option, such as whether the option is part of the stable
1688 /// long-term interface for rustc.
1689 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
1690 let mut opts = rustc_short_optgroups();
1695 "Specify where an external rust library is located",
1698 opt::opt_s("", "sysroot", "Override the system root", "PATH"),
1699 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
1703 "How errors and other messages are produced",
1709 "Configure coloring of output:
1710 auto = colorize, if output goes to a tty (default);
1711 always = always colorize output;
1712 never = never colorize output",
1713 "auto|always|never",
1718 "Pretty-print the input instead of compiling;
1719 valid types are: `normal` (un-annotated source),
1720 `expanded` (crates expanded), or
1721 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
1727 "Specify which edition of the compiler to use when compiling code.",
1732 "remap-path-prefix",
1733 "Remap source names in all output (compiler messages and output files)",
1740 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
1741 pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> ast::CrateConfig {
1745 let sess = parse::ParseSess::new(FilePathMapping::empty());
1747 parse::new_parser_from_source_str(&sess, FileName::CfgSpec, s.to_string());
1749 let meta_item = panictry!(parser.parse_meta_item());
1751 if parser.token != token::Eof {
1753 ErrorOutputType::default(),
1754 &format!("invalid --cfg argument: {}", s),
1756 } else if meta_item.is_meta_item_list() {
1758 "invalid predicate in --cfg command line argument: `{}`",
1761 early_error(ErrorOutputType::default(), &msg)
1764 (meta_item.name(), meta_item.value_str())
1766 .collect::<ast::CrateConfig>()
1769 pub fn get_cmd_lint_options(matches: &getopts::Matches,
1770 error_format: ErrorOutputType)
1771 -> (Vec<(String, lint::Level)>, bool, Option<lint::Level>) {
1772 let mut lint_opts = vec![];
1773 let mut describe_lints = false;
1775 for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
1776 for lint_name in matches.opt_strs(level.as_str()) {
1777 if lint_name == "help" {
1778 describe_lints = true;
1780 lint_opts.push((lint_name.replace("-", "_"), level));
1785 let lint_cap = matches.opt_str("cap-lints").map(|cap| {
1786 lint::Level::from_str(&cap)
1787 .unwrap_or_else(|| early_error(error_format, &format!("unknown lint level: `{}`", cap)))
1789 (lint_opts, describe_lints, lint_cap)
1792 pub fn build_session_options_and_crate_config(
1793 matches: &getopts::Matches,
1794 ) -> (Options, ast::CrateConfig) {
1795 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
1796 Some("auto") => ColorConfig::Auto,
1797 Some("always") => ColorConfig::Always,
1798 Some("never") => ColorConfig::Never,
1800 None => ColorConfig::Auto,
1802 Some(arg) => early_error(
1803 ErrorOutputType::default(),
1805 "argument for --color must be auto, \
1806 always or never (instead was `{}`)",
1812 let edition = match matches.opt_str("edition") {
1813 Some(arg) => match Edition::from_str(&arg){
1814 Ok(edition) => edition,
1815 Err(_) => early_error(
1816 ErrorOutputType::default(),
1818 "argument for --edition must be one of: \
1819 {}. (instead was `{}`)",
1825 None => DEFAULT_EDITION,
1828 if !edition.is_stable() && !nightly_options::is_nightly_build() {
1830 ErrorOutputType::default(),
1832 "Edition {} is unstable and only \
1833 available for nightly builds of rustc.",
1840 // We need the opts_present check because the driver will send us Matches
1841 // with only stable options if no unstable options are used. Since error-format
1842 // is unstable, it will not be present. We have to use opts_present not
1843 // opt_present because the latter will panic.
1844 let error_format = if matches.opts_present(&["error-format".to_owned()]) {
1845 match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
1846 Some("human") => ErrorOutputType::HumanReadable(color),
1847 Some("json") => ErrorOutputType::Json(false),
1848 Some("pretty-json") => ErrorOutputType::Json(true),
1849 Some("short") => ErrorOutputType::Short(color),
1850 None => ErrorOutputType::HumanReadable(color),
1852 Some(arg) => early_error(
1853 ErrorOutputType::HumanReadable(color),
1855 "argument for --error-format must be `human`, `json` or \
1856 `short` (instead was `{}`)",
1862 ErrorOutputType::HumanReadable(color)
1865 let unparsed_crate_types = matches.opt_strs("crate-type");
1866 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
1867 .unwrap_or_else(|e| early_error(error_format, &e[..]));
1869 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
1871 let mut debugging_opts = build_debugging_options(matches, error_format);
1873 if !debugging_opts.unstable_options && error_format == ErrorOutputType::Json(true) {
1875 ErrorOutputType::Json(false),
1876 "--error-format=pretty-json is unstable",
1880 if debugging_opts.pgo_gen.is_some() && !debugging_opts.pgo_use.is_empty() {
1883 "options `-Z pgo-gen` and `-Z pgo-use` are exclusive",
1887 let mut output_types = BTreeMap::new();
1888 if !debugging_opts.parse_only {
1889 for list in matches.opt_strs("emit") {
1890 for output_type in list.split(',') {
1891 let mut parts = output_type.splitn(2, '=');
1892 let shorthand = parts.next().unwrap();
1893 let output_type = match OutputType::from_shorthand(shorthand) {
1894 Some(output_type) => output_type,
1895 None => early_error(
1898 "unknown emission type: `{}` - expected one of: {}",
1900 OutputType::shorthands_display(),
1904 let path = parts.next().map(PathBuf::from);
1905 output_types.insert(output_type, path);
1909 if output_types.is_empty() {
1910 output_types.insert(OutputType::Exe, None);
1913 let mut cg = build_codegen_options(matches, error_format);
1914 let mut codegen_units = cg.codegen_units;
1915 let mut disable_thinlto = false;
1917 // Issue #30063: if user requests llvm-related output to one
1918 // particular path, disable codegen-units.
1919 let incompatible: Vec<_> = output_types
1921 .map(|ot_path| ot_path.0)
1922 .filter(|ot| !ot.is_compatible_with_codegen_units_and_single_output_file())
1923 .map(|ot| ot.shorthand())
1925 if !incompatible.is_empty() {
1926 match codegen_units {
1927 Some(n) if n > 1 => {
1928 if matches.opt_present("o") {
1929 for ot in &incompatible {
1933 "--emit={} with -o incompatible with \
1934 -C codegen-units=N for N > 1",
1939 early_warn(error_format, "resetting to default -C codegen-units=1");
1940 codegen_units = Some(1);
1941 disable_thinlto = true;
1945 codegen_units = Some(1);
1946 disable_thinlto = true;
1951 if debugging_opts.query_threads == Some(0) {
1954 "Value for query threads must be a positive nonzero integer",
1958 if debugging_opts.query_threads.unwrap_or(1) > 1 && debugging_opts.fuel.is_some() {
1961 "Optimization fuel is incompatible with multiple query threads",
1965 if codegen_units == Some(0) {
1968 "Value for codegen units must be a positive nonzero integer",
1972 let incremental = match (&debugging_opts.incremental, &cg.incremental) {
1973 (&Some(ref path1), &Some(ref path2)) => {
1978 "conflicting paths for `-Z incremental` and \
1979 `-C incremental` specified: {} versus {}",
1987 (&Some(ref path), &None) => Some(path),
1988 (&None, &Some(ref path)) => Some(path),
1989 (&None, &None) => None,
1990 }.map(|m| PathBuf::from(m));
1992 if cg.lto != Lto::No && incremental.is_some() {
1995 "can't perform LTO when compiling incrementally",
1999 if debugging_opts.profile && incremental.is_some() {
2002 "can't instrument with gcov profiling when compiling incrementally",
2006 let mut prints = Vec::<PrintRequest>::new();
2007 if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
2008 prints.push(PrintRequest::TargetCPUs);
2009 cg.target_cpu = None;
2011 if cg.target_feature == "help" {
2012 prints.push(PrintRequest::TargetFeatures);
2013 cg.target_feature = "".to_string();
2015 if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
2016 prints.push(PrintRequest::RelocationModels);
2017 cg.relocation_model = None;
2019 if cg.code_model.as_ref().map_or(false, |s| s == "help") {
2020 prints.push(PrintRequest::CodeModels);
2021 cg.code_model = None;
2026 .map_or(false, |s| s == "help")
2028 prints.push(PrintRequest::TlsModels);
2029 debugging_opts.tls_model = None;
2034 let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
2035 let target_triple = if let Some(target) = matches.opt_str("target") {
2036 if target.ends_with(".json") {
2037 let path = Path::new(&target);
2038 match TargetTriple::from_path(&path) {
2039 Ok(triple) => triple,
2041 early_error(error_format, &format!("target file {:?} does not exist", path))
2045 TargetTriple::TargetTriple(target)
2048 TargetTriple::from_triple(host_triple())
2051 if matches.opt_present("O") {
2052 if cg.opt_level.is_some() {
2053 early_error(error_format, "-O and -C opt-level both provided");
2057 match cg.opt_level.as_ref().map(String::as_ref) {
2058 None => OptLevel::No,
2059 Some("0") => OptLevel::No,
2060 Some("1") => OptLevel::Less,
2061 Some("2") => OptLevel::Default,
2062 Some("3") => OptLevel::Aggressive,
2063 Some("s") => OptLevel::Size,
2064 Some("z") => OptLevel::SizeMin,
2069 "optimization level needs to be \
2070 between 0-3 (instead was `{}`)",
2078 let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
2079 let debuginfo = if matches.opt_present("g") {
2080 if cg.debuginfo.is_some() {
2081 early_error(error_format, "-g and -C debuginfo both provided");
2085 match cg.debuginfo {
2086 None | Some(0) => NoDebugInfo,
2087 Some(1) => LimitedDebugInfo,
2088 Some(2) => FullDebugInfo,
2093 "debug info level needs to be between \
2094 0-2 (instead was `{}`)",
2102 let mut search_paths = SearchPaths::new();
2103 for s in &matches.opt_strs("L") {
2104 search_paths.add_path(&s[..], error_format);
2111 // Parse string of the form "[KIND=]lib[:new_name]",
2112 // where KIND is one of "dylib", "framework", "static".
2113 let mut parts = s.splitn(2, '=');
2114 let kind = parts.next().unwrap();
2115 let (name, kind) = match (parts.next(), kind) {
2116 (None, name) => (name, None),
2117 (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
2118 (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
2119 (Some(name), "static") => (name, Some(cstore::NativeStatic)),
2120 (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
2125 "unknown library kind `{}`, expected \
2126 one of dylib, framework, or static",
2132 if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
2136 "the library kind 'static-nobundle' is only \
2137 accepted on the nightly compiler"
2141 let mut name_parts = name.splitn(2, ':');
2142 let name = name_parts.next().unwrap();
2143 let new_name = name_parts.next();
2144 (name.to_string(), new_name.map(|n| n.to_string()), kind)
2148 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
2149 let test = matches.opt_present("test");
2151 prints.extend(matches.opt_strs("print").into_iter().map(|s| match &*s {
2152 "crate-name" => PrintRequest::CrateName,
2153 "file-names" => PrintRequest::FileNames,
2154 "sysroot" => PrintRequest::Sysroot,
2155 "cfg" => PrintRequest::Cfg,
2156 "target-list" => PrintRequest::TargetList,
2157 "target-cpus" => PrintRequest::TargetCPUs,
2158 "target-features" => PrintRequest::TargetFeatures,
2159 "relocation-models" => PrintRequest::RelocationModels,
2160 "code-models" => PrintRequest::CodeModels,
2161 "tls-models" => PrintRequest::TlsModels,
2162 "native-static-libs" => PrintRequest::NativeStaticLibs,
2163 "target-spec-json" => {
2164 if nightly_options::is_unstable_enabled(matches) {
2165 PrintRequest::TargetSpec
2170 "the `-Z unstable-options` flag must also be passed to \
2171 enable the target-spec-json print option"
2176 req => early_error(error_format, &format!("unknown print request `{}`", req)),
2179 let borrowck_mode = match debugging_opts.borrowck.as_ref().map(|s| &s[..]) {
2180 None | Some("ast") => BorrowckMode::Ast,
2181 Some("mir") => BorrowckMode::Mir,
2182 Some("compare") => BorrowckMode::Compare,
2183 Some("migrate") => BorrowckMode::Migrate,
2184 Some(m) => early_error(error_format, &format!("unknown borrowck mode `{}`", m)),
2187 if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
2190 "-C remark will not show source locations without \
2195 let mut externs = BTreeMap::new();
2196 for arg in &matches.opt_strs("extern") {
2197 let mut parts = arg.splitn(2, '=');
2198 let name = match parts.next() {
2200 None => early_error(error_format, "--extern value must not be empty"),
2202 let location = match parts.next() {
2204 None => early_error(
2206 "--extern value must be of the format `foo=bar`",
2211 .entry(name.to_string())
2212 .or_insert_with(BTreeSet::new)
2213 .insert(location.to_string());
2216 let crate_name = matches.opt_str("crate-name");
2218 let remap_path_prefix = matches
2219 .opt_strs("remap-path-prefix")
2222 let mut parts = remap.rsplitn(2, '='); // reverse iterator
2223 let to = parts.next();
2224 let from = parts.next();
2226 (Some(from), Some(to)) => (PathBuf::from(from), PathBuf::from(to)),
2229 "--remap-path-prefix must contain '=' between FROM and TO",
2238 optimize: opt_level,
2243 output_types: OutputTypes(output_types),
2245 maybe_sysroot: sysroot_opt,
2254 externs: Externs(externs),
2258 unstable_features: UnstableFeatures::from_environment(),
2260 actually_rustdoc: false,
2261 cli_forced_codegen_units: codegen_units,
2262 cli_forced_thinlto_off: disable_thinlto,
2270 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
2271 let mut crate_types: Vec<CrateType> = Vec::new();
2272 for unparsed_crate_type in &list_list {
2273 for part in unparsed_crate_type.split(',') {
2274 let new_part = match part {
2275 "lib" => default_lib_output(),
2276 "rlib" => CrateTypeRlib,
2277 "staticlib" => CrateTypeStaticlib,
2278 "dylib" => CrateTypeDylib,
2279 "cdylib" => CrateTypeCdylib,
2280 "bin" => CrateTypeExecutable,
2281 "proc-macro" => CrateTypeProcMacro,
2283 return Err(format!("unknown crate type: `{}`", part));
2286 if !crate_types.contains(&new_part) {
2287 crate_types.push(new_part)
2295 pub mod nightly_options {
2297 use syntax::feature_gate::UnstableFeatures;
2298 use super::{ErrorOutputType, OptionStability, RustcOptGroup};
2299 use session::early_error;
2301 pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
2306 .any(|x| *x == "unstable-options")
2309 pub fn is_nightly_build() -> bool {
2310 UnstableFeatures::from_environment().is_nightly_build()
2313 pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
2314 let has_z_unstable_option = matches
2317 .any(|x| *x == "unstable-options");
2318 let really_allows_unstable_options =
2319 UnstableFeatures::from_environment().is_nightly_build();
2321 for opt in flags.iter() {
2322 if opt.stability == OptionStability::Stable {
2325 if !matches.opt_present(opt.name) {
2328 if opt.name != "Z" && !has_z_unstable_option {
2330 ErrorOutputType::default(),
2332 "the `-Z unstable-options` flag must also be passed to enable \
2338 if really_allows_unstable_options {
2341 match opt.stability {
2342 OptionStability::Unstable => {
2344 "the option `{}` is only accepted on the \
2348 early_error(ErrorOutputType::default(), &msg);
2350 OptionStability::Stable => {}
2356 impl fmt::Display for CrateType {
2357 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2359 CrateTypeExecutable => "bin".fmt(f),
2360 CrateTypeDylib => "dylib".fmt(f),
2361 CrateTypeRlib => "rlib".fmt(f),
2362 CrateTypeStaticlib => "staticlib".fmt(f),
2363 CrateTypeCdylib => "cdylib".fmt(f),
2364 CrateTypeProcMacro => "proc-macro".fmt(f),
2369 /// Commandline arguments passed to the compiler have to be incorporated with
2370 /// the dependency tracking system for incremental compilation. This module
2371 /// provides some utilities to make this more convenient.
2373 /// The values of all commandline arguments that are relevant for dependency
2374 /// tracking are hashed into a single value that determines whether the
2375 /// incremental compilation cache can be re-used or not. This hashing is done
2376 /// via the DepTrackingHash trait defined below, since the standard Hash
2377 /// implementation might not be suitable (e.g. arguments are stored in a Vec,
2378 /// the hash of which is order dependent, but we might not want the order of
2379 /// arguments to make a difference for the hash).
2381 /// However, since the value provided by Hash::hash often *is* suitable,
2382 /// especially for primitive types, there is the
2383 /// impl_dep_tracking_hash_via_hash!() macro that allows to simply reuse the
2384 /// Hash implementation for DepTrackingHash. It's important though that
2385 /// we have an opt-in scheme here, so one is hopefully forced to think about
2386 /// how the hash should be calculated when adding a new commandline argument.
2390 use std::collections::BTreeMap;
2391 use std::hash::Hash;
2392 use std::path::PathBuf;
2393 use std::collections::hash_map::DefaultHasher;
2394 use super::{CrateType, DebugInfoLevel, ErrorOutputType, Lto, OptLevel, OutputTypes,
2395 Passes, Sanitizer, CrossLangLto};
2396 use syntax::feature_gate::UnstableFeatures;
2397 use rustc_target::spec::{PanicStrategy, RelroLevel, TargetTriple};
2398 use syntax::edition::Edition;
2400 pub trait DepTrackingHash {
2401 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);
2404 macro_rules! impl_dep_tracking_hash_via_hash {
2406 impl DepTrackingHash for $t {
2407 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
2408 Hash::hash(self, hasher);
2414 macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
2416 impl DepTrackingHash for Vec<$t> {
2417 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2418 let mut elems: Vec<&$t> = self.iter().collect();
2420 Hash::hash(&elems.len(), hasher);
2421 for (index, elem) in elems.iter().enumerate() {
2422 Hash::hash(&index, hasher);
2423 DepTrackingHash::hash(*elem, hasher, error_format);
2430 impl_dep_tracking_hash_via_hash!(bool);
2431 impl_dep_tracking_hash_via_hash!(usize);
2432 impl_dep_tracking_hash_via_hash!(u64);
2433 impl_dep_tracking_hash_via_hash!(String);
2434 impl_dep_tracking_hash_via_hash!(PathBuf);
2435 impl_dep_tracking_hash_via_hash!(lint::Level);
2436 impl_dep_tracking_hash_via_hash!(Option<bool>);
2437 impl_dep_tracking_hash_via_hash!(Option<usize>);
2438 impl_dep_tracking_hash_via_hash!(Option<String>);
2439 impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
2440 impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
2441 impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
2442 impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
2443 impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
2444 impl_dep_tracking_hash_via_hash!(Option<cstore::NativeLibraryKind>);
2445 impl_dep_tracking_hash_via_hash!(CrateType);
2446 impl_dep_tracking_hash_via_hash!(PanicStrategy);
2447 impl_dep_tracking_hash_via_hash!(RelroLevel);
2448 impl_dep_tracking_hash_via_hash!(Passes);
2449 impl_dep_tracking_hash_via_hash!(OptLevel);
2450 impl_dep_tracking_hash_via_hash!(Lto);
2451 impl_dep_tracking_hash_via_hash!(DebugInfoLevel);
2452 impl_dep_tracking_hash_via_hash!(UnstableFeatures);
2453 impl_dep_tracking_hash_via_hash!(OutputTypes);
2454 impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
2455 impl_dep_tracking_hash_via_hash!(Sanitizer);
2456 impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
2457 impl_dep_tracking_hash_via_hash!(TargetTriple);
2458 impl_dep_tracking_hash_via_hash!(Edition);
2459 impl_dep_tracking_hash_via_hash!(CrossLangLto);
2461 impl_dep_tracking_hash_for_sortable_vec_of!(String);
2462 impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
2463 impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
2464 impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
2465 impl_dep_tracking_hash_for_sortable_vec_of!((
2468 Option<cstore::NativeLibraryKind>
2470 impl_dep_tracking_hash_for_sortable_vec_of!((String, u64));
2472 impl<T1, T2> DepTrackingHash for (T1, T2)
2474 T1: DepTrackingHash,
2475 T2: DepTrackingHash,
2477 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2478 Hash::hash(&0, hasher);
2479 DepTrackingHash::hash(&self.0, hasher, error_format);
2480 Hash::hash(&1, hasher);
2481 DepTrackingHash::hash(&self.1, hasher, error_format);
2485 impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
2487 T1: DepTrackingHash,
2488 T2: DepTrackingHash,
2489 T3: DepTrackingHash,
2491 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2492 Hash::hash(&0, hasher);
2493 DepTrackingHash::hash(&self.0, hasher, error_format);
2494 Hash::hash(&1, hasher);
2495 DepTrackingHash::hash(&self.1, hasher, error_format);
2496 Hash::hash(&2, hasher);
2497 DepTrackingHash::hash(&self.2, hasher, error_format);
2501 // This is a stable hash because BTreeMap is a sorted container
2503 sub_hashes: BTreeMap<&'static str, &dyn DepTrackingHash>,
2504 hasher: &mut DefaultHasher,
2505 error_format: ErrorOutputType,
2507 for (key, sub_hash) in sub_hashes {
2508 // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
2509 // the keys, as they are just plain strings
2510 Hash::hash(&key.len(), hasher);
2511 Hash::hash(key, hasher);
2512 sub_hash.hash(hasher, error_format);
2523 use session::config::{build_configuration, build_session_options_and_crate_config};
2524 use session::config::{Lto, CrossLangLto};
2525 use session::build_session;
2526 use std::collections::{BTreeMap, BTreeSet};
2527 use std::iter::FromIterator;
2528 use std::path::PathBuf;
2529 use super::{Externs, OutputType, OutputTypes};
2530 use rustc_target::spec::{PanicStrategy, RelroLevel};
2531 use syntax::symbol::Symbol;
2532 use syntax::edition::{Edition, DEFAULT_EDITION};
2535 fn optgroups() -> getopts::Options {
2536 let mut opts = getopts::Options::new();
2537 for group in super::rustc_optgroups() {
2538 (group.apply)(&mut opts);
2543 fn mk_map<K: Ord, V>(entries: Vec<(K, V)>) -> BTreeMap<K, V> {
2544 BTreeMap::from_iter(entries.into_iter())
2547 fn mk_set<V: Ord>(entries: Vec<V>) -> BTreeSet<V> {
2548 BTreeSet::from_iter(entries.into_iter())
2551 // When the user supplies --test we should implicitly supply --cfg test
2553 fn test_switch_implies_cfg_test() {
2554 syntax::with_globals(|| {
2555 let matches = &match optgroups().parse(&["--test".to_string()]) {
2557 Err(f) => panic!("test_switch_implies_cfg_test: {}", f),
2559 let registry = errors::registry::Registry::new(&[]);
2560 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2561 let sess = build_session(sessopts, None, registry);
2562 let cfg = build_configuration(&sess, cfg);
2563 assert!(cfg.contains(&(Symbol::intern("test"), None)));
2567 // When the user supplies --test and --cfg test, don't implicitly add
2568 // another --cfg test
2570 fn test_switch_implies_cfg_test_unless_cfg_test() {
2571 syntax::with_globals(|| {
2572 let matches = &match optgroups().parse(&["--test".to_string(),
2573 "--cfg=test".to_string()]) {
2575 Err(f) => panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f),
2577 let registry = errors::registry::Registry::new(&[]);
2578 let (sessopts, cfg) = build_session_options_and_crate_config(matches);
2579 let sess = build_session(sessopts, None, registry);
2580 let cfg = build_configuration(&sess, cfg);
2581 let mut test_items = cfg.iter().filter(|&&(name, _)| name == "test");
2582 assert!(test_items.next().is_some());
2583 assert!(test_items.next().is_none());
2588 fn test_can_print_warnings() {
2589 syntax::with_globals(|| {
2590 let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
2591 let registry = errors::registry::Registry::new(&[]);
2592 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2593 let sess = build_session(sessopts, None, registry);
2594 assert!(!sess.diagnostic().flags.can_emit_warnings);
2597 syntax::with_globals(|| {
2598 let matches = optgroups()
2599 .parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()])
2601 let registry = errors::registry::Registry::new(&[]);
2602 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2603 let sess = build_session(sessopts, None, registry);
2604 assert!(sess.diagnostic().flags.can_emit_warnings);
2607 syntax::with_globals(|| {
2608 let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
2609 let registry = errors::registry::Registry::new(&[]);
2610 let (sessopts, _) = build_session_options_and_crate_config(&matches);
2611 let sess = build_session(sessopts, None, registry);
2612 assert!(sess.diagnostic().flags.can_emit_warnings);
2617 fn test_output_types_tracking_hash_different_paths() {
2618 let mut v1 = super::basic_options();
2619 let mut v2 = super::basic_options();
2620 let mut v3 = super::basic_options();
2623 OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("./some/thing")))]);
2625 OutputTypes::new(&[(OutputType::Exe, Some(PathBuf::from("/some/thing")))]);
2626 v3.output_types = OutputTypes::new(&[(OutputType::Exe, None)]);
2628 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2629 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2630 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2633 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2634 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2635 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2639 fn test_output_types_tracking_hash_different_construction_order() {
2640 let mut v1 = super::basic_options();
2641 let mut v2 = super::basic_options();
2643 v1.output_types = OutputTypes::new(&[
2644 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2645 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2648 v2.output_types = OutputTypes::new(&[
2649 (OutputType::Bitcode, Some(PathBuf::from("./some/thing.bc"))),
2650 (OutputType::Exe, Some(PathBuf::from("./some/thing"))),
2653 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2656 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2660 fn test_externs_tracking_hash_different_construction_order() {
2661 let mut v1 = super::basic_options();
2662 let mut v2 = super::basic_options();
2663 let mut v3 = super::basic_options();
2665 v1.externs = Externs::new(mk_map(vec![
2668 mk_set(vec![String::from("b"), String::from("c")]),
2672 mk_set(vec![String::from("e"), String::from("f")]),
2676 v2.externs = Externs::new(mk_map(vec![
2679 mk_set(vec![String::from("e"), String::from("f")]),
2683 mk_set(vec![String::from("b"), String::from("c")]),
2687 v3.externs = Externs::new(mk_map(vec![
2690 mk_set(vec![String::from("b"), String::from("c")]),
2694 mk_set(vec![String::from("f"), String::from("e")]),
2698 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2699 assert_eq!(v1.dep_tracking_hash(), v3.dep_tracking_hash());
2700 assert_eq!(v2.dep_tracking_hash(), v3.dep_tracking_hash());
2703 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2704 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2705 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2709 fn test_lints_tracking_hash_different_values() {
2710 let mut v1 = super::basic_options();
2711 let mut v2 = super::basic_options();
2712 let mut v3 = super::basic_options();
2714 v1.lint_opts = vec![
2715 (String::from("a"), lint::Allow),
2716 (String::from("b"), lint::Warn),
2717 (String::from("c"), lint::Deny),
2718 (String::from("d"), lint::Forbid),
2721 v2.lint_opts = vec![
2722 (String::from("a"), lint::Allow),
2723 (String::from("b"), lint::Warn),
2724 (String::from("X"), lint::Deny),
2725 (String::from("d"), lint::Forbid),
2728 v3.lint_opts = vec![
2729 (String::from("a"), lint::Allow),
2730 (String::from("b"), lint::Warn),
2731 (String::from("c"), lint::Forbid),
2732 (String::from("d"), lint::Deny),
2735 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2736 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2737 assert!(v2.dep_tracking_hash() != v3.dep_tracking_hash());
2740 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2741 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2742 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2746 fn test_lints_tracking_hash_different_construction_order() {
2747 let mut v1 = super::basic_options();
2748 let mut v2 = super::basic_options();
2750 v1.lint_opts = vec![
2751 (String::from("a"), lint::Allow),
2752 (String::from("b"), lint::Warn),
2753 (String::from("c"), lint::Deny),
2754 (String::from("d"), lint::Forbid),
2757 v2.lint_opts = vec![
2758 (String::from("a"), lint::Allow),
2759 (String::from("c"), lint::Deny),
2760 (String::from("b"), lint::Warn),
2761 (String::from("d"), lint::Forbid),
2764 assert_eq!(v1.dep_tracking_hash(), v2.dep_tracking_hash());
2767 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2768 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2772 fn test_search_paths_tracking_hash_different_order() {
2773 let mut v1 = super::basic_options();
2774 let mut v2 = super::basic_options();
2775 let mut v3 = super::basic_options();
2776 let mut v4 = super::basic_options();
2780 .add_path("native=abc", super::ErrorOutputType::Json(false));
2782 .add_path("crate=def", super::ErrorOutputType::Json(false));
2784 .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2786 .add_path("framework=jkl", super::ErrorOutputType::Json(false));
2788 .add_path("all=mno", super::ErrorOutputType::Json(false));
2791 .add_path("native=abc", super::ErrorOutputType::Json(false));
2793 .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2795 .add_path("crate=def", super::ErrorOutputType::Json(false));
2797 .add_path("framework=jkl", super::ErrorOutputType::Json(false));
2799 .add_path("all=mno", super::ErrorOutputType::Json(false));
2802 .add_path("crate=def", super::ErrorOutputType::Json(false));
2804 .add_path("framework=jkl", super::ErrorOutputType::Json(false));
2806 .add_path("native=abc", super::ErrorOutputType::Json(false));
2808 .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2810 .add_path("all=mno", super::ErrorOutputType::Json(false));
2813 .add_path("all=mno", super::ErrorOutputType::Json(false));
2815 .add_path("native=abc", super::ErrorOutputType::Json(false));
2817 .add_path("crate=def", super::ErrorOutputType::Json(false));
2819 .add_path("dependency=ghi", super::ErrorOutputType::Json(false));
2821 .add_path("framework=jkl", super::ErrorOutputType::Json(false));
2823 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2824 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2825 assert!(v1.dep_tracking_hash() == v4.dep_tracking_hash());
2828 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2829 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2830 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2831 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2835 fn test_native_libs_tracking_hash_different_values() {
2836 let mut v1 = super::basic_options();
2837 let mut v2 = super::basic_options();
2838 let mut v3 = super::basic_options();
2839 let mut v4 = super::basic_options();
2843 (String::from("a"), None, Some(cstore::NativeStatic)),
2844 (String::from("b"), None, Some(cstore::NativeFramework)),
2845 (String::from("c"), None, Some(cstore::NativeUnknown)),
2850 (String::from("a"), None, Some(cstore::NativeStatic)),
2851 (String::from("X"), None, Some(cstore::NativeFramework)),
2852 (String::from("c"), None, Some(cstore::NativeUnknown)),
2857 (String::from("a"), None, Some(cstore::NativeStatic)),
2858 (String::from("b"), None, Some(cstore::NativeStatic)),
2859 (String::from("c"), None, Some(cstore::NativeUnknown)),
2864 (String::from("a"), None, Some(cstore::NativeStatic)),
2867 Some(String::from("X")),
2868 Some(cstore::NativeFramework),
2870 (String::from("c"), None, Some(cstore::NativeUnknown)),
2873 assert!(v1.dep_tracking_hash() != v2.dep_tracking_hash());
2874 assert!(v1.dep_tracking_hash() != v3.dep_tracking_hash());
2875 assert!(v1.dep_tracking_hash() != v4.dep_tracking_hash());
2878 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2879 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2880 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2881 assert_eq!(v4.dep_tracking_hash(), v4.clone().dep_tracking_hash());
2885 fn test_native_libs_tracking_hash_different_order() {
2886 let mut v1 = super::basic_options();
2887 let mut v2 = super::basic_options();
2888 let mut v3 = super::basic_options();
2892 (String::from("a"), None, Some(cstore::NativeStatic)),
2893 (String::from("b"), None, Some(cstore::NativeFramework)),
2894 (String::from("c"), None, Some(cstore::NativeUnknown)),
2898 (String::from("b"), None, Some(cstore::NativeFramework)),
2899 (String::from("a"), None, Some(cstore::NativeStatic)),
2900 (String::from("c"), None, Some(cstore::NativeUnknown)),
2904 (String::from("c"), None, Some(cstore::NativeUnknown)),
2905 (String::from("a"), None, Some(cstore::NativeStatic)),
2906 (String::from("b"), None, Some(cstore::NativeFramework)),
2909 assert!(v1.dep_tracking_hash() == v2.dep_tracking_hash());
2910 assert!(v1.dep_tracking_hash() == v3.dep_tracking_hash());
2911 assert!(v2.dep_tracking_hash() == v3.dep_tracking_hash());
2914 assert_eq!(v1.dep_tracking_hash(), v1.clone().dep_tracking_hash());
2915 assert_eq!(v2.dep_tracking_hash(), v2.clone().dep_tracking_hash());
2916 assert_eq!(v3.dep_tracking_hash(), v3.clone().dep_tracking_hash());
2920 fn test_codegen_options_tracking_hash() {
2921 let reference = super::basic_options();
2922 let mut opts = super::basic_options();
2924 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
2925 opts.cg.ar = Some(String::from("abc"));
2926 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2928 opts.cg.linker = Some(PathBuf::from("linker"));
2929 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2931 opts.cg.link_args = Some(vec![String::from("abc"), String::from("def")]);
2932 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2934 opts.cg.link_dead_code = true;
2935 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2937 opts.cg.rpath = true;
2938 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2940 opts.cg.extra_filename = String::from("extra-filename");
2941 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2943 opts.cg.codegen_units = Some(42);
2944 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2946 opts.cg.remark = super::SomePasses(vec![String::from("pass1"), String::from("pass2")]);
2947 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2949 opts.cg.save_temps = true;
2950 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2952 opts.cg.incremental = Some(String::from("abc"));
2953 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
2955 // Make sure changing a [TRACKED] option changes the hash
2956 opts = reference.clone();
2957 opts.cg.lto = Lto::Fat;
2958 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2960 opts = reference.clone();
2961 opts.cg.target_cpu = Some(String::from("abc"));
2962 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2964 opts = reference.clone();
2965 opts.cg.target_feature = String::from("all the features, all of them");
2966 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2968 opts = reference.clone();
2969 opts.cg.passes = vec![String::from("1"), String::from("2")];
2970 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2972 opts = reference.clone();
2973 opts.cg.llvm_args = vec![String::from("1"), String::from("2")];
2974 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2976 opts = reference.clone();
2977 opts.cg.overflow_checks = Some(true);
2978 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2980 opts = reference.clone();
2981 opts.cg.no_prepopulate_passes = true;
2982 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2984 opts = reference.clone();
2985 opts.cg.no_vectorize_loops = true;
2986 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2988 opts = reference.clone();
2989 opts.cg.no_vectorize_slp = true;
2990 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2992 opts = reference.clone();
2993 opts.cg.soft_float = true;
2994 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
2996 opts = reference.clone();
2997 opts.cg.prefer_dynamic = true;
2998 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3000 opts = reference.clone();
3001 opts.cg.no_integrated_as = true;
3002 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3004 opts = reference.clone();
3005 opts.cg.no_redzone = Some(true);
3006 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3008 opts = reference.clone();
3009 opts.cg.relocation_model = Some(String::from("relocation model"));
3010 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3012 opts = reference.clone();
3013 opts.cg.code_model = Some(String::from("code model"));
3014 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3016 opts = reference.clone();
3017 opts.debugging_opts.tls_model = Some(String::from("tls model"));
3018 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3020 opts = reference.clone();
3021 opts.debugging_opts.pgo_gen = Some(String::from("abc"));
3022 assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3024 opts = reference.clone();
3025 opts.debugging_opts.pgo_use = String::from("abc");
3026 assert_ne!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3028 opts = reference.clone();
3029 opts.cg.metadata = vec![String::from("A"), String::from("B")];
3030 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3032 opts = reference.clone();
3033 opts.cg.debuginfo = Some(0xdeadbeef);
3034 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3036 opts = reference.clone();
3037 opts.cg.debuginfo = Some(0xba5eba11);
3038 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3040 opts = reference.clone();
3041 opts.cg.force_frame_pointers = Some(false);
3042 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3044 opts = reference.clone();
3045 opts.cg.debug_assertions = Some(true);
3046 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3048 opts = reference.clone();
3049 opts.cg.inline_threshold = Some(0xf007ba11);
3050 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3052 opts = reference.clone();
3053 opts.cg.panic = Some(PanicStrategy::Abort);
3054 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3058 fn test_debugging_options_tracking_hash() {
3059 let reference = super::basic_options();
3060 let mut opts = super::basic_options();
3062 // Make sure the changing an [UNTRACKED] option leaves the hash unchanged
3063 opts.debugging_opts.verbose = true;
3064 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3065 opts.debugging_opts.time_passes = true;
3066 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3067 opts.debugging_opts.count_llvm_insns = true;
3068 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3069 opts.debugging_opts.time_llvm_passes = true;
3070 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3071 opts.debugging_opts.input_stats = true;
3072 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3073 opts.debugging_opts.codegen_stats = true;
3074 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3075 opts.debugging_opts.borrowck_stats = true;
3076 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3077 opts.debugging_opts.meta_stats = true;
3078 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3079 opts.debugging_opts.print_link_args = true;
3080 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3081 opts.debugging_opts.print_llvm_passes = true;
3082 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3083 opts.debugging_opts.ast_json = true;
3084 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3085 opts.debugging_opts.ast_json_noexpand = true;
3086 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3087 opts.debugging_opts.ls = true;
3088 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3089 opts.debugging_opts.save_analysis = true;
3090 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3091 opts.debugging_opts.flowgraph_print_loans = true;
3092 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3093 opts.debugging_opts.flowgraph_print_moves = true;
3094 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3095 opts.debugging_opts.flowgraph_print_assigns = true;
3096 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3097 opts.debugging_opts.flowgraph_print_all = true;
3098 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3099 opts.debugging_opts.print_region_graph = true;
3100 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3101 opts.debugging_opts.parse_only = true;
3102 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3103 opts.debugging_opts.incremental = Some(String::from("abc"));
3104 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3105 opts.debugging_opts.dump_dep_graph = true;
3106 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3107 opts.debugging_opts.query_dep_graph = true;
3108 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3109 opts.debugging_opts.no_analysis = true;
3110 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3111 opts.debugging_opts.unstable_options = true;
3112 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3113 opts.debugging_opts.trace_macros = true;
3114 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3115 opts.debugging_opts.keep_hygiene_data = true;
3116 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3117 opts.debugging_opts.keep_ast = true;
3118 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3119 opts.debugging_opts.print_mono_items = Some(String::from("abc"));
3120 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3121 opts.debugging_opts.dump_mir = Some(String::from("abc"));
3122 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3123 opts.debugging_opts.dump_mir_dir = String::from("abc");
3124 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3125 opts.debugging_opts.dump_mir_graphviz = true;
3126 assert_eq!(reference.dep_tracking_hash(), opts.dep_tracking_hash());
3128 // Make sure changing a [TRACKED] option changes the hash
3129 opts = reference.clone();
3130 opts.debugging_opts.asm_comments = true;
3131 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3133 opts = reference.clone();
3134 opts.debugging_opts.verify_llvm_ir = true;
3135 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3137 opts = reference.clone();
3138 opts.debugging_opts.no_landing_pads = true;
3139 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3141 opts = reference.clone();
3142 opts.debugging_opts.fewer_names = true;
3143 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3145 opts = reference.clone();
3146 opts.debugging_opts.no_codegen = true;
3147 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3149 opts = reference.clone();
3150 opts.debugging_opts.treat_err_as_bug = true;
3151 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3153 opts = reference.clone();
3154 opts.debugging_opts.report_delayed_bugs = true;
3155 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3157 opts = reference.clone();
3158 opts.debugging_opts.continue_parse_after_error = true;
3159 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3161 opts = reference.clone();
3162 opts.debugging_opts.extra_plugins = vec![String::from("plugin1"), String::from("plugin2")];
3163 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3165 opts = reference.clone();
3166 opts.debugging_opts.force_overflow_checks = Some(true);
3167 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3169 opts = reference.clone();
3170 opts.debugging_opts.show_span = Some(String::from("abc"));
3171 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3173 opts = reference.clone();
3174 opts.debugging_opts.mir_opt_level = 3;
3175 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3177 opts = reference.clone();
3178 opts.debugging_opts.relro_level = Some(RelroLevel::Full);
3179 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3181 opts = reference.clone();
3182 opts.debugging_opts.cross_lang_lto = CrossLangLto::LinkerPluginAuto;
3183 assert!(reference.dep_tracking_hash() != opts.dep_tracking_hash());
3187 fn test_edition_parsing() {
3188 // test default edition
3189 let options = super::basic_options();
3190 assert!(options.edition == DEFAULT_EDITION);
3192 let matches = optgroups()
3193 .parse(&["--edition=2018".to_string()])
3195 let (sessopts, _) = build_session_options_and_crate_config(&matches);
3196 assert!(sessopts.edition == Edition::Edition2018)