1 //! Contains infrastructure for configuring the compiler, including parsing
2 //! command-line options.
4 // ignore-tidy-filelength
7 use crate::middle::cstore;
8 use crate::session::{early_error, early_warn, Session};
9 use crate::session::search_paths::SearchPath;
10 use crate::hir::map as hir_map;
12 use rustc_data_structures::fx::FxHashSet;
14 use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
15 use rustc_target::spec::{Target, TargetTriple};
18 use syntax::ast::{self, IntTy, UintTy};
19 use syntax::source_map::{FileName, FilePathMapping};
20 use syntax::edition::{Edition, EDITION_NAME_LIST, DEFAULT_EDITION};
21 use syntax::symbol::{sym, Symbol};
22 use syntax::feature_gate::UnstableFeatures;
24 use errors::emitter::HumanReadableErrorType;
25 use errors::{ColorConfig, FatalError, Handler};
29 use std::collections::{BTreeMap, BTreeSet};
30 use std::collections::btree_map::{
31 Iter as BTreeMapIter, Keys as BTreeMapKeysIter, Values as BTreeMapValuesIter,
34 use std::str::{self, FromStr};
35 use std::hash::Hasher;
36 use std::collections::hash_map::DefaultHasher;
37 use std::iter::FromIterator;
38 use std::path::{Path, PathBuf};
46 #[derive(Clone, Hash, Debug)]
54 #[derive(Clone, Copy, Debug, PartialEq, Hash)]
64 impl_stable_hash_via_hash!(OptLevel);
66 /// This is what the `LtoCli` values get mapped to after resolving defaults and
67 /// and taking other command line options into account.
68 #[derive(Clone, PartialEq)]
70 /// Don't do any LTO whatsoever
73 /// Do a full crate graph LTO with ThinLTO
76 /// Do a local graph LTO with ThinLTO (only relevant for multiple codegen
80 /// Do a full crate graph LTO with "fat" LTO
84 /// The different settings that the `-C lto` flag can have.
85 #[derive(Clone, Copy, PartialEq, Hash, Debug)]
97 /// No `-C lto` flag passed
101 #[derive(Clone, PartialEq, Hash)]
102 pub enum LinkerPluginLto {
103 LinkerPlugin(PathBuf),
108 impl LinkerPluginLto {
109 pub fn enabled(&self) -> bool {
111 LinkerPluginLto::LinkerPlugin(_) |
112 LinkerPluginLto::LinkerPluginAuto => true,
113 LinkerPluginLto::Disabled => false,
118 #[derive(Clone, PartialEq, Hash)]
119 pub enum SwitchWithOptPath {
120 Enabled(Option<PathBuf>),
124 impl SwitchWithOptPath {
125 pub fn enabled(&self) -> bool {
127 SwitchWithOptPath::Enabled(_) => true,
128 SwitchWithOptPath::Disabled => false,
133 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
134 pub enum SymbolManglingVersion {
139 impl_stable_hash_via_hash!(SymbolManglingVersion);
141 #[derive(Clone, Copy, PartialEq, Hash)]
148 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord, RustcEncodable, RustcDecodable)]
149 pub enum OutputType {
160 impl_stable_hash_via_hash!(OutputType);
163 fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
165 OutputType::Exe | OutputType::DepInfo | OutputType::Metadata => true,
167 | OutputType::Assembly
168 | OutputType::LlvmAssembly
170 | OutputType::Object => false,
174 fn shorthand(&self) -> &'static str {
176 OutputType::Bitcode => "llvm-bc",
177 OutputType::Assembly => "asm",
178 OutputType::LlvmAssembly => "llvm-ir",
179 OutputType::Mir => "mir",
180 OutputType::Object => "obj",
181 OutputType::Metadata => "metadata",
182 OutputType::Exe => "link",
183 OutputType::DepInfo => "dep-info",
187 fn from_shorthand(shorthand: &str) -> Option<Self> {
188 Some(match shorthand {
189 "asm" => OutputType::Assembly,
190 "llvm-ir" => OutputType::LlvmAssembly,
191 "mir" => OutputType::Mir,
192 "llvm-bc" => OutputType::Bitcode,
193 "obj" => OutputType::Object,
194 "metadata" => OutputType::Metadata,
195 "link" => OutputType::Exe,
196 "dep-info" => OutputType::DepInfo,
201 fn shorthands_display() -> String {
203 "`{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`, `{}`",
204 OutputType::Bitcode.shorthand(),
205 OutputType::Assembly.shorthand(),
206 OutputType::LlvmAssembly.shorthand(),
207 OutputType::Mir.shorthand(),
208 OutputType::Object.shorthand(),
209 OutputType::Metadata.shorthand(),
210 OutputType::Exe.shorthand(),
211 OutputType::DepInfo.shorthand(),
215 pub fn extension(&self) -> &'static str {
217 OutputType::Bitcode => "bc",
218 OutputType::Assembly => "s",
219 OutputType::LlvmAssembly => "ll",
220 OutputType::Mir => "mir",
221 OutputType::Object => "o",
222 OutputType::Metadata => "rmeta",
223 OutputType::DepInfo => "d",
224 OutputType::Exe => "",
229 /// The type of diagnostics output to generate.
230 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
231 pub enum ErrorOutputType {
232 /// Output meant for the consumption of humans.
233 HumanReadable(HumanReadableErrorType),
234 /// Output that's consumed by other tools such as `rustfix` or the `RLS`.
236 /// Render the JSON in a human readable way (with indents and newlines).
238 /// The JSON output includes a `rendered` field that includes the rendered
240 json_rendered: HumanReadableErrorType,
244 impl Default for ErrorOutputType {
245 fn default() -> Self {
246 Self::HumanReadable(HumanReadableErrorType::Default(ColorConfig::Auto))
250 /// Use tree-based collections to cheaply get a deterministic `Hash` implementation.
251 /// *Do not* switch `BTreeMap` out for an unsorted container type! That would break
252 /// dependency tracking for command-line arguments.
253 #[derive(Clone, Hash)]
254 pub struct OutputTypes(BTreeMap<OutputType, Option<PathBuf>>);
256 impl_stable_hash_via_hash!(OutputTypes);
259 pub fn new(entries: &[(OutputType, Option<PathBuf>)]) -> OutputTypes {
260 OutputTypes(BTreeMap::from_iter(
261 entries.iter().map(|&(k, ref v)| (k, v.clone())),
265 pub fn get(&self, key: &OutputType) -> Option<&Option<PathBuf>> {
269 pub fn contains_key(&self, key: &OutputType) -> bool {
270 self.0.contains_key(key)
273 pub fn keys(&self) -> BTreeMapKeysIter<'_, OutputType, Option<PathBuf>> {
277 pub fn values(&self) -> BTreeMapValuesIter<'_, OutputType, Option<PathBuf>> {
281 pub fn len(&self) -> usize {
285 // Returns `true` if any of the output types require codegen or linking.
286 pub fn should_codegen(&self) -> bool {
287 self.0.keys().any(|k| match *k {
289 | OutputType::Assembly
290 | OutputType::LlvmAssembly
293 | OutputType::Exe => true,
294 OutputType::Metadata | OutputType::DepInfo => false,
299 /// Use tree-based collections to cheaply get a deterministic `Hash` implementation.
300 /// *Do not* switch `BTreeMap` or `BTreeSet` out for an unsorted container type! That
301 /// would break dependency tracking for command-line arguments.
303 pub struct Externs(BTreeMap<String, ExternEntry>);
305 #[derive(Clone, Debug, Default)]
306 pub struct ExternEntry {
307 pub locations: BTreeSet<Option<String>>,
308 pub is_private_dep: bool
312 pub fn new(data: BTreeMap<String, ExternEntry>) -> Externs {
316 pub fn get(&self, key: &str) -> Option<&ExternEntry> {
320 pub fn iter(&self) -> BTreeMapIter<'_, String, ExternEntry> {
326 macro_rules! hash_option {
327 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [UNTRACKED]) => ({});
328 ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({
329 if $sub_hashes.insert(stringify!($opt_name),
330 $opt_expr as &dyn dep_tracking::DepTrackingHash).is_some() {
331 bug!("duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
336 macro_rules! top_level_options {
337 (pub struct Options { $(
338 $opt:ident : $t:ty [$dep_tracking_marker:ident $($warn_val:expr, $warn_text:expr)*],
346 pub fn dep_tracking_hash(&self) -> u64 {
347 let mut sub_hashes = BTreeMap::new();
352 [$dep_tracking_marker $($warn_val,
354 self.error_format)*]);
356 let mut hasher = DefaultHasher::new();
357 dep_tracking::stable_hash(sub_hashes,
366 // The top-level command-line options struct.
368 // For each option, one has to specify how it behaves with regard to the
369 // dependency tracking system of incremental compilation. This is done via the
370 // square-bracketed directive after the field type. The options are:
373 // A change in the given field will cause the compiler to completely clear the
374 // incremental compilation cache before proceeding.
377 // Incremental compilation is not influenced by this option.
379 // If you add a new option to this struct or one of the sub-structs like
380 // `CodegenOptions`, think about how it influences incremental compilation. If in
381 // doubt, specify [TRACKED], which is always "correct" but might lead to
382 // unnecessary re-compilation.
385 // The crate config requested for the session, which may be combined
386 // with additional crate configurations during the compile process.
387 crate_types: Vec<CrateType> [TRACKED],
388 optimize: OptLevel [TRACKED],
389 // Include the `debug_assertions` flag in dependency tracking, since it
390 // can influence whether overflow checks are done or not.
391 debug_assertions: bool [TRACKED],
392 debuginfo: DebugInfo [TRACKED],
393 lint_opts: Vec<(String, lint::Level)> [TRACKED],
394 lint_cap: Option<lint::Level> [TRACKED],
395 describe_lints: bool [UNTRACKED],
396 output_types: OutputTypes [TRACKED],
397 search_paths: Vec<SearchPath> [UNTRACKED],
398 libs: Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> [TRACKED],
399 maybe_sysroot: Option<PathBuf> [UNTRACKED],
401 target_triple: TargetTriple [TRACKED],
403 test: bool [TRACKED],
404 error_format: ErrorOutputType [UNTRACKED],
406 // If `Some`, enable incremental compilation, using the given
407 // directory to store intermediate results.
408 incremental: Option<PathBuf> [UNTRACKED],
410 debugging_opts: DebuggingOptions [TRACKED],
411 prints: Vec<PrintRequest> [UNTRACKED],
412 // Determines which borrow checker(s) to run. This is the parsed, sanitized
413 // version of `debugging_opts.borrowck`, which is just a plain string.
414 borrowck_mode: BorrowckMode [UNTRACKED],
415 cg: CodegenOptions [TRACKED],
416 externs: Externs [UNTRACKED],
417 crate_name: Option<String> [TRACKED],
418 // An optional name to use as the crate for std during std injection,
419 // written `extern crate name as std`. Defaults to `std`. Used by
420 // out-of-tree drivers.
421 alt_std_name: Option<String> [TRACKED],
422 // Indicates how the compiler should treat unstable features.
423 unstable_features: UnstableFeatures [TRACKED],
425 // Indicates whether this run of the compiler is actually rustdoc. This
426 // is currently just a hack and will be removed eventually, so please
427 // try to not rely on this too much.
428 actually_rustdoc: bool [TRACKED],
430 // Specifications of codegen units / ThinLTO which are forced as a
431 // result of parsing command line options. These are not necessarily
432 // what rustc was invoked with, but massaged a bit to agree with
433 // commands like `--emit llvm-ir` which they're often incompatible with
434 // if we otherwise use the defaults of rustc.
435 cli_forced_codegen_units: Option<usize> [UNTRACKED],
436 cli_forced_thinlto_off: bool [UNTRACKED],
438 // Remap source path prefixes in all output (messages, object files, debug, etc.).
439 remap_path_prefix: Vec<(PathBuf, PathBuf)> [UNTRACKED],
441 edition: Edition [TRACKED],
443 // `true` if we're emitting JSON blobs about each artifact produced
445 json_artifact_notifications: bool [TRACKED],
447 pretty: Option<(PpMode, Option<UserIdentifiedItem>)> [UNTRACKED],
451 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
452 pub enum PrintRequest {
467 #[derive(Copy, Clone)]
468 pub enum BorrowckMode {
474 /// Returns whether we should run the MIR-based borrow check, but also fall back
475 /// on the AST borrow check if the MIR-based one errors.
476 pub fn migrate(self) -> bool {
478 BorrowckMode::Mir => false,
479 BorrowckMode::Migrate => true,
485 /// Load source code from a file.
487 /// Load source code from a string.
489 /// A string that is shown in place of a filename.
491 /// An anonymous string containing the source code.
497 pub fn filestem(&self) -> &str {
499 Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap(),
500 Input::Str { .. } => "rust_out",
504 pub fn get_input(&mut self) -> Option<&mut String> {
506 Input::File(_) => None,
507 Input::Str { ref mut input, .. } => Some(input),
511 pub fn source_name(&self) -> FileName {
513 Input::File(ref ifile) => ifile.clone().into(),
514 Input::Str { ref name, .. } => name.clone(),
519 #[derive(Clone, Hash)]
520 pub struct OutputFilenames {
521 pub out_directory: PathBuf,
522 pub out_filestem: String,
523 pub single_output_file: Option<PathBuf>,
525 pub outputs: OutputTypes,
528 impl_stable_hash_via_hash!(OutputFilenames);
530 pub const RUST_CGU_EXT: &str = "rcgu";
532 impl OutputFilenames {
533 pub fn path(&self, flavor: OutputType) -> PathBuf {
536 .and_then(|p| p.to_owned())
537 .or_else(|| self.single_output_file.clone())
538 .unwrap_or_else(|| self.temp_path(flavor, None))
541 /// Gets the path where a compilation artifact of the given type for the
542 /// given codegen unit should be placed on disk. If codegen_unit_name is
543 /// None, a path distinct from those of any codegen unit will be generated.
544 pub fn temp_path(&self, flavor: OutputType, codegen_unit_name: Option<&str>) -> PathBuf {
545 let extension = flavor.extension();
546 self.temp_path_ext(extension, codegen_unit_name)
549 /// Like temp_path, but also supports things where there is no corresponding
550 /// OutputType, like noopt-bitcode or lto-bitcode.
551 pub fn temp_path_ext(&self, ext: &str, codegen_unit_name: Option<&str>) -> PathBuf {
552 let base = self.out_directory.join(&self.filestem());
554 let mut extension = String::new();
556 if let Some(codegen_unit_name) = codegen_unit_name {
557 extension.push_str(codegen_unit_name);
561 if !extension.is_empty() {
562 extension.push_str(".");
563 extension.push_str(RUST_CGU_EXT);
564 extension.push_str(".");
567 extension.push_str(ext);
570 let path = base.with_extension(&extension[..]);
574 pub fn with_extension(&self, extension: &str) -> PathBuf {
576 .join(&self.filestem())
577 .with_extension(extension)
580 pub fn filestem(&self) -> String {
581 format!("{}{}", self.out_filestem, self.extra)
585 pub fn host_triple() -> &'static str {
586 // Get the host triple out of the build environment. This ensures that our
587 // idea of the host triple is the same as for the set of libraries we've
588 // actually built. We can't just take LLVM's host triple because they
589 // normalize all ix86 architectures to i386.
591 // Instead of grabbing the host triple (for the current host), we grab (at
592 // compile time) the target triple that this rustc is built with and
593 // calling that (at runtime) the host triple.
594 (option_env!("CFG_COMPILER_HOST_TRIPLE")).expect("CFG_COMPILER_HOST_TRIPLE")
597 impl Default for Options {
598 fn default() -> Options {
600 crate_types: Vec::new(),
601 optimize: OptLevel::No,
602 debuginfo: DebugInfo::None,
603 lint_opts: Vec::new(),
605 describe_lints: false,
606 output_types: OutputTypes(BTreeMap::new()),
607 search_paths: vec![],
609 target_triple: TargetTriple::from_triple(host_triple()),
612 debugging_opts: basic_debugging_options(),
614 borrowck_mode: BorrowckMode::Migrate,
615 cg: basic_codegen_options(),
616 error_format: ErrorOutputType::default(),
617 externs: Externs(BTreeMap::new()),
621 unstable_features: UnstableFeatures::Disallow,
622 debug_assertions: true,
623 actually_rustdoc: false,
624 cli_forced_codegen_units: None,
625 cli_forced_thinlto_off: false,
626 remap_path_prefix: Vec::new(),
627 edition: DEFAULT_EDITION,
628 json_artifact_notifications: false,
635 /// Returns `true` if there is a reason to build the dep graph.
636 pub fn build_dep_graph(&self) -> bool {
637 self.incremental.is_some() || self.debugging_opts.dump_dep_graph
638 || self.debugging_opts.query_dep_graph
642 pub fn enable_dep_node_debug_strs(&self) -> bool {
643 cfg!(debug_assertions)
644 && (self.debugging_opts.query_dep_graph || self.debugging_opts.incremental_info)
647 pub fn file_path_mapping(&self) -> FilePathMapping {
648 FilePathMapping::new(self.remap_path_prefix.clone())
651 /// Returns `true` if there will be an output file generated.
652 pub fn will_create_output_file(&self) -> bool {
653 !self.debugging_opts.parse_only && // The file is just being parsed
654 !self.debugging_opts.ls // The file is just being queried
658 pub fn share_generics(&self) -> bool {
659 match self.debugging_opts.share_generics {
660 Some(setting) => setting,
662 match self.optimize {
666 OptLevel::SizeMin => true,
668 OptLevel::Aggressive => false,
675 // The type of entry function, so users can have their own entry functions
676 #[derive(Copy, Clone, PartialEq, Hash, Debug)]
677 pub enum EntryFnType {
682 impl_stable_hash_via_hash!(EntryFnType);
684 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug, HashStable)]
694 #[derive(Clone, Hash)]
701 pub fn is_empty(&self) -> bool {
703 Passes::Some(ref v) => v.is_empty(),
704 Passes::All => false,
709 /// Defines all `CodegenOptions`/`DebuggingOptions` fields and parsers all at once. The goal of this
710 /// macro is to define an interface that can be programmatically used by the option parser
711 /// to initialize the struct without hardcoding field names all over the place.
713 /// The goal is to invoke this macro once with the correct fields, and then this macro generates all
714 /// necessary code. The main gotcha of this macro is the `cgsetters` module which is a bunch of
715 /// generated code to parse an option into its respective field in the struct. There are a few
716 /// hand-written parsers for parsing specific types of values in this module.
717 macro_rules! options {
718 ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
719 $buildfn:ident, $prefix:expr, $outputname:expr,
720 $stat:ident, $mod_desc:ident, $mod_set:ident,
721 $($opt:ident : $t:ty = (
724 [$dep_tracking_marker:ident $(($dep_warn_val:expr, $dep_warn_text:expr))*],
729 pub struct $struct_name { $(pub $opt: $t),* }
731 pub fn $defaultfn() -> $struct_name {
732 $struct_name { $($opt: $init),* }
735 pub fn $buildfn(matches: &getopts::Matches, error_format: ErrorOutputType) -> $struct_name
737 let mut op = $defaultfn();
738 for option in matches.opt_strs($prefix) {
739 let mut iter = option.splitn(2, '=');
740 let key = iter.next().unwrap();
741 let value = iter.next();
742 let option_to_lookup = key.replace("-", "_");
743 let mut found = false;
744 for &(candidate, setter, opt_type_desc, _) in $stat {
745 if option_to_lookup != candidate { continue }
746 if !setter(&mut op, value) {
747 match (value, opt_type_desc) {
748 (Some(..), None) => {
749 early_error(error_format, &format!("{} option `{}` takes no \
750 value", $outputname, key))
752 (None, Some(type_desc)) => {
753 early_error(error_format, &format!("{0} option `{1}` requires \
754 {2} ({3} {1}=<value>)",
758 (Some(value), Some(type_desc)) => {
759 early_error(error_format, &format!("incorrect value `{}` for {} \
760 option `{}` - {} was expected",
764 (None, None) => bug!()
771 early_error(error_format, &format!("unknown {} option: `{}`",
778 impl dep_tracking::DepTrackingHash for $struct_name {
779 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
780 let mut sub_hashes = BTreeMap::new();
785 [$dep_tracking_marker $($dep_warn_val,
789 dep_tracking::stable_hash(sub_hashes, hasher, error_format);
793 pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
794 pub const $stat: &[(&str, $setter_name, Option<&str>, &str)] =
795 &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
797 #[allow(non_upper_case_globals, dead_code)]
799 pub const parse_bool: Option<&str> = None;
800 pub const parse_opt_bool: Option<&str> =
801 Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
802 pub const parse_string: Option<&str> = Some("a string");
803 pub const parse_string_push: Option<&str> = Some("a string");
804 pub const parse_pathbuf_push: Option<&str> = Some("a path");
805 pub const parse_opt_string: Option<&str> = Some("a string");
806 pub const parse_opt_pathbuf: Option<&str> = Some("a path");
807 pub const parse_list: Option<&str> = Some("a space-separated list of strings");
808 pub const parse_opt_list: Option<&str> = Some("a space-separated list of strings");
809 pub const parse_opt_comma_list: Option<&str> = Some("a comma-separated list of strings");
810 pub const parse_threads: Option<&str> = Some("a number");
811 pub const parse_uint: Option<&str> = Some("a number");
812 pub const parse_passes: Option<&str> =
813 Some("a space-separated list of passes, or `all`");
814 pub const parse_opt_uint: Option<&str> =
816 pub const parse_panic_strategy: Option<&str> =
817 Some("either `unwind` or `abort`");
818 pub const parse_relro_level: Option<&str> =
819 Some("one of: `full`, `partial`, or `off`");
820 pub const parse_sanitizer: Option<&str> =
821 Some("one of: `address`, `leak`, `memory` or `thread`");
822 pub const parse_linker_flavor: Option<&str> =
823 Some(::rustc_target::spec::LinkerFlavor::one_of());
824 pub const parse_optimization_fuel: Option<&str> =
825 Some("crate=integer");
826 pub const parse_unpretty: Option<&str> =
827 Some("`string` or `string=string`");
828 pub const parse_treat_err_as_bug: Option<&str> =
829 Some("either no value or a number bigger than 0");
830 pub const parse_lto: Option<&str> =
831 Some("either a boolean (`yes`, `no`, `on`, `off`, etc), `thin`, \
833 pub const parse_linker_plugin_lto: Option<&str> =
834 Some("either a boolean (`yes`, `no`, `on`, `off`, etc), \
835 or the path to the linker plugin");
836 pub const parse_switch_with_opt_path: Option<&str> =
837 Some("an optional path to the profiling data output directory");
838 pub const parse_merge_functions: Option<&str> =
839 Some("one of: `disabled`, `trampolines`, or `aliases`");
840 pub const parse_symbol_mangling_version: Option<&str> =
841 Some("either `legacy` or `v0` (RFC 2603)");
846 use super::{$struct_name, Passes, Sanitizer, LtoCli, LinkerPluginLto, SwitchWithOptPath,
847 SymbolManglingVersion};
848 use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
849 use std::path::PathBuf;
850 use std::str::FromStr;
853 pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
854 $parse(&mut cg.$opt, v)
858 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
861 None => { *slot = true; true }
865 fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
869 "n" | "no" | "off" => {
872 "y" | "yes" | "on" => {
875 _ => { return false; }
880 None => { *slot = Some(true); true }
884 fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
886 Some(s) => { *slot = Some(s.to_string()); true },
891 fn parse_opt_pathbuf(slot: &mut Option<PathBuf>, v: Option<&str>) -> bool {
893 Some(s) => { *slot = Some(PathBuf::from(s)); true },
898 fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
900 Some(s) => { *slot = s.to_string(); true },
905 fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
907 Some(s) => { slot.push(s.to_string()); true },
912 fn parse_pathbuf_push(slot: &mut Vec<PathBuf>, v: Option<&str>) -> bool {
914 Some(s) => { slot.push(PathBuf::from(s)); true },
919 fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
923 slot.extend(s.split_whitespace().map(|s| s.to_string()));
930 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
934 let v = s.split_whitespace().map(|s| s.to_string()).collect();
942 fn parse_opt_comma_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
946 let v = s.split(',').map(|s| s.to_string()).collect();
954 fn parse_threads(slot: &mut usize, v: Option<&str>) -> bool {
955 match v.and_then(|s| s.parse().ok()) {
956 Some(0) => { *slot = ::num_cpus::get(); true },
957 Some(i) => { *slot = i; true },
962 fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
963 match v.and_then(|s| s.parse().ok()) {
964 Some(i) => { *slot = i; true },
969 fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
971 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
972 None => { *slot = None; false }
976 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
983 let mut passes = vec![];
984 if parse_list(&mut passes, v) {
985 *slot = Passes::Some(passes);
994 fn parse_panic_strategy(slot: &mut Option<PanicStrategy>, v: Option<&str>) -> bool {
996 Some("unwind") => *slot = Some(PanicStrategy::Unwind),
997 Some("abort") => *slot = Some(PanicStrategy::Abort),
1003 fn parse_relro_level(slot: &mut Option<RelroLevel>, v: Option<&str>) -> bool {
1006 match s.parse::<RelroLevel>() {
1007 Ok(level) => *slot = Some(level),
1016 fn parse_sanitizer(slote: &mut Option<Sanitizer>, v: Option<&str>) -> bool {
1018 Some("address") => *slote = Some(Sanitizer::Address),
1019 Some("leak") => *slote = Some(Sanitizer::Leak),
1020 Some("memory") => *slote = Some(Sanitizer::Memory),
1021 Some("thread") => *slote = Some(Sanitizer::Thread),
1027 fn parse_linker_flavor(slote: &mut Option<LinkerFlavor>, v: Option<&str>) -> bool {
1028 match v.and_then(LinkerFlavor::from_str) {
1029 Some(lf) => *slote = Some(lf),
1035 fn parse_optimization_fuel(slot: &mut Option<(String, u64)>, v: Option<&str>) -> bool {
1039 let parts = s.split('=').collect::<Vec<_>>();
1040 if parts.len() != 2 { return false; }
1041 let crate_name = parts[0].to_string();
1042 let fuel = parts[1].parse::<u64>();
1043 if fuel.is_err() { return false; }
1044 *slot = Some((crate_name, fuel.unwrap()));
1050 fn parse_unpretty(slot: &mut Option<String>, v: Option<&str>) -> bool {
1053 Some(s) if s.split('=').count() <= 2 => {
1054 *slot = Some(s.to_string());
1061 fn parse_treat_err_as_bug(slot: &mut Option<usize>, v: Option<&str>) -> bool {
1063 Some(s) => { *slot = s.parse().ok().filter(|&x| x != 0); slot.unwrap_or(0) != 0 }
1064 None => { *slot = Some(1); true }
1068 fn parse_lto(slot: &mut LtoCli, v: Option<&str>) -> bool {
1070 let mut bool_arg = None;
1071 if parse_opt_bool(&mut bool_arg, v) {
1072 *slot = if bool_arg.unwrap() {
1082 None => LtoCli::NoParam,
1083 Some("thin") => LtoCli::Thin,
1084 Some("fat") => LtoCli::Fat,
1085 Some(_) => return false,
1090 fn parse_linker_plugin_lto(slot: &mut LinkerPluginLto, v: Option<&str>) -> bool {
1092 let mut bool_arg = None;
1093 if parse_opt_bool(&mut bool_arg, v) {
1094 *slot = if bool_arg.unwrap() {
1095 LinkerPluginLto::LinkerPluginAuto
1097 LinkerPluginLto::Disabled
1104 None => LinkerPluginLto::LinkerPluginAuto,
1105 Some(path) => LinkerPluginLto::LinkerPlugin(PathBuf::from(path)),
1110 fn parse_switch_with_opt_path(slot: &mut SwitchWithOptPath, v: Option<&str>) -> bool {
1112 None => SwitchWithOptPath::Enabled(None),
1113 Some(path) => SwitchWithOptPath::Enabled(Some(PathBuf::from(path))),
1118 fn parse_merge_functions(slot: &mut Option<MergeFunctions>, v: Option<&str>) -> bool {
1119 match v.and_then(|s| MergeFunctions::from_str(s).ok()) {
1120 Some(mergefunc) => *slot = Some(mergefunc),
1126 fn parse_symbol_mangling_version(
1127 slot: &mut SymbolManglingVersion,
1131 Some("legacy") => SymbolManglingVersion::Legacy,
1132 Some("v0") => SymbolManglingVersion::V0,
1140 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
1141 build_codegen_options, "C", "codegen",
1142 CG_OPTIONS, cg_type_desc, cgsetters,
1143 ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
1144 "this option is deprecated and does nothing"),
1145 linker: Option<PathBuf> = (None, parse_opt_pathbuf, [UNTRACKED],
1146 "system linker to link outputs with"),
1147 link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1148 "a single extra argument to append to the linker invocation (can be used several times)"),
1149 link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1150 "extra arguments to append to the linker invocation (space separated)"),
1151 link_dead_code: bool = (false, parse_bool, [UNTRACKED],
1152 "don't let linker strip dead code (turning it on can be used for code coverage)"),
1153 lto: LtoCli = (LtoCli::Unspecified, parse_lto, [TRACKED],
1154 "perform LLVM link-time optimizations"),
1155 target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
1156 "select target processor (`rustc --print target-cpus` for details)"),
1157 target_feature: String = (String::new(), parse_string, [TRACKED],
1158 "target specific attributes. (`rustc --print target-features` for details). \
1159 This feature is unsafe."),
1160 passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1161 "a list of extra LLVM passes to run (space separated)"),
1162 llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1163 "a list of arguments to pass to LLVM (space separated)"),
1164 save_temps: bool = (false, parse_bool, [UNTRACKED],
1165 "save all temporary output files during compilation"),
1166 rpath: bool = (false, parse_bool, [UNTRACKED],
1167 "set rpath values in libs/exes"),
1168 overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1169 "use overflow checks for integer arithmetic"),
1170 no_prepopulate_passes: bool = (false, parse_bool, [TRACKED],
1171 "don't pre-populate the pass manager with a list of passes"),
1172 no_vectorize_loops: bool = (false, parse_bool, [TRACKED],
1173 "don't run the loop vectorization optimization passes"),
1174 no_vectorize_slp: bool = (false, parse_bool, [TRACKED],
1175 "don't run LLVM's SLP vectorization pass"),
1176 soft_float: bool = (false, parse_bool, [TRACKED],
1177 "use soft float ABI (*eabihf targets only)"),
1178 prefer_dynamic: bool = (false, parse_bool, [TRACKED],
1179 "prefer dynamic linking to static linking"),
1180 no_integrated_as: bool = (false, parse_bool, [TRACKED],
1181 "use an external assembler rather than LLVM's integrated one"),
1182 no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
1183 "disable the use of the redzone"),
1184 relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
1185 "choose the relocation model to use (`rustc --print relocation-models` for details)"),
1186 code_model: Option<String> = (None, parse_opt_string, [TRACKED],
1187 "choose the code model to use (`rustc --print code-models` for details)"),
1188 metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1189 "metadata to mangle symbol names with"),
1190 extra_filename: String = (String::new(), parse_string, [UNTRACKED],
1191 "extra data to put in each output filename"),
1192 codegen_units: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1193 "divide crate into N units to optimize in parallel"),
1194 remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
1195 "print remarks for these optimization passes (space separated, or \"all\")"),
1196 no_stack_check: bool = (false, parse_bool, [UNTRACKED],
1197 "the `--no-stack-check` flag is deprecated and does nothing"),
1198 debuginfo: Option<usize> = (None, parse_opt_uint, [TRACKED],
1199 "debug info emission level, 0 = no debug info, 1 = line tables only, \
1200 2 = full debug info with variable and type information"),
1201 opt_level: Option<String> = (None, parse_opt_string, [TRACKED],
1202 "optimize with possible levels 0-3, s, or z"),
1203 force_frame_pointers: Option<bool> = (None, parse_opt_bool, [TRACKED],
1204 "force use of the frame pointers"),
1205 debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
1206 "explicitly enable the cfg(debug_assertions) directive"),
1207 inline_threshold: Option<usize> = (None, parse_opt_uint, [TRACKED],
1208 "set the threshold for inlining a function (default: 225)"),
1209 panic: Option<PanicStrategy> = (None, parse_panic_strategy,
1210 [TRACKED], "panic strategy to compile crate with"),
1211 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1212 "enable incremental compilation"),
1213 default_linker_libraries: Option<bool> = (None, parse_opt_bool, [UNTRACKED],
1214 "allow the linker to link its default libraries"),
1215 linker_flavor: Option<LinkerFlavor> = (None, parse_linker_flavor, [UNTRACKED],
1217 linker_plugin_lto: LinkerPluginLto = (LinkerPluginLto::Disabled,
1218 parse_linker_plugin_lto, [TRACKED],
1219 "generate build artifacts that are compatible with linker-based LTO."),
1220 profile_generate: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
1221 parse_switch_with_opt_path, [TRACKED],
1222 "compile the program with profiling instrumentation"),
1223 profile_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
1224 "use the given `.profdata` file for profile-guided optimization"),
1227 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
1228 build_debugging_options, "Z", "debugging",
1229 DB_OPTIONS, db_type_desc, dbsetters,
1230 codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
1231 "the backend to use"),
1232 verbose: bool = (false, parse_bool, [UNTRACKED],
1233 "in general, enable more debug printouts"),
1234 span_free_formats: bool = (false, parse_bool, [UNTRACKED],
1235 "when debug-printing compiler state, do not include spans"), // o/w tests have closure@path
1236 identify_regions: bool = (false, parse_bool, [UNTRACKED],
1237 "make unnamed regions display as '# (where # is some non-ident unique id)"),
1238 borrowck: Option<String> = (None, parse_opt_string, [UNTRACKED],
1239 "select which borrowck is used (`mir` or `migrate`)"),
1240 time_passes: bool = (false, parse_bool, [UNTRACKED],
1241 "measure time of each rustc pass"),
1242 time: bool = (false, parse_bool, [UNTRACKED],
1243 "measure time of rustc processes"),
1244 time_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1245 "measure time of each LLVM pass"),
1246 input_stats: bool = (false, parse_bool, [UNTRACKED],
1247 "gather statistics about the input"),
1248 asm_comments: bool = (false, parse_bool, [TRACKED],
1249 "generate comments into the assembly (may change behavior)"),
1250 verify_llvm_ir: bool = (false, parse_bool, [TRACKED],
1252 borrowck_stats: bool = (false, parse_bool, [UNTRACKED],
1253 "gather borrowck statistics"),
1254 no_landing_pads: bool = (false, parse_bool, [TRACKED],
1255 "omit landing pads for unwinding"),
1256 fewer_names: bool = (false, parse_bool, [TRACKED],
1257 "reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR)"),
1258 meta_stats: bool = (false, parse_bool, [UNTRACKED],
1259 "gather metadata statistics"),
1260 print_link_args: bool = (false, parse_bool, [UNTRACKED],
1261 "print the arguments passed to the linker"),
1262 print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
1263 "prints the LLVM optimization passes being run"),
1264 ast_json: bool = (false, parse_bool, [UNTRACKED],
1265 "print the AST as JSON and halt"),
1266 // We default to 1 here since we want to behave like
1267 // a sequential compiler for now. This'll likely be adjusted
1268 // in the future. Note that -Zthreads=0 is the way to get
1269 // the num_cpus behavior.
1270 threads: usize = (1, parse_threads, [UNTRACKED],
1271 "use a thread pool with N threads"),
1272 ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
1273 "print the pre-expansion AST as JSON and halt"),
1274 ls: bool = (false, parse_bool, [UNTRACKED],
1275 "list the symbols defined by a library crate"),
1276 save_analysis: bool = (false, parse_bool, [UNTRACKED],
1277 "write syntax and type analysis (in JSON format) information, in \
1278 addition to normal output"),
1279 print_region_graph: bool = (false, parse_bool, [UNTRACKED],
1280 "prints region inference graph. \
1281 Use with RUST_REGION_GRAPH=help for more info"),
1282 parse_only: bool = (false, parse_bool, [UNTRACKED],
1283 "parse only; do not compile, assemble, or link"),
1284 dual_proc_macros: bool = (false, parse_bool, [TRACKED],
1285 "load proc macros for both target and host, but only link to the target"),
1286 no_codegen: bool = (false, parse_bool, [TRACKED],
1287 "run all passes except codegen; no output"),
1288 treat_err_as_bug: Option<usize> = (None, parse_treat_err_as_bug, [TRACKED],
1289 "treat error number `val` that occurs as bug"),
1290 report_delayed_bugs: bool = (false, parse_bool, [TRACKED],
1291 "immediately print bugs registered with `delay_span_bug`"),
1292 external_macro_backtrace: bool = (false, parse_bool, [UNTRACKED],
1293 "show macro backtraces even for non-local macros"),
1294 teach: bool = (false, parse_bool, [TRACKED],
1295 "show extended diagnostic help"),
1296 terminal_width: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
1297 "set the current terminal width"),
1298 panic_abort_tests: bool = (false, parse_bool, [TRACKED],
1299 "support compiling tests with panic=abort"),
1300 continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
1301 "attempt to recover from parse errors (experimental)"),
1302 dep_tasks: bool = (false, parse_bool, [UNTRACKED],
1303 "print tasks that execute and the color their dep node gets (requires debug build)"),
1304 incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
1305 "enable incremental compilation (experimental)"),
1306 incremental_queries: bool = (true, parse_bool, [UNTRACKED],
1307 "enable incremental compilation support for queries (experimental)"),
1308 incremental_info: bool = (false, parse_bool, [UNTRACKED],
1309 "print high-level information about incremental reuse (or the lack thereof)"),
1310 incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
1311 "dump hash information in textual format to stdout"),
1312 incremental_verify_ich: bool = (false, parse_bool, [UNTRACKED],
1313 "verify incr. comp. hashes of green query instances"),
1314 incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED],
1315 "ignore spans during ICH computation -- used for testing"),
1316 instrument_mcount: bool = (false, parse_bool, [TRACKED],
1317 "insert function instrument code for mcount-based tracing"),
1318 dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1319 "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
1320 query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
1321 "enable queries of the dependency graph for regression testing"),
1322 no_analysis: bool = (false, parse_bool, [UNTRACKED],
1323 "parse and expand the source, but run no analysis"),
1324 extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
1325 "load extra plugins"),
1326 unstable_options: bool = (false, parse_bool, [UNTRACKED],
1327 "adds unstable command line options to rustc interface"),
1328 force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
1329 "force overflow checks on or off"),
1330 trace_macros: bool = (false, parse_bool, [UNTRACKED],
1331 "for every macro invocation, print its name and arguments"),
1332 debug_macros: bool = (false, parse_bool, [TRACKED],
1333 "emit line numbers debug info inside macros"),
1334 keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
1335 "don't clear the hygiene data after analysis"),
1336 keep_ast: bool = (false, parse_bool, [UNTRACKED],
1337 "keep the AST after lowering it to HIR"),
1338 show_span: Option<String> = (None, parse_opt_string, [TRACKED],
1339 "show spans for compiler debugging (expr|pat|ty)"),
1340 print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
1341 "print layout information for each type encountered"),
1342 print_mono_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
1343 "print the result of the monomorphization collection pass"),
1344 mir_opt_level: usize = (1, parse_uint, [TRACKED],
1345 "set the MIR optimization level (0-3, default: 1)"),
1346 mutable_noalias: Option<bool> = (None, parse_opt_bool, [TRACKED],
1347 "emit noalias metadata for mutable references (default: no)"),
1348 dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
1349 "dump MIR state to file.
1350 `val` is used to select which passes and functions to dump. For example:
1351 `all` matches all passes and functions,
1352 `foo` matches all passes for functions whose name contains 'foo',
1353 `foo & ConstProp` only the 'ConstProp' pass for function names containing 'foo',
1354 `foo | bar` all passes for function names containing 'foo' or 'bar'."),
1356 dump_mir_dir: String = (String::from("mir_dump"), parse_string, [UNTRACKED],
1357 "the directory the MIR is dumped into"),
1358 dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED],
1359 "in addition to `.mir` files, create graphviz `.dot` files"),
1360 dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED],
1361 "if set, exclude the pass number when dumping MIR (used in tests)"),
1362 mir_emit_retag: bool = (false, parse_bool, [TRACKED],
1363 "emit Retagging MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0"),
1364 perf_stats: bool = (false, parse_bool, [UNTRACKED],
1365 "print some performance-related statistics"),
1366 query_stats: bool = (false, parse_bool, [UNTRACKED],
1367 "print some statistics about the query system"),
1368 hir_stats: bool = (false, parse_bool, [UNTRACKED],
1369 "print some statistics about AST and HIR"),
1370 always_encode_mir: bool = (false, parse_bool, [TRACKED],
1371 "encode MIR of all functions into the crate metadata"),
1372 json_rendered: Option<String> = (None, parse_opt_string, [UNTRACKED],
1373 "describes how to render the `rendered` field of json diagnostics"),
1374 unleash_the_miri_inside_of_you: bool = (false, parse_bool, [TRACKED],
1375 "take the breaks off const evaluation. NOTE: this is unsound"),
1376 osx_rpath_install_name: bool = (false, parse_bool, [TRACKED],
1377 "pass `-install_name @rpath/...` to the macOS linker"),
1378 sanitizer: Option<Sanitizer> = (None, parse_sanitizer, [TRACKED],
1380 fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED],
1381 "set the optimization fuel quota for a crate"),
1382 print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
1383 "make rustc print the total optimization fuel used by a crate"),
1384 force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED],
1385 "force all crates to be `rustc_private` unstable"),
1386 pre_link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
1387 "a single extra argument to prepend the linker invocation (can be used several times)"),
1388 pre_link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
1389 "extra arguments to prepend to the linker invocation (space separated)"),
1390 profile: bool = (false, parse_bool, [TRACKED],
1391 "insert profiling code"),
1392 disable_instrumentation_preinliner: bool = (false, parse_bool, [TRACKED],
1393 "Disable the instrumentation pre-inliner, useful for profiling / PGO."),
1394 relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
1395 "choose which RELRO level to use"),
1396 nll_facts: bool = (false, parse_bool, [UNTRACKED],
1397 "dump facts from NLL analysis into side files"),
1398 nll_dont_emit_read_for_match: bool = (false, parse_bool, [UNTRACKED],
1399 "in match codegen, do not include FakeRead statements (used by mir-borrowck)"),
1400 dont_buffer_diagnostics: bool = (false, parse_bool, [UNTRACKED],
1401 "emit diagnostics rather than buffering (breaks NLL error downgrading, sorting)."),
1402 polonius: bool = (false, parse_bool, [UNTRACKED],
1403 "enable polonius-based borrow-checker"),
1404 codegen_time_graph: bool = (false, parse_bool, [UNTRACKED],
1405 "generate a graphical HTML report of time spent in codegen and LLVM"),
1406 thinlto: Option<bool> = (None, parse_opt_bool, [TRACKED],
1407 "enable ThinLTO when possible"),
1408 inline_in_all_cgus: Option<bool> = (None, parse_opt_bool, [TRACKED],
1409 "control whether `#[inline]` functions are in all CGUs"),
1410 tls_model: Option<String> = (None, parse_opt_string, [TRACKED],
1411 "choose the TLS model to use (`rustc --print tls-models` for details)"),
1412 saturating_float_casts: bool = (false, parse_bool, [TRACKED],
1413 "make float->int casts UB-free: numbers outside the integer type's range are clipped to \
1414 the max/min integer respectively, and NaN is mapped to 0"),
1415 human_readable_cgu_names: bool = (false, parse_bool, [TRACKED],
1416 "generate human-readable, predictable names for codegen units"),
1417 dep_info_omit_d_target: bool = (false, parse_bool, [TRACKED],
1418 "in dep-info output, omit targets for tracking dependencies of the dep-info files \
1420 unpretty: Option<String> = (None, parse_unpretty, [UNTRACKED],
1421 "present the input source, unstable (and less-pretty) variants;
1422 valid types are any of the types for `--pretty`, as well as:
1423 `expanded`, `expanded,identified`,
1424 `expanded,hygiene` (with internal representations),
1425 `everybody_loops` (all function bodies replaced with `loop {}`),
1426 `hir` (the HIR), `hir,identified`,
1427 `hir,typed` (HIR with types for each node),
1428 `hir-tree` (dump the raw HIR),
1429 `mir` (the MIR), or `mir-cfg` (graphviz formatted MIR)"),
1430 run_dsymutil: Option<bool> = (None, parse_opt_bool, [TRACKED],
1431 "run `dsymutil` and delete intermediate object files"),
1432 ui_testing: bool = (false, parse_bool, [UNTRACKED],
1433 "format compiler diagnostics in a way that's better suitable for UI testing"),
1434 embed_bitcode: bool = (false, parse_bool, [TRACKED],
1435 "embed LLVM bitcode in object files"),
1436 strip_debuginfo_if_disabled: Option<bool> = (None, parse_opt_bool, [TRACKED],
1437 "tell the linker to strip debuginfo when building without debuginfo enabled."),
1438 share_generics: Option<bool> = (None, parse_opt_bool, [TRACKED],
1439 "make the current crate share its generic instantiations"),
1440 chalk: bool = (false, parse_bool, [TRACKED],
1441 "enable the experimental Chalk-based trait solving engine"),
1442 no_parallel_llvm: bool = (false, parse_bool, [UNTRACKED],
1443 "don't run LLVM in parallel (while keeping codegen-units and ThinLTO)"),
1444 no_leak_check: bool = (false, parse_bool, [UNTRACKED],
1445 "disables the 'leak check' for subtyping; unsound, but useful for tests"),
1446 no_interleave_lints: bool = (false, parse_bool, [UNTRACKED],
1447 "don't interleave execution of lints; allows benchmarking individual lints"),
1448 crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],
1449 "inject the given attribute in the crate"),
1450 self_profile: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
1451 parse_switch_with_opt_path, [UNTRACKED],
1452 "run the self profiler and output the raw event data"),
1453 self_profile_events: Option<Vec<String>> = (None, parse_opt_comma_list, [UNTRACKED],
1454 "specifies which kinds of events get recorded by the self profiler"),
1455 emit_stack_sizes: bool = (false, parse_bool, [UNTRACKED],
1456 "emits a section containing stack size metadata"),
1457 plt: Option<bool> = (None, parse_opt_bool, [TRACKED],
1458 "whether to use the PLT when calling into shared libraries;
1459 only has effect for PIC code on systems with ELF binaries
1460 (default: PLT is disabled if full relro is enabled)"),
1461 merge_functions: Option<MergeFunctions> = (None, parse_merge_functions, [TRACKED],
1462 "control the operation of the MergeFunctions LLVM pass, taking
1463 the same values as the target option of the same name"),
1464 allow_features: Option<Vec<String>> = (None, parse_opt_comma_list, [TRACKED],
1465 "only allow the listed language features to be enabled in code (space separated)"),
1466 symbol_mangling_version: SymbolManglingVersion = (SymbolManglingVersion::Legacy,
1467 parse_symbol_mangling_version, [TRACKED],
1468 "which mangling version to use for symbol names"),
1469 binary_dep_depinfo: bool = (false, parse_bool, [TRACKED],
1470 "include artifacts (sysroot, crate dependencies) used during compilation in dep-info"),
1471 insert_sideeffect: bool = (false, parse_bool, [TRACKED],
1472 "fix undefined behavior when a thread doesn't eventually make progress \
1473 (such as entering an empty infinite loop) by inserting llvm.sideeffect"),
1476 pub const fn default_lib_output() -> CrateType {
1480 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
1481 let end = &sess.target.target.target_endian;
1482 let arch = &sess.target.target.arch;
1483 let wordsz = &sess.target.target.target_pointer_width;
1484 let os = &sess.target.target.target_os;
1485 let env = &sess.target.target.target_env;
1486 let vendor = &sess.target.target.target_vendor;
1487 let min_atomic_width = sess.target.target.min_atomic_width();
1488 let max_atomic_width = sess.target.target.max_atomic_width();
1489 let atomic_cas = sess.target.target.options.atomic_cas;
1491 let mut ret = FxHashSet::default();
1492 ret.reserve(6); // the minimum number of insertions
1494 ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
1495 if let Some(ref fam) = sess.target.target.options.target_family {
1496 ret.insert((Symbol::intern("target_family"), Some(Symbol::intern(fam))));
1497 if fam == "windows" || fam == "unix" {
1498 ret.insert((Symbol::intern(fam), None));
1501 ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
1502 ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
1504 Symbol::intern("target_pointer_width"),
1505 Some(Symbol::intern(wordsz)),
1507 ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
1509 Symbol::intern("target_vendor"),
1510 Some(Symbol::intern(vendor)),
1512 if sess.target.target.options.has_elf_tls {
1513 ret.insert((sym::target_thread_local, None));
1515 for &i in &[8, 16, 32, 64, 128] {
1516 if i >= min_atomic_width && i <= max_atomic_width {
1517 let mut insert_atomic = |s| {
1519 sym::target_has_atomic_load_store,
1520 Some(Symbol::intern(s)),
1524 sym::target_has_atomic,
1525 Some(Symbol::intern(s))
1529 let s = i.to_string();
1532 insert_atomic("ptr");
1536 if sess.opts.debug_assertions {
1537 ret.insert((Symbol::intern("debug_assertions"), None));
1539 if sess.opts.crate_types.contains(&CrateType::ProcMacro) {
1540 ret.insert((sym::proc_macro, None));
1545 /// Converts the crate `cfg!` configuration from `String` to `Symbol`.
1546 /// `rustc_interface::interface::Config` accepts this in the compiler configuration,
1547 /// but the symbol interner is not yet set up then, so we must convert it later.
1548 pub fn to_crate_config(cfg: FxHashSet<(String, Option<String>)>) -> ast::CrateConfig {
1550 .map(|(a, b)| (Symbol::intern(&a), b.map(|b| Symbol::intern(&b))))
1554 pub fn build_configuration(sess: &Session, mut user_cfg: ast::CrateConfig) -> ast::CrateConfig {
1555 // Combine the configuration requested by the session (command line) with
1556 // some default and generated configuration items.
1557 let default_cfg = default_configuration(sess);
1558 // If the user wants a test runner, then add the test cfg.
1560 user_cfg.insert((sym::test, None));
1562 user_cfg.extend(default_cfg.iter().cloned());
1566 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
1567 let target = Target::search(&opts.target_triple).unwrap_or_else(|e| {
1568 sp.struct_fatal(&format!("Error loading target specification: {}", e))
1569 .help("Use `--print target-list` for a list of built-in targets")
1574 let (isize_ty, usize_ty) = match &target.target_pointer_width[..] {
1575 "16" => (ast::IntTy::I16, ast::UintTy::U16),
1576 "32" => (ast::IntTy::I32, ast::UintTy::U32),
1577 "64" => (ast::IntTy::I64, ast::UintTy::U64),
1578 w => sp.fatal(&format!(
1579 "target specification was invalid: \
1580 unrecognized target-pointer-width {}",
1592 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1593 pub enum OptionStability {
1598 pub struct RustcOptGroup {
1599 pub apply: Box<dyn Fn(&mut getopts::Options) -> &mut getopts::Options>,
1600 pub name: &'static str,
1601 pub stability: OptionStability,
1604 impl RustcOptGroup {
1605 pub fn is_stable(&self) -> bool {
1606 self.stability == OptionStability::Stable
1609 pub fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
1611 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1616 stability: OptionStability::Stable,
1620 pub fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
1622 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1627 stability: OptionStability::Unstable,
1632 // The `opt` local module holds wrappers around the `getopts` API that
1633 // adds extra rustc-specific metadata to each option; such metadata
1634 // is exposed by . The public
1635 // functions below ending with `_u` are the functions that return
1636 // *unstable* options, i.e., options that are only enabled when the
1637 // user also passes the `-Z unstable-options` debugging flag.
1639 // The `fn flag*` etc below are written so that we can use them
1640 // in the future; do not warn about them not being used right now.
1641 #![allow(dead_code)]
1644 use super::RustcOptGroup;
1646 pub type R = RustcOptGroup;
1647 pub type S = &'static str;
1649 fn stable<F>(name: S, f: F) -> R
1651 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1653 RustcOptGroup::stable(name, f)
1656 fn unstable<F>(name: S, f: F) -> R
1658 F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static,
1660 RustcOptGroup::unstable(name, f)
1663 fn longer(a: S, b: S) -> S {
1664 if a.len() > b.len() {
1671 pub fn opt_s(a: S, b: S, c: S, d: S) -> R {
1672 stable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1674 pub fn multi_s(a: S, b: S, c: S, d: S) -> R {
1675 stable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1677 pub fn flag_s(a: S, b: S, c: S) -> R {
1678 stable(longer(a, b), move |opts| opts.optflag(a, b, c))
1680 pub fn flagopt_s(a: S, b: S, c: S, d: S) -> R {
1681 stable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1683 pub fn flagmulti_s(a: S, b: S, c: S) -> R {
1684 stable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1687 pub fn opt(a: S, b: S, c: S, d: S) -> R {
1688 unstable(longer(a, b), move |opts| opts.optopt(a, b, c, d))
1690 pub fn multi(a: S, b: S, c: S, d: S) -> R {
1691 unstable(longer(a, b), move |opts| opts.optmulti(a, b, c, d))
1693 pub fn flag(a: S, b: S, c: S) -> R {
1694 unstable(longer(a, b), move |opts| opts.optflag(a, b, c))
1696 pub fn flagopt(a: S, b: S, c: S, d: S) -> R {
1697 unstable(longer(a, b), move |opts| opts.optflagopt(a, b, c, d))
1699 pub fn flagmulti(a: S, b: S, c: S) -> R {
1700 unstable(longer(a, b), move |opts| opts.optflagmulti(a, b, c))
1704 /// Returns the "short" subset of the rustc command line options,
1705 /// including metadata for each option, such as whether the option is
1706 /// part of the stable long-term interface for rustc.
1707 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
1709 opt::flag_s("h", "help", "Display this message"),
1710 opt::multi_s("", "cfg", "Configure the compilation environment", "SPEC"),
1714 "Add a directory to the library search path. The
1715 optional KIND can be one of dependency, crate, native,
1716 framework, or all (the default).",
1722 "Link the generated crate(s) to the specified native
1723 library NAME. The optional KIND can be one of
1724 static, framework, or dylib (the default).",
1727 make_crate_type_option(),
1731 "Specify the name of the crate being built",
1737 "Specify which edition of the compiler to use when compiling code.",
1743 "Comma separated list of types of output for \
1744 the compiler to emit",
1745 "[asm|llvm-bc|llvm-ir|obj|metadata|link|dep-info|mir]",
1750 "Compiler information to print on stdout",
1751 "[crate-name|file-names|sysroot|cfg|target-list|\
1752 target-cpus|target-features|relocation-models|\
1753 code-models|tls-models|target-spec-json|native-static-libs]",
1755 opt::flagmulti_s("g", "", "Equivalent to -C debuginfo=2"),
1756 opt::flagmulti_s("O", "", "Equivalent to -C opt-level=2"),
1757 opt::opt_s("o", "", "Write output to <filename>", "FILENAME"),
1761 "Write output to compiler-chosen filename \
1768 "Provide a detailed explanation of an error \
1772 opt::flag_s("", "test", "Build a test harness"),
1776 "Target triple for which the code is compiled",
1779 opt::multi_s("W", "warn", "Set lint warnings", "OPT"),
1780 opt::multi_s("A", "allow", "Set lint allowed", "OPT"),
1781 opt::multi_s("D", "deny", "Set lint denied", "OPT"),
1782 opt::multi_s("F", "forbid", "Set lint forbidden", "OPT"),
1786 "Set the most restrictive lint level. \
1787 More restrictive lints are capped at this \
1791 opt::multi_s("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
1792 opt::flag_s("V", "version", "Print version info and exit"),
1793 opt::flag_s("v", "verbose", "Use verbose output"),
1797 /// Returns all rustc command line options, including metadata for
1798 /// each option, such as whether the option is part of the stable
1799 /// long-term interface for rustc.
1800 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
1801 let mut opts = rustc_short_optgroups();
1806 "Specify where an external rust library is located",
1812 "Specify where an extern rust library is located, marking it as a private dependency",
1815 opt::opt_s("", "sysroot", "Override the system root", "PATH"),
1816 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
1820 "How errors and other messages are produced",
1826 "Configure the JSON output of the compiler",
1832 "Configure coloring of output:
1833 auto = colorize, if output goes to a tty (default);
1834 always = always colorize output;
1835 never = never colorize output",
1836 "auto|always|never",
1841 "Pretty-print the input instead of compiling;
1842 valid types are: `normal` (un-annotated source),
1843 `expanded` (crates expanded), or
1844 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
1849 "remap-path-prefix",
1850 "Remap source names in all output (compiler messages and output files)",
1857 pub fn get_cmd_lint_options(matches: &getopts::Matches,
1858 error_format: ErrorOutputType)
1859 -> (Vec<(String, lint::Level)>, bool, Option<lint::Level>) {
1860 let mut lint_opts = vec![];
1861 let mut describe_lints = false;
1863 for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
1864 for lint_name in matches.opt_strs(level.as_str()) {
1865 if lint_name == "help" {
1866 describe_lints = true;
1868 lint_opts.push((lint_name.replace("-", "_"), level));
1873 let lint_cap = matches.opt_str("cap-lints").map(|cap| {
1874 lint::Level::from_str(&cap)
1875 .unwrap_or_else(|| early_error(error_format, &format!("unknown lint level: `{}`", cap)))
1877 (lint_opts, describe_lints, lint_cap)
1880 /// Parses the `--color` flag.
1881 pub fn parse_color(matches: &getopts::Matches) -> ColorConfig {
1882 match matches.opt_str("color").as_ref().map(|s| &s[..]) {
1883 Some("auto") => ColorConfig::Auto,
1884 Some("always") => ColorConfig::Always,
1885 Some("never") => ColorConfig::Never,
1887 None => ColorConfig::Auto,
1889 Some(arg) => early_error(
1890 ErrorOutputType::default(),
1892 "argument for `--color` must be auto, \
1893 always or never (instead was `{}`)",
1900 /// Parse the `--json` flag.
1902 /// The first value returned is how to render JSON diagnostics, and the second
1903 /// is whether or not artifact notifications are enabled.
1904 pub fn parse_json(matches: &getopts::Matches) -> (HumanReadableErrorType, bool) {
1905 let mut json_rendered: fn(ColorConfig) -> HumanReadableErrorType =
1906 HumanReadableErrorType::Default;
1907 let mut json_color = ColorConfig::Never;
1908 let mut json_artifact_notifications = false;
1909 for option in matches.opt_strs("json") {
1910 // For now conservatively forbid `--color` with `--json` since `--json`
1911 // won't actually be emitting any colors and anything colorized is
1912 // embedded in a diagnostic message anyway.
1913 if matches.opt_str("color").is_some() {
1915 ErrorOutputType::default(),
1916 "cannot specify the `--color` option with `--json`",
1920 for sub_option in option.split(',') {
1922 "diagnostic-short" => json_rendered = HumanReadableErrorType::Short,
1923 "diagnostic-rendered-ansi" => json_color = ColorConfig::Always,
1924 "artifacts" => json_artifact_notifications = true,
1927 ErrorOutputType::default(),
1928 &format!("unknown `--json` option `{}`", s),
1934 (json_rendered(json_color), json_artifact_notifications)
1937 /// Parses the `--error-format` flag.
1938 pub fn parse_error_format(
1939 matches: &getopts::Matches,
1941 json_rendered: HumanReadableErrorType,
1942 ) -> ErrorOutputType {
1943 // We need the `opts_present` check because the driver will send us Matches
1944 // with only stable options if no unstable options are used. Since error-format
1945 // is unstable, it will not be present. We have to use `opts_present` not
1946 // `opt_present` because the latter will panic.
1947 let error_format = if matches.opts_present(&["error-format".to_owned()]) {
1948 match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
1950 Some("human") => ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color)),
1951 Some("human-annotate-rs") => {
1952 ErrorOutputType::HumanReadable(HumanReadableErrorType::AnnotateSnippet(color))
1954 Some("json") => ErrorOutputType::Json { pretty: false, json_rendered },
1955 Some("pretty-json") => ErrorOutputType::Json { pretty: true, json_rendered },
1956 Some("short") => ErrorOutputType::HumanReadable(HumanReadableErrorType::Short(color)),
1958 Some(arg) => early_error(
1959 ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color)),
1961 "argument for `--error-format` must be `human`, `json` or \
1962 `short` (instead was `{}`)",
1968 ErrorOutputType::HumanReadable(HumanReadableErrorType::Default(color))
1971 match error_format {
1972 ErrorOutputType::Json { .. } => {}
1974 // Conservatively require that the `--json` argument is coupled with
1975 // `--error-format=json`. This means that `--json` is specified we
1976 // should actually be emitting JSON blobs.
1977 _ if matches.opt_strs("json").len() > 0 => {
1979 ErrorOutputType::default(),
1980 "using `--json` requires also using `--error-format=json`",
1987 return error_format;
1990 fn parse_crate_edition(matches: &getopts::Matches) -> Edition {
1991 let edition = match matches.opt_str("edition") {
1992 Some(arg) => Edition::from_str(&arg).unwrap_or_else(|_|
1994 ErrorOutputType::default(),
1996 "argument for `--edition` must be one of: \
1997 {}. (instead was `{}`)",
2003 None => DEFAULT_EDITION,
2006 if !edition.is_stable() && !nightly_options::is_nightly_build() {
2008 ErrorOutputType::default(),
2010 "edition {} is unstable and only \
2011 available for nightly builds of rustc.",
2020 fn check_debug_option_stability(
2021 debugging_opts: &DebuggingOptions,
2022 error_format: ErrorOutputType,
2023 json_rendered: HumanReadableErrorType,
2025 if !debugging_opts.unstable_options {
2026 if let ErrorOutputType::Json { pretty: true, json_rendered } = error_format {
2028 ErrorOutputType::Json { pretty: false, json_rendered },
2029 "`--error-format=pretty-json` is unstable",
2032 if let ErrorOutputType::HumanReadable(HumanReadableErrorType::AnnotateSnippet(_)) =
2035 ErrorOutputType::Json { pretty: false, json_rendered },
2036 "`--error-format=human-annotate-rs` is unstable",
2042 fn parse_output_types(
2043 debugging_opts: &DebuggingOptions,
2044 matches: &getopts::Matches,
2045 error_format: ErrorOutputType,
2047 let mut output_types = BTreeMap::new();
2048 if !debugging_opts.parse_only {
2049 for list in matches.opt_strs("emit") {
2050 for output_type in list.split(',') {
2051 let mut parts = output_type.splitn(2, '=');
2052 let shorthand = parts.next().unwrap();
2053 let output_type = OutputType::from_shorthand(shorthand).unwrap_or_else(||
2057 "unknown emission type: `{}` - expected one of: {}",
2059 OutputType::shorthands_display(),
2063 let path = parts.next().map(PathBuf::from);
2064 output_types.insert(output_type, path);
2068 if output_types.is_empty() {
2069 output_types.insert(OutputType::Exe, None);
2071 OutputTypes(output_types)
2074 fn should_override_cgus_and_disable_thinlto(
2075 output_types: &OutputTypes,
2076 matches: &getopts::Matches,
2077 error_format: ErrorOutputType,
2078 mut codegen_units: Option<usize>,
2079 ) -> (bool, Option<usize>) {
2080 let mut disable_thinlto = false;
2081 // Issue #30063: if user requests LLVM-related output to one
2082 // particular path, disable codegen-units.
2083 let incompatible: Vec<_> = output_types.0
2085 .map(|ot_path| ot_path.0)
2086 .filter(|ot| !ot.is_compatible_with_codegen_units_and_single_output_file())
2087 .map(|ot| ot.shorthand())
2089 if !incompatible.is_empty() {
2090 match codegen_units {
2091 Some(n) if n > 1 => {
2092 if matches.opt_present("o") {
2093 for ot in &incompatible {
2097 "`--emit={}` with `-o` incompatible with \
2098 `-C codegen-units=N` for N > 1",
2103 early_warn(error_format, "resetting to default -C codegen-units=1");
2104 codegen_units = Some(1);
2105 disable_thinlto = true;
2109 codegen_units = Some(1);
2110 disable_thinlto = true;
2115 if codegen_units == Some(0) {
2118 "value for codegen units must be a positive non-zero integer",
2122 (disable_thinlto, codegen_units)
2125 fn check_thread_count(debugging_opts: &DebuggingOptions, error_format: ErrorOutputType) {
2126 if debugging_opts.threads == 0 {
2129 "value for threads must be a positive non-zero integer",
2133 if debugging_opts.threads > 1 && debugging_opts.fuel.is_some() {
2136 "optimization fuel is incompatible with multiple threads",
2141 fn select_incremental_path(
2142 debugging_opts: &DebuggingOptions,
2143 cg: &CodegenOptions,
2144 error_format: ErrorOutputType,
2145 ) -> Option<PathBuf> {
2146 match (&debugging_opts.incremental, &cg.incremental) {
2147 (Some(path1), Some(path2)) => {
2152 "conflicting paths for `-Z incremental` and \
2153 `-C incremental` specified: {} versus {}",
2161 (Some(path), None) => Some(path),
2162 (None, Some(path)) => Some(path),
2163 (None, None) => None,
2164 }.map(|m| PathBuf::from(m))
2167 fn collect_print_requests(
2168 cg: &mut CodegenOptions,
2169 dopts: &mut DebuggingOptions,
2170 matches: &getopts::Matches,
2171 error_format: ErrorOutputType,
2172 ) -> Vec<PrintRequest> {
2173 let mut prints = Vec::<PrintRequest>::new();
2174 if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
2175 prints.push(PrintRequest::TargetCPUs);
2176 cg.target_cpu = None;
2178 if cg.target_feature == "help" {
2179 prints.push(PrintRequest::TargetFeatures);
2180 cg.target_feature = String::new();
2182 if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
2183 prints.push(PrintRequest::RelocationModels);
2184 cg.relocation_model = None;
2186 if cg.code_model.as_ref().map_or(false, |s| s == "help") {
2187 prints.push(PrintRequest::CodeModels);
2188 cg.code_model = None;
2193 .map_or(false, |s| s == "help")
2195 prints.push(PrintRequest::TlsModels);
2196 dopts.tls_model = None;
2199 prints.extend(matches.opt_strs("print").into_iter().map(|s| match &*s {
2200 "crate-name" => PrintRequest::CrateName,
2201 "file-names" => PrintRequest::FileNames,
2202 "sysroot" => PrintRequest::Sysroot,
2203 "cfg" => PrintRequest::Cfg,
2204 "target-list" => PrintRequest::TargetList,
2205 "target-cpus" => PrintRequest::TargetCPUs,
2206 "target-features" => PrintRequest::TargetFeatures,
2207 "relocation-models" => PrintRequest::RelocationModels,
2208 "code-models" => PrintRequest::CodeModels,
2209 "tls-models" => PrintRequest::TlsModels,
2210 "native-static-libs" => PrintRequest::NativeStaticLibs,
2211 "target-spec-json" => {
2212 if dopts.unstable_options {
2213 PrintRequest::TargetSpec
2217 "the `-Z unstable-options` flag must also be passed to \
2218 enable the target-spec-json print option",
2222 req => early_error(error_format, &format!("unknown print request `{}`", req)),
2228 fn parse_target_triple(matches: &getopts::Matches, error_format: ErrorOutputType) -> TargetTriple {
2229 match matches.opt_str("target") {
2230 Some(target) if target.ends_with(".json") => {
2231 let path = Path::new(&target);
2232 TargetTriple::from_path(&path).unwrap_or_else(|_|
2233 early_error(error_format, &format!("target file {:?} does not exist", path)))
2235 Some(target) => TargetTriple::TargetTriple(target),
2236 _ => TargetTriple::from_triple(host_triple()),
2241 matches: &getopts::Matches,
2242 cg: &CodegenOptions,
2243 error_format: ErrorOutputType,
2245 // The `-O` and `-C opt-level` flags specify the same setting, so we want to be able
2246 // to use them interchangeably. However, because they're technically different flags,
2247 // we need to work out manually which should take precedence if both are supplied (i.e.
2248 // the rightmost flag). We do this by finding the (rightmost) position of both flags and
2249 // comparing them. Note that if a flag is not found, its position will be `None`, which
2250 // always compared less than `Some(_)`.
2251 let max_o = matches.opt_positions("O").into_iter().max();
2252 let max_c = matches.opt_strs_pos("C").into_iter().flat_map(|(i, s)| {
2253 if let Some("opt-level") = s.splitn(2, '=').next() {
2262 match cg.opt_level.as_ref().map(String::as_ref) {
2263 None => OptLevel::No,
2264 Some("0") => OptLevel::No,
2265 Some("1") => OptLevel::Less,
2266 Some("2") => OptLevel::Default,
2267 Some("3") => OptLevel::Aggressive,
2268 Some("s") => OptLevel::Size,
2269 Some("z") => OptLevel::SizeMin,
2274 "optimization level needs to be \
2275 between 0-3, s or z (instead was `{}`)",
2284 fn select_debuginfo(
2285 matches: &getopts::Matches,
2286 cg: &CodegenOptions,
2287 error_format: ErrorOutputType,
2289 let max_g = matches.opt_positions("g").into_iter().max();
2290 let max_c = matches.opt_strs_pos("C").into_iter().flat_map(|(i, s)| {
2291 if let Some("debuginfo") = s.splitn(2, '=').next() {
2300 match cg.debuginfo {
2301 None | Some(0) => DebugInfo::None,
2302 Some(1) => DebugInfo::Limited,
2303 Some(2) => DebugInfo::Full,
2308 "debug info level needs to be between \
2309 0-2 (instead was `{}`)",
2319 matches: &getopts::Matches,
2320 error_format: ErrorOutputType,
2321 ) -> Vec<(String, Option<String>, Option<cstore::NativeLibraryKind>)> {
2326 // Parse string of the form "[KIND=]lib[:new_name]",
2327 // where KIND is one of "dylib", "framework", "static".
2328 let mut parts = s.splitn(2, '=');
2329 let kind = parts.next().unwrap();
2330 let (name, kind) = match (parts.next(), kind) {
2331 (None, name) => (name, None),
2332 (Some(name), "dylib") => (name, Some(cstore::NativeUnknown)),
2333 (Some(name), "framework") => (name, Some(cstore::NativeFramework)),
2334 (Some(name), "static") => (name, Some(cstore::NativeStatic)),
2335 (Some(name), "static-nobundle") => (name, Some(cstore::NativeStaticNobundle)),
2340 "unknown library kind `{}`, expected \
2341 one of dylib, framework, or static",
2347 if kind == Some(cstore::NativeStaticNobundle) && !nightly_options::is_nightly_build() {
2351 "the library kind 'static-nobundle' is only \
2352 accepted on the nightly compiler"
2356 let mut name_parts = name.splitn(2, ':');
2357 let name = name_parts.next().unwrap();
2358 let new_name = name_parts.next();
2359 (name.to_owned(), new_name.map(|n| n.to_owned()), kind)
2364 fn parse_borrowck_mode(dopts: &DebuggingOptions, error_format: ErrorOutputType) -> BorrowckMode {
2365 match dopts.borrowck.as_ref().map(|s| &s[..]) {
2366 None | Some("migrate") => BorrowckMode::Migrate,
2367 Some("mir") => BorrowckMode::Mir,
2368 Some(m) => early_error(error_format, &format!("unknown borrowck mode `{}`", m)),
2373 matches: &getopts::Matches,
2374 debugging_opts: &DebuggingOptions,
2375 error_format: ErrorOutputType,
2377 if matches.opt_present("extern-private") && !debugging_opts.unstable_options {
2379 ErrorOutputType::default(),
2380 "'--extern-private' is unstable and only \
2381 available for nightly builds of rustc."
2385 // We start out with a `Vec<(Option<String>, bool)>>`,
2386 // and later convert it into a `BTreeSet<(Option<String>, bool)>`
2387 // This allows to modify entries in-place to set their correct
2389 let mut externs: BTreeMap<String, ExternEntry> = BTreeMap::new();
2390 for (arg, private) in matches.opt_strs("extern").into_iter().map(|v| (v, false))
2391 .chain(matches.opt_strs("extern-private").into_iter().map(|v| (v, true))) {
2393 let mut parts = arg.splitn(2, '=');
2394 let name = parts.next().unwrap_or_else(||
2395 early_error(error_format, "--extern value must not be empty"));
2396 let location = parts.next().map(|s| s.to_string());
2399 .entry(name.to_owned())
2403 entry.locations.insert(location.clone());
2405 // Crates start out being not private,
2406 // and go to being private if we see an '--extern-private'
2408 entry.is_private_dep |= private;
2413 fn parse_remap_path_prefix(
2414 matches: &getopts::Matches,
2415 error_format: ErrorOutputType
2416 ) -> Vec<(PathBuf, PathBuf)> {
2418 .opt_strs("remap-path-prefix")
2421 let mut parts = remap.rsplitn(2, '='); // reverse iterator
2422 let to = parts.next();
2423 let from = parts.next();
2425 (Some(from), Some(to)) => (PathBuf::from(from), PathBuf::from(to)),
2428 "--remap-path-prefix must contain '=' between FROM and TO",
2435 pub fn build_session_options(matches: &getopts::Matches) -> Options {
2436 let color = parse_color(matches);
2438 let edition = parse_crate_edition(matches);
2440 let (json_rendered, json_artifact_notifications) = parse_json(matches);
2442 let error_format = parse_error_format(matches, color, json_rendered);
2444 let unparsed_crate_types = matches.opt_strs("crate-type");
2445 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
2446 .unwrap_or_else(|e| early_error(error_format, &e[..]));
2448 let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
2450 let mut debugging_opts = build_debugging_options(matches, error_format);
2451 check_debug_option_stability(&debugging_opts, error_format, json_rendered);
2453 let output_types = parse_output_types(&debugging_opts, matches, error_format);
2455 let mut cg = build_codegen_options(matches, error_format);
2456 let (disable_thinlto, codegen_units) = should_override_cgus_and_disable_thinlto(
2463 check_thread_count(&debugging_opts, error_format);
2465 let incremental = select_incremental_path(&debugging_opts, &cg, error_format);
2467 if debugging_opts.profile && incremental.is_some() {
2470 "can't instrument with gcov profiling when compiling incrementally",
2474 if cg.profile_generate.enabled() && cg.profile_use.is_some() {
2477 "options `-C profile-generate` and `-C profile-use` are exclusive",
2481 let prints = collect_print_requests(
2483 &mut debugging_opts,
2490 let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
2491 let target_triple = parse_target_triple(matches, error_format);
2492 let opt_level = parse_opt_level(matches, &cg, error_format);
2493 // The `-g` and `-C debuginfo` flags specify the same setting, so we want to be able
2494 // to use them interchangeably. See the note above (regarding `-O` and `-C opt-level`)
2495 // for more details.
2496 let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
2497 let debuginfo = select_debuginfo(matches, &cg, error_format);
2499 let mut search_paths = vec![];
2500 for s in &matches.opt_strs("L") {
2501 search_paths.push(SearchPath::from_cli_opt(&s[..], error_format));
2504 let libs = parse_libs(matches, error_format);
2506 let test = matches.opt_present("test");
2508 let borrowck_mode = parse_borrowck_mode(&debugging_opts, error_format);
2510 if !cg.remark.is_empty() && debuginfo == DebugInfo::None {
2513 "-C remark requires \"-C debuginfo=n\" to show source locations",
2517 let externs = parse_externs(matches, &debugging_opts, error_format);
2519 let crate_name = matches.opt_str("crate-name");
2521 let remap_path_prefix = parse_remap_path_prefix(matches, error_format);
2523 let pretty = parse_pretty(matches, &debugging_opts, error_format);
2527 optimize: opt_level,
2534 maybe_sysroot: sysroot_opt,
2547 unstable_features: UnstableFeatures::from_environment(),
2549 actually_rustdoc: false,
2550 cli_forced_codegen_units: codegen_units,
2551 cli_forced_thinlto_off: disable_thinlto,
2554 json_artifact_notifications,
2560 matches: &getopts::Matches,
2561 debugging_opts: &DebuggingOptions,
2562 efmt: ErrorOutputType,
2563 ) -> Option<(PpMode, Option<UserIdentifiedItem>)> {
2564 let pretty = if debugging_opts.unstable_options {
2565 matches.opt_default("pretty", "normal").map(|a| {
2566 // stable pretty-print variants only
2567 parse_pretty_inner(efmt, &a, false)
2573 return if pretty.is_none() {
2574 debugging_opts.unpretty.as_ref().map(|a| {
2575 // extended with unstable pretty-print variants
2576 parse_pretty_inner(efmt, &a, true)
2582 fn parse_pretty_inner(
2583 efmt: ErrorOutputType,
2586 ) -> (PpMode, Option<UserIdentifiedItem>) {
2588 use PpSourceMode::*;
2589 let mut split = name.splitn(2, '=');
2590 let first = split.next().unwrap();
2591 let opt_second = split.next();
2592 let first = match (first, extended) {
2593 ("normal", _) => PpmSource(PpmNormal),
2594 ("identified", _) => PpmSource(PpmIdentified),
2595 ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
2596 ("expanded", _) => PpmSource(PpmExpanded),
2597 ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
2598 ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
2599 ("hir", true) => PpmHir(PpmNormal),
2600 ("hir,identified", true) => PpmHir(PpmIdentified),
2601 ("hir,typed", true) => PpmHir(PpmTyped),
2602 ("hir-tree", true) => PpmHirTree(PpmNormal),
2603 ("mir", true) => PpmMir,
2604 ("mir-cfg", true) => PpmMirCFG,
2607 early_error(efmt, &format!("argument to `unpretty` must be one of `normal`, \
2608 `expanded`, `identified`, `expanded,identified`, \
2609 `expanded,hygiene`, `everybody_loops`, \
2610 `hir`, `hir,identified`, `hir,typed`, `hir-tree`, \
2611 `mir` or `mir-cfg`; got {}",
2614 early_error(efmt, &format!("argument to `pretty` must be one of `normal`, \
2615 `expanded`, `identified`, or `expanded,identified`; got {}",
2620 let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
2625 pub fn make_crate_type_option() -> RustcOptGroup {
2629 "Comma separated list of types of crates
2630 for the compiler to emit",
2631 "[bin|lib|rlib|dylib|cdylib|staticlib|proc-macro]",
2635 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
2636 let mut crate_types: Vec<CrateType> = Vec::new();
2637 for unparsed_crate_type in &list_list {
2638 for part in unparsed_crate_type.split(',') {
2639 let new_part = match part {
2640 "lib" => default_lib_output(),
2641 "rlib" => CrateType::Rlib,
2642 "staticlib" => CrateType::Staticlib,
2643 "dylib" => CrateType::Dylib,
2644 "cdylib" => CrateType::Cdylib,
2645 "bin" => CrateType::Executable,
2646 "proc-macro" => CrateType::ProcMacro,
2647 _ => return Err(format!("unknown crate type: `{}`", part))
2649 if !crate_types.contains(&new_part) {
2650 crate_types.push(new_part)
2658 pub mod nightly_options {
2660 use syntax::feature_gate::UnstableFeatures;
2661 use super::{ErrorOutputType, OptionStability, RustcOptGroup};
2662 use crate::session::early_error;
2664 pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
2669 .any(|x| *x == "unstable-options")
2672 pub fn is_nightly_build() -> bool {
2673 UnstableFeatures::from_environment().is_nightly_build()
2676 pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
2677 let has_z_unstable_option = matches
2680 .any(|x| *x == "unstable-options");
2681 let really_allows_unstable_options =
2682 UnstableFeatures::from_environment().is_nightly_build();
2684 for opt in flags.iter() {
2685 if opt.stability == OptionStability::Stable {
2688 if !matches.opt_present(opt.name) {
2691 if opt.name != "Z" && !has_z_unstable_option {
2693 ErrorOutputType::default(),
2695 "the `-Z unstable-options` flag must also be passed to enable \
2701 if really_allows_unstable_options {
2704 match opt.stability {
2705 OptionStability::Unstable => {
2707 "the option `{}` is only accepted on the \
2711 early_error(ErrorOutputType::default(), &msg);
2713 OptionStability::Stable => {}
2719 impl fmt::Display for CrateType {
2720 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2722 CrateType::Executable => "bin".fmt(f),
2723 CrateType::Dylib => "dylib".fmt(f),
2724 CrateType::Rlib => "rlib".fmt(f),
2725 CrateType::Staticlib => "staticlib".fmt(f),
2726 CrateType::Cdylib => "cdylib".fmt(f),
2727 CrateType::ProcMacro => "proc-macro".fmt(f),
2732 #[derive(Copy, Clone, PartialEq, Debug)]
2733 pub enum PpSourceMode {
2738 PpmExpandedIdentified,
2743 #[derive(Copy, Clone, PartialEq, Debug)]
2745 PpmSource(PpSourceMode),
2746 PpmHir(PpSourceMode),
2747 PpmHirTree(PpSourceMode),
2753 pub fn needs_ast_map(&self, opt_uii: &Option<UserIdentifiedItem>) -> bool {
2755 use PpSourceMode::*;
2757 PpmSource(PpmNormal) |
2758 PpmSource(PpmEveryBodyLoops) |
2759 PpmSource(PpmIdentified) => opt_uii.is_some(),
2761 PpmSource(PpmExpanded) |
2762 PpmSource(PpmExpandedIdentified) |
2763 PpmSource(PpmExpandedHygiene) |
2768 PpmSource(PpmTyped) => panic!("invalid state"),
2772 pub fn needs_analysis(&self) -> bool {
2775 PpmMir | PpmMirCFG => true,
2781 #[derive(Clone, Debug)]
2782 pub enum UserIdentifiedItem {
2783 ItemViaNode(ast::NodeId),
2784 ItemViaPath(Vec<String>),
2787 impl FromStr for UserIdentifiedItem {
2789 fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
2790 use UserIdentifiedItem::*;
2792 .map(ast::NodeId::from_u32)
2794 .unwrap_or_else(|_| ItemViaPath(s.split("::").map(|s| s.to_string()).collect())))
2798 pub enum NodesMatchingUII<'a> {
2799 NodesMatchingDirect(std::option::IntoIter<ast::NodeId>),
2800 NodesMatchingSuffix(Box<dyn Iterator<Item = ast::NodeId> + 'a>),
2803 impl<'a> Iterator for NodesMatchingUII<'a> {
2804 type Item = ast::NodeId;
2806 fn next(&mut self) -> Option<ast::NodeId> {
2807 use NodesMatchingUII::*;
2809 &mut NodesMatchingDirect(ref mut iter) => iter.next(),
2810 &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
2814 fn size_hint(&self) -> (usize, Option<usize>) {
2815 use NodesMatchingUII::*;
2817 &NodesMatchingDirect(ref iter) => iter.size_hint(),
2818 &NodesMatchingSuffix(ref iter) => iter.size_hint(),
2823 impl UserIdentifiedItem {
2824 pub fn reconstructed_input(&self) -> String {
2825 use UserIdentifiedItem::*;
2827 ItemViaNode(node_id) => node_id.to_string(),
2828 ItemViaPath(ref parts) => parts.join("::"),
2832 pub fn all_matching_node_ids<'a, 'hir>(&'a self,
2833 map: &'a hir_map::Map<'hir>)
2834 -> NodesMatchingUII<'a> {
2835 use UserIdentifiedItem::*;
2836 use NodesMatchingUII::*;
2838 ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()),
2839 ItemViaPath(ref parts) => {
2840 NodesMatchingSuffix(Box::new(map.nodes_matching_suffix(&parts)))
2845 pub fn to_one_node_id(self,
2848 map: &hir_map::Map<'_>)
2850 let fail_because = |is_wrong_because| -> ast::NodeId {
2851 let message = format!("{} needs NodeId (int) or unique path suffix (b::c::d); got \
2854 self.reconstructed_input(),
2856 sess.fatal(&message)
2859 let mut saw_node = ast::DUMMY_NODE_ID;
2861 for node in self.all_matching_node_ids(map) {
2865 fail_because("does not resolve uniquely");
2869 fail_because("does not resolve to any item");
2877 /// Command-line arguments passed to the compiler have to be incorporated with
2878 /// the dependency tracking system for incremental compilation. This module
2879 /// provides some utilities to make this more convenient.
2881 /// The values of all command-line arguments that are relevant for dependency
2882 /// tracking are hashed into a single value that determines whether the
2883 /// incremental compilation cache can be re-used or not. This hashing is done
2884 /// via the `DepTrackingHash` trait defined below, since the standard `Hash`
2885 /// implementation might not be suitable (e.g., arguments are stored in a `Vec`,
2886 /// the hash of which is order dependent, but we might not want the order of
2887 /// arguments to make a difference for the hash).
2889 /// However, since the value provided by `Hash::hash` often *is* suitable,
2890 /// especially for primitive types, there is the
2891 /// `impl_dep_tracking_hash_via_hash!()` macro that allows to simply reuse the
2892 /// `Hash` implementation for `DepTrackingHash`. It's important though that
2893 /// we have an opt-in scheme here, so one is hopefully forced to think about
2894 /// how the hash should be calculated when adding a new command-line argument.
2897 use crate::middle::cstore;
2898 use std::collections::BTreeMap;
2899 use std::hash::Hash;
2900 use std::path::PathBuf;
2901 use std::collections::hash_map::DefaultHasher;
2902 use super::{CrateType, DebugInfo, ErrorOutputType, OptLevel, OutputTypes,
2903 Passes, Sanitizer, LtoCli, LinkerPluginLto, SwitchWithOptPath,
2904 SymbolManglingVersion};
2905 use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel, TargetTriple};
2906 use syntax::edition::Edition;
2907 use syntax::feature_gate::UnstableFeatures;
2909 pub trait DepTrackingHash {
2910 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType);
2913 macro_rules! impl_dep_tracking_hash_via_hash {
2915 impl DepTrackingHash for $t {
2916 fn hash(&self, hasher: &mut DefaultHasher, _: ErrorOutputType) {
2917 Hash::hash(self, hasher);
2923 macro_rules! impl_dep_tracking_hash_for_sortable_vec_of {
2925 impl DepTrackingHash for Vec<$t> {
2926 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2927 let mut elems: Vec<&$t> = self.iter().collect();
2929 Hash::hash(&elems.len(), hasher);
2930 for (index, elem) in elems.iter().enumerate() {
2931 Hash::hash(&index, hasher);
2932 DepTrackingHash::hash(*elem, hasher, error_format);
2939 impl_dep_tracking_hash_via_hash!(bool);
2940 impl_dep_tracking_hash_via_hash!(usize);
2941 impl_dep_tracking_hash_via_hash!(u64);
2942 impl_dep_tracking_hash_via_hash!(String);
2943 impl_dep_tracking_hash_via_hash!(PathBuf);
2944 impl_dep_tracking_hash_via_hash!(lint::Level);
2945 impl_dep_tracking_hash_via_hash!(Option<bool>);
2946 impl_dep_tracking_hash_via_hash!(Option<usize>);
2947 impl_dep_tracking_hash_via_hash!(Option<String>);
2948 impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
2949 impl_dep_tracking_hash_via_hash!(Option<Vec<String>>);
2950 impl_dep_tracking_hash_via_hash!(Option<MergeFunctions>);
2951 impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
2952 impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
2953 impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
2954 impl_dep_tracking_hash_via_hash!(Option<PathBuf>);
2955 impl_dep_tracking_hash_via_hash!(Option<cstore::NativeLibraryKind>);
2956 impl_dep_tracking_hash_via_hash!(CrateType);
2957 impl_dep_tracking_hash_via_hash!(MergeFunctions);
2958 impl_dep_tracking_hash_via_hash!(PanicStrategy);
2959 impl_dep_tracking_hash_via_hash!(RelroLevel);
2960 impl_dep_tracking_hash_via_hash!(Passes);
2961 impl_dep_tracking_hash_via_hash!(OptLevel);
2962 impl_dep_tracking_hash_via_hash!(LtoCli);
2963 impl_dep_tracking_hash_via_hash!(DebugInfo);
2964 impl_dep_tracking_hash_via_hash!(UnstableFeatures);
2965 impl_dep_tracking_hash_via_hash!(OutputTypes);
2966 impl_dep_tracking_hash_via_hash!(cstore::NativeLibraryKind);
2967 impl_dep_tracking_hash_via_hash!(Sanitizer);
2968 impl_dep_tracking_hash_via_hash!(Option<Sanitizer>);
2969 impl_dep_tracking_hash_via_hash!(TargetTriple);
2970 impl_dep_tracking_hash_via_hash!(Edition);
2971 impl_dep_tracking_hash_via_hash!(LinkerPluginLto);
2972 impl_dep_tracking_hash_via_hash!(SwitchWithOptPath);
2973 impl_dep_tracking_hash_via_hash!(SymbolManglingVersion);
2975 impl_dep_tracking_hash_for_sortable_vec_of!(String);
2976 impl_dep_tracking_hash_for_sortable_vec_of!(PathBuf);
2977 impl_dep_tracking_hash_for_sortable_vec_of!(CrateType);
2978 impl_dep_tracking_hash_for_sortable_vec_of!((String, lint::Level));
2979 impl_dep_tracking_hash_for_sortable_vec_of!((
2982 Option<cstore::NativeLibraryKind>
2984 impl_dep_tracking_hash_for_sortable_vec_of!((String, u64));
2986 impl<T1, T2> DepTrackingHash for (T1, T2)
2988 T1: DepTrackingHash,
2989 T2: DepTrackingHash,
2991 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
2992 Hash::hash(&0, hasher);
2993 DepTrackingHash::hash(&self.0, hasher, error_format);
2994 Hash::hash(&1, hasher);
2995 DepTrackingHash::hash(&self.1, hasher, error_format);
2999 impl<T1, T2, T3> DepTrackingHash for (T1, T2, T3)
3001 T1: DepTrackingHash,
3002 T2: DepTrackingHash,
3003 T3: DepTrackingHash,
3005 fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
3006 Hash::hash(&0, hasher);
3007 DepTrackingHash::hash(&self.0, hasher, error_format);
3008 Hash::hash(&1, hasher);
3009 DepTrackingHash::hash(&self.1, hasher, error_format);
3010 Hash::hash(&2, hasher);
3011 DepTrackingHash::hash(&self.2, hasher, error_format);
3015 // This is a stable hash because BTreeMap is a sorted container
3017 sub_hashes: BTreeMap<&'static str, &dyn DepTrackingHash>,
3018 hasher: &mut DefaultHasher,
3019 error_format: ErrorOutputType,
3021 for (key, sub_hash) in sub_hashes {
3022 // Using Hash::hash() instead of DepTrackingHash::hash() is fine for
3023 // the keys, as they are just plain strings
3024 Hash::hash(&key.len(), hasher);
3025 Hash::hash(key, hasher);
3026 sub_hash.hash(hasher, error_format);