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::OptLevel::*;
18 pub use self::DebugInfoLevel::*;
20 use session::{early_error, early_warn, Session};
21 use session::search_paths::SearchPaths;
23 use rustc_back::target::Target;
27 use syntax::ast::{self, IntTy, UintTy};
29 use syntax::attr::AttrMetaMethods;
30 use syntax::diagnostic::{ColorConfig, Auto, Always, Never, SpanHandler};
32 use syntax::parse::token::InternedString;
33 use syntax::feature_gate::UnstableFeatures;
36 use std::collections::HashMap;
39 use std::path::PathBuf;
46 pub uint_type: UintTy,
49 #[derive(Clone, Copy, PartialEq)]
57 #[derive(Clone, Copy, PartialEq)]
58 pub enum DebugInfoLevel {
64 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
75 fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
78 OutputType::DepInfo => true,
80 OutputType::Assembly |
81 OutputType::LlvmAssembly |
82 OutputType::Object => false,
86 fn shorthand(&self) -> &'static str {
88 OutputType::Bitcode => "llvm-bc",
89 OutputType::Assembly => "asm",
90 OutputType::LlvmAssembly => "llvm-ir",
91 OutputType::Object => "obj",
92 OutputType::Exe => "link",
93 OutputType::DepInfo => "dep-info",
100 // The crate config requested for the session, which may be combined
101 // with additional crate configurations during the compile process
102 pub crate_types: Vec<CrateType>,
105 pub optimize: OptLevel,
106 pub debug_assertions: bool,
107 pub debuginfo: DebugInfoLevel,
108 pub lint_opts: Vec<(String, lint::Level)>,
109 pub lint_cap: Option<lint::Level>,
110 pub describe_lints: bool,
111 pub output_types: HashMap<OutputType, Option<PathBuf>>,
112 // This was mutable for rustpkg, which updates search paths based on the
113 // parsed code. It remains mutable in case its replacements wants to use
115 pub search_paths: SearchPaths,
116 pub libs: Vec<(String, cstore::NativeLibraryKind)>,
117 pub maybe_sysroot: Option<PathBuf>,
118 pub target_triple: String,
119 // User-specified cfg meta items. The compiler itself will add additional
120 // items to the crate config, and during parsing the entire crate config
121 // will be added to the crate AST node. This should not be used for
122 // anything except building the full crate config prior to parsing.
123 pub cfg: ast::CrateConfig,
125 pub parse_only: bool,
127 pub treat_err_as_bug: bool,
128 pub no_analysis: bool,
129 pub debugging_opts: DebuggingOptions,
130 pub prints: Vec<PrintRequest>,
131 pub cg: CodegenOptions,
132 pub color: ColorConfig,
133 pub show_span: Option<String>,
134 pub externs: HashMap<String, Vec<String>>,
135 pub crate_name: Option<String>,
136 /// An optional name to use as the crate for std during std injection,
137 /// written `extern crate std = "name"`. Default to "std". Used by
138 /// out-of-tree drivers.
139 pub alt_std_name: Option<String>,
140 /// Indicates how the compiler should treat unstable features
141 pub unstable_features: UnstableFeatures
144 #[derive(Clone, PartialEq, Eq)]
145 pub enum PrintRequest {
152 /// Load source from file
154 /// The string is the source
159 pub fn filestem(&self) -> String {
161 Input::File(ref ifile) => ifile.file_stem().unwrap()
162 .to_str().unwrap().to_string(),
163 Input::Str(_) => "rust_out".to_string(),
169 pub struct OutputFilenames {
170 pub out_directory: PathBuf,
171 pub out_filestem: String,
172 pub single_output_file: Option<PathBuf>,
174 pub outputs: HashMap<OutputType, Option<PathBuf>>,
177 impl OutputFilenames {
178 pub fn path(&self, flavor: OutputType) -> PathBuf {
179 self.outputs.get(&flavor).and_then(|p| p.to_owned())
180 .or_else(|| self.single_output_file.clone())
181 .unwrap_or_else(|| self.temp_path(flavor))
184 pub fn temp_path(&self, flavor: OutputType) -> PathBuf {
185 let base = self.out_directory.join(&self.filestem());
187 OutputType::Bitcode => base.with_extension("bc"),
188 OutputType::Assembly => base.with_extension("s"),
189 OutputType::LlvmAssembly => base.with_extension("ll"),
190 OutputType::Object => base.with_extension("o"),
191 OutputType::DepInfo => base.with_extension("d"),
192 OutputType::Exe => base,
196 pub fn with_extension(&self, extension: &str) -> PathBuf {
197 self.out_directory.join(&self.filestem()).with_extension(extension)
200 pub fn filestem(&self) -> String {
201 format!("{}{}", self.out_filestem, self.extra)
205 pub fn host_triple() -> &'static str {
206 // Get the host triple out of the build environment. This ensures that our
207 // idea of the host triple is the same as for the set of libraries we've
208 // actually built. We can't just take LLVM's host triple because they
209 // normalize all ix86 architectures to i386.
211 // Instead of grabbing the host triple (for the current host), we grab (at
212 // compile time) the target triple that this rustc is built with and
213 // calling that (at runtime) the host triple.
214 (option_env!("CFG_COMPILER_HOST_TRIPLE")).
215 expect("CFG_COMPILER_HOST_TRIPLE")
218 /// Some reasonable defaults
219 pub fn basic_options() -> Options {
221 crate_types: Vec::new(),
224 debuginfo: NoDebugInfo,
225 lint_opts: Vec::new(),
227 describe_lints: false,
228 output_types: HashMap::new(),
229 search_paths: SearchPaths::new(),
231 target_triple: host_triple().to_string(),
236 treat_err_as_bug: false,
238 debugging_opts: basic_debugging_options(),
240 cg: basic_codegen_options(),
243 externs: HashMap::new(),
247 unstable_features: UnstableFeatures::Disallow,
248 debug_assertions: true,
252 // The type of entry function, so
253 // users can have their own entry
254 // functions that don't start a
256 #[derive(Copy, Clone, PartialEq)]
257 pub enum EntryFnType {
263 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
273 SomePasses(Vec<String>),
278 pub fn is_empty(&self) -> bool {
280 SomePasses(ref v) => v.is_empty(),
286 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
287 /// at once. The goal of this macro is to define an interface that can be
288 /// programmatically used by the option parser in order to initialize the struct
289 /// without hardcoding field names all over the place.
291 /// The goal is to invoke this macro once with the correct fields, and then this
292 /// macro generates all necessary code. The main gotcha of this macro is the
293 /// cgsetters module which is a bunch of generated code to parse an option into
294 /// its respective field in the struct. There are a few hand-written parsers for
295 /// parsing specific types of values in this module.
296 macro_rules! options {
297 ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
298 $buildfn:ident, $prefix:expr, $outputname:expr,
299 $stat:ident, $mod_desc:ident, $mod_set:ident,
300 $($opt:ident : $t:ty = ($init:expr, $parse:ident, $desc:expr)),* ,) =>
303 pub struct $struct_name { $(pub $opt: $t),* }
305 pub fn $defaultfn() -> $struct_name {
306 $struct_name { $($opt: $init),* }
309 pub fn $buildfn(matches: &getopts::Matches, color: ColorConfig) -> $struct_name
311 let mut op = $defaultfn();
312 for option in matches.opt_strs($prefix) {
313 let mut iter = option.splitn(2, '=');
314 let key = iter.next().unwrap();
315 let value = iter.next();
316 let option_to_lookup = key.replace("-", "_");
317 let mut found = false;
318 for &(candidate, setter, opt_type_desc, _) in $stat {
319 if option_to_lookup != candidate { continue }
320 if !setter(&mut op, value) {
321 match (value, opt_type_desc) {
322 (Some(..), None) => {
323 early_error(color, &format!("{} option `{}` takes no \
324 value", $outputname, key))
326 (None, Some(type_desc)) => {
327 early_error(color, &format!("{0} option `{1}` requires \
328 {2} ({3} {1}=<value>)",
332 (Some(value), Some(type_desc)) => {
333 early_error(color, &format!("incorrect value `{}` for {} \
334 option `{}` - {} was expected",
338 (None, None) => unreachable!()
345 early_error(color, &format!("unknown {} option: `{}`",
352 pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
353 pub const $stat: &'static [(&'static str, $setter_name,
354 Option<&'static str>, &'static str)] =
355 &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
357 #[allow(non_upper_case_globals, dead_code)]
359 pub const parse_bool: Option<&'static str> = None;
360 pub const parse_opt_bool: Option<&'static str> =
361 Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
362 pub const parse_string: Option<&'static str> = Some("a string");
363 pub const parse_opt_string: Option<&'static str> = Some("a string");
364 pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
365 pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
366 pub const parse_uint: Option<&'static str> = Some("a number");
367 pub const parse_passes: Option<&'static str> =
368 Some("a space-separated list of passes, or `all`");
369 pub const parse_opt_uint: Option<&'static str> =
375 use super::{$struct_name, Passes, SomePasses, AllPasses};
378 pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
379 $parse(&mut cg.$opt, v)
383 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
386 None => { *slot = true; true }
390 fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
394 "n" | "no" | "off" => {
397 "y" | "yes" | "on" => {
400 _ => { return false; }
405 None => { *slot = Some(true); true }
409 fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
411 Some(s) => { *slot = Some(s.to_string()); true },
416 fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
418 Some(s) => { *slot = s.to_string(); true },
423 fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
427 for s in s.split_whitespace() {
428 slot.push(s.to_string());
436 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
440 let v = s.split_whitespace().map(|s| s.to_string()).collect();
448 fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
449 match v.and_then(|s| s.parse().ok()) {
450 Some(i) => { *slot = i; true },
455 fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
457 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
458 None => { *slot = None; true }
462 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
469 let mut passes = vec!();
470 if parse_list(&mut passes, v) {
471 *slot = SomePasses(passes);
482 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
483 build_codegen_options, "C", "codegen",
484 CG_OPTIONS, cg_type_desc, cgsetters,
485 ar: Option<String> = (None, parse_opt_string,
486 "tool to assemble archives with"),
487 linker: Option<String> = (None, parse_opt_string,
488 "system linker to link outputs with"),
489 link_args: Option<Vec<String>> = (None, parse_opt_list,
490 "extra arguments to pass to the linker (space separated)"),
491 lto: bool = (false, parse_bool,
492 "perform LLVM link-time optimizations"),
493 target_cpu: Option<String> = (None, parse_opt_string,
494 "select target processor (llc -mcpu=help for details)"),
495 target_feature: String = ("".to_string(), parse_string,
496 "target specific attributes (llc -mattr=help for details)"),
497 passes: Vec<String> = (Vec::new(), parse_list,
498 "a list of extra LLVM passes to run (space separated)"),
499 llvm_args: Vec<String> = (Vec::new(), parse_list,
500 "a list of arguments to pass to llvm (space separated)"),
501 save_temps: bool = (false, parse_bool,
502 "save all temporary output files during compilation"),
503 rpath: bool = (false, parse_bool,
504 "set rpath values in libs/exes"),
505 no_prepopulate_passes: bool = (false, parse_bool,
506 "don't pre-populate the pass manager with a list of passes"),
507 no_vectorize_loops: bool = (false, parse_bool,
508 "don't run the loop vectorization optimization passes"),
509 no_vectorize_slp: bool = (false, parse_bool,
510 "don't run LLVM's SLP vectorization pass"),
511 soft_float: bool = (false, parse_bool,
512 "generate software floating point library calls"),
513 prefer_dynamic: bool = (false, parse_bool,
514 "prefer dynamic linking to static linking"),
515 no_integrated_as: bool = (false, parse_bool,
516 "use an external assembler rather than LLVM's integrated one"),
517 no_redzone: Option<bool> = (None, parse_opt_bool,
518 "disable the use of the redzone"),
519 relocation_model: Option<String> = (None, parse_opt_string,
520 "choose the relocation model to use (llc -relocation-model for details)"),
521 code_model: Option<String> = (None, parse_opt_string,
522 "choose the code model to use (llc -code-model for details)"),
523 metadata: Vec<String> = (Vec::new(), parse_list,
524 "metadata to mangle symbol names with"),
525 extra_filename: String = ("".to_string(), parse_string,
526 "extra data to put in each output filename"),
527 codegen_units: usize = (1, parse_uint,
528 "divide crate into N units to optimize in parallel"),
529 remark: Passes = (SomePasses(Vec::new()), parse_passes,
530 "print remarks for these optimization passes (space separated, or \"all\")"),
531 no_stack_check: bool = (false, parse_bool,
532 "disable checks for stack exhaustion (a memory-safety hazard!)"),
533 debuginfo: Option<usize> = (None, parse_opt_uint,
534 "debug info emission level, 0 = no debug info, 1 = line tables only, \
535 2 = full debug info with variable and type information"),
536 opt_level: Option<usize> = (None, parse_opt_uint,
537 "optimize with possible levels 0-3"),
538 debug_assertions: Option<bool> = (None, parse_opt_bool,
539 "explicitly enable the cfg(debug_assertions) directive"),
540 inline_threshold: Option<usize> = (None, parse_opt_uint,
541 "set the inlining threshold for"),
545 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
546 build_debugging_options, "Z", "debugging",
547 DB_OPTIONS, db_type_desc, dbsetters,
548 verbose: bool = (false, parse_bool,
549 "in general, enable more debug printouts"),
550 time_passes: bool = (false, parse_bool,
551 "measure time of each rustc pass"),
552 count_llvm_insns: bool = (false, parse_bool,
553 "count where LLVM instrs originate"),
554 time_llvm_passes: bool = (false, parse_bool,
555 "measure time of each LLVM pass"),
556 input_stats: bool = (false, parse_bool,
557 "gather statistics about the input"),
558 trans_stats: bool = (false, parse_bool,
559 "gather trans statistics"),
560 asm_comments: bool = (false, parse_bool,
561 "generate comments into the assembly (may change behavior)"),
562 no_verify: bool = (false, parse_bool,
563 "skip LLVM verification"),
564 borrowck_stats: bool = (false, parse_bool,
565 "gather borrowck statistics"),
566 no_landing_pads: bool = (false, parse_bool,
567 "omit landing pads for unwinding"),
568 debug_llvm: bool = (false, parse_bool,
569 "enable debug output from LLVM"),
570 count_type_sizes: bool = (false, parse_bool,
571 "count the sizes of aggregate types"),
572 meta_stats: bool = (false, parse_bool,
573 "gather metadata statistics"),
574 print_link_args: bool = (false, parse_bool,
575 "print the arguments passed to the linker"),
576 gc: bool = (false, parse_bool,
577 "garbage collect shared data (experimental)"),
578 print_llvm_passes: bool = (false, parse_bool,
579 "prints the llvm optimization passes being run"),
580 ast_json: bool = (false, parse_bool,
581 "print the AST as JSON and halt"),
582 ast_json_noexpand: bool = (false, parse_bool,
583 "print the pre-expansion AST as JSON and halt"),
584 ls: bool = (false, parse_bool,
585 "list the symbols defined by a library crate"),
586 save_analysis: bool = (false, parse_bool,
587 "write syntax and type analysis information in addition to normal output"),
588 print_move_fragments: bool = (false, parse_bool,
589 "print out move-fragment data for every fn"),
590 flowgraph_print_loans: bool = (false, parse_bool,
591 "include loan analysis data in --unpretty flowgraph output"),
592 flowgraph_print_moves: bool = (false, parse_bool,
593 "include move analysis data in --unpretty flowgraph output"),
594 flowgraph_print_assigns: bool = (false, parse_bool,
595 "include assignment analysis data in --unpretty flowgraph output"),
596 flowgraph_print_all: bool = (false, parse_bool,
597 "include all dataflow analysis data in --unpretty flowgraph output"),
598 print_region_graph: bool = (false, parse_bool,
599 "prints region inference graph. \
600 Use with RUST_REGION_GRAPH=help for more info"),
601 parse_only: bool = (false, parse_bool,
602 "parse only; do not compile, assemble, or link"),
603 no_trans: bool = (false, parse_bool,
604 "run all passes except translation; no output"),
605 treat_err_as_bug: bool = (false, parse_bool,
606 "treat all errors that occur as bugs"),
607 no_analysis: bool = (false, parse_bool,
608 "parse and expand the source, but run no analysis"),
609 extra_plugins: Vec<String> = (Vec::new(), parse_list,
610 "load extra plugins"),
611 unstable_options: bool = (false, parse_bool,
612 "adds unstable command line options to rustc interface"),
613 print_enum_sizes: bool = (false, parse_bool,
614 "print the size of enums and their variants"),
615 force_overflow_checks: Option<bool> = (None, parse_opt_bool,
616 "force overflow checks on or off"),
617 force_dropflag_checks: Option<bool> = (None, parse_opt_bool,
618 "force drop flag checks on or off"),
619 trace_macros: bool = (false, parse_bool,
620 "for every macro invocation, print its name and arguments"),
621 enable_nonzeroing_move_hints: bool = (false, parse_bool,
622 "force nonzeroing move optimization on"),
623 keep_mtwt_tables: bool = (false, parse_bool,
624 "don't clear the resolution tables after analysis"),
627 pub fn default_lib_output() -> CrateType {
631 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
632 use syntax::parse::token::intern_and_get_ident as intern;
634 let end = &sess.target.target.target_endian;
635 let arch = &sess.target.target.arch;
636 let wordsz = &sess.target.target.target_pointer_width;
637 let os = &sess.target.target.target_os;
638 let env = &sess.target.target.target_env;
639 let vendor = &sess.target.target.target_vendor;
641 let fam = if let Some(ref fam) = sess.target.target.options.target_family {
643 } else if sess.target.target.options.is_like_windows {
644 InternedString::new("windows")
646 InternedString::new("unix")
649 let mk = attr::mk_name_value_item_str;
650 let mut ret = vec![ // Target bindings.
651 mk(InternedString::new("target_os"), intern(os)),
652 mk(InternedString::new("target_family"), fam.clone()),
653 mk(InternedString::new("target_arch"), intern(arch)),
654 mk(InternedString::new("target_endian"), intern(end)),
655 mk(InternedString::new("target_pointer_width"), intern(wordsz)),
656 mk(InternedString::new("target_env"), intern(env)),
657 mk(InternedString::new("target_vendor"), intern(vendor)),
660 "windows" | "unix" => ret.push(attr::mk_word_item(fam)),
663 if sess.opts.debug_assertions {
664 ret.push(attr::mk_word_item(InternedString::new("debug_assertions")));
669 pub fn append_configuration(cfg: &mut ast::CrateConfig,
670 name: InternedString) {
671 if !cfg.iter().any(|mi| mi.name() == name) {
672 cfg.push(attr::mk_word_item(name))
676 pub fn build_configuration(sess: &Session) -> ast::CrateConfig {
677 // Combine the configuration requested by the session (command line) with
678 // some default and generated configuration items
679 let default_cfg = default_configuration(sess);
680 let mut user_cfg = sess.opts.cfg.clone();
681 // If the user wants a test runner, then add the test cfg
683 append_configuration(&mut user_cfg, InternedString::new("test"))
685 let mut v = user_cfg.into_iter().collect::<Vec<_>>();
686 v.extend_from_slice(&default_cfg[..]);
690 pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config {
691 let target = match Target::search(&opts.target_triple) {
694 panic!(sp.handler().fatal(&format!("Error loading target specification: {}", e)));
698 let (int_type, uint_type) = match &target.target_pointer_width[..] {
699 "32" => (ast::TyI32, ast::TyU32),
700 "64" => (ast::TyI64, ast::TyU64),
701 w => panic!(sp.handler().fatal(&format!("target specification was invalid: \
702 unrecognized target-pointer-width {}", w))),
708 uint_type: uint_type,
712 /// Returns the "short" subset of the stable rustc command line options.
713 pub fn short_optgroups() -> Vec<getopts::OptGroup> {
714 rustc_short_optgroups().into_iter()
715 .filter(|g|g.is_stable())
720 /// Returns all of the stable rustc command line options.
721 pub fn optgroups() -> Vec<getopts::OptGroup> {
722 rustc_optgroups().into_iter()
723 .filter(|g|g.is_stable())
728 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
729 pub enum OptionStability { Stable, Unstable }
731 #[derive(Clone, PartialEq, Eq)]
732 pub struct RustcOptGroup {
733 pub opt_group: getopts::OptGroup,
734 pub stability: OptionStability,
738 pub fn is_stable(&self) -> bool {
739 self.stability == OptionStability::Stable
742 fn stable(g: getopts::OptGroup) -> RustcOptGroup {
743 RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
746 fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
747 RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
751 // The `opt` local module holds wrappers around the `getopts` API that
752 // adds extra rustc-specific metadata to each option; such metadata
753 // is exposed by . The public
754 // functions below ending with `_u` are the functions that return
755 // *unstable* options, i.e. options that are only enabled when the
756 // user also passes the `-Z unstable-options` debugging flag.
758 // The `fn opt_u` etc below are written so that we can use them
759 // in the future; do not warn about them not being used right now.
763 use super::RustcOptGroup;
765 pub type R = RustcOptGroup;
766 pub type S<'a> = &'a str;
768 fn stable(g: getopts::OptGroup) -> R { RustcOptGroup::stable(g) }
769 fn unstable(g: getopts::OptGroup) -> R { RustcOptGroup::unstable(g) }
771 // FIXME (pnkfelix): We default to stable since the current set of
772 // options is defacto stable. However, it would be good to revise the
773 // code so that a stable option is the thing that takes extra effort
776 pub fn opt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optopt(a, b, c, d)) }
777 pub fn multi(a: S, b: S, c: S, d: S) -> R { stable(getopts::optmulti(a, b, c, d)) }
778 pub fn flag(a: S, b: S, c: S) -> R { stable(getopts::optflag(a, b, c)) }
779 pub fn flagopt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optflagopt(a, b, c, d)) }
780 pub fn flagmulti(a: S, b: S, c: S) -> R { stable(getopts::optflagmulti(a, b, c)) }
783 pub fn opt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optopt(a, b, c, d)) }
784 pub fn multi_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optmulti(a, b, c, d)) }
785 pub fn flag_u(a: S, b: S, c: S) -> R { unstable(getopts::optflag(a, b, c)) }
786 pub fn flagopt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optflagopt(a, b, c, d)) }
787 pub fn flagmulti_u(a: S, b: S, c: S) -> R { unstable(getopts::optflagmulti(a, b, c)) }
790 /// Returns the "short" subset of the rustc command line options,
791 /// including metadata for each option, such as whether the option is
792 /// part of the stable long-term interface for rustc.
793 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
795 opt::flag("h", "help", "Display this message"),
796 opt::multi("", "cfg", "Configure the compilation environment", "SPEC"),
797 opt::multi("L", "", "Add a directory to the library search path",
799 opt::multi("l", "", "Link the generated crate(s) to the specified native
800 library NAME. The optional KIND can be one of,
801 static, dylib, or framework. If omitted, dylib is
802 assumed.", "[KIND=]NAME"),
803 opt::multi("", "crate-type", "Comma separated list of types of crates
804 for the compiler to emit",
805 "[bin|lib|rlib|dylib|staticlib]"),
806 opt::opt("", "crate-name", "Specify the name of the crate being built",
808 opt::multi("", "emit", "Comma separated list of types of output for \
809 the compiler to emit",
810 "[asm|llvm-bc|llvm-ir|obj|link|dep-info]"),
811 opt::multi("", "print", "Comma separated list of compiler information to \
813 "[crate-name|file-names|sysroot]"),
814 opt::flagmulti("g", "", "Equivalent to -C debuginfo=2"),
815 opt::flagmulti("O", "", "Equivalent to -C opt-level=2"),
816 opt::opt("o", "", "Write output to <filename>", "FILENAME"),
817 opt::opt("", "out-dir", "Write output to compiler-chosen filename \
819 opt::opt("", "explain", "Provide a detailed explanation of an error \
821 opt::flag("", "test", "Build a test harness"),
822 opt::opt("", "target", "Target triple cpu-manufacturer-kernel[-os] \
823 to compile for (see chapter 3.4 of \
824 http://www.sourceware.org/autobook/
827 opt::multi("W", "warn", "Set lint warnings", "OPT"),
828 opt::multi("A", "allow", "Set lint allowed", "OPT"),
829 opt::multi("D", "deny", "Set lint denied", "OPT"),
830 opt::multi("F", "forbid", "Set lint forbidden", "OPT"),
831 opt::multi("", "cap-lints", "Set the most restrictive lint level. \
832 More restrictive lints are capped at this \
834 opt::multi("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
835 opt::flag("V", "version", "Print version info and exit"),
836 opt::flag("v", "verbose", "Use verbose output"),
840 /// Returns all rustc command line options, including metadata for
841 /// each option, such as whether the option is part of the stable
842 /// long-term interface for rustc.
843 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
844 let mut opts = rustc_short_optgroups();
845 opts.extend_from_slice(&[
846 opt::multi("", "extern", "Specify where an external rust library is \
849 opt::opt("", "sysroot", "Override the system root", "PATH"),
850 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
851 opt::opt("", "color", "Configure coloring of output:
852 auto = colorize, if output goes to a tty (default);
853 always = always colorize output;
854 never = never colorize output", "auto|always|never"),
856 opt::flagopt_u("", "pretty",
857 "Pretty-print the input instead of compiling;
858 valid types are: `normal` (un-annotated source),
859 `expanded` (crates expanded), or
860 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
862 opt::flagopt_u("", "unpretty",
863 "Present the input source, unstable (and less-pretty) variants;
864 valid types are any of the types for `--pretty`, as well as:
865 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
866 `everybody_loops` (all function bodies replaced with `loop {}`),
867 `hir` (the HIR), `hir,identified`, or
868 `hir,typed` (HIR with types for each node).",
870 opt::opt_u("", "show-span", "Show spans for compiler debugging", "expr|pat|ty"),
875 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
876 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
877 cfgspecs.into_iter().map(|s| {
878 parse::parse_meta_from_source_str("cfgspec".to_string(),
881 &parse::ParseSess::new())
882 }).collect::<ast::CrateConfig>()
885 pub fn build_session_options(matches: &getopts::Matches) -> Options {
886 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
887 Some("auto") => Auto,
888 Some("always") => Always,
889 Some("never") => Never,
894 early_error(Auto, &format!("argument for --color must be auto, always \
895 or never (instead was `{}`)",
900 let unparsed_crate_types = matches.opt_strs("crate-type");
901 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
902 .unwrap_or_else(|e| early_error(color, &e[..]));
904 let mut lint_opts = vec!();
905 let mut describe_lints = false;
907 for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
908 for lint_name in matches.opt_strs(level.as_str()) {
909 if lint_name == "help" {
910 describe_lints = true;
912 lint_opts.push((lint_name.replace("-", "_"), level));
917 let lint_cap = matches.opt_str("cap-lints").map(|cap| {
918 lint::Level::from_str(&cap).unwrap_or_else(|| {
919 early_error(color, &format!("unknown lint level: `{}`", cap))
923 let debugging_opts = build_debugging_options(matches, color);
925 let parse_only = debugging_opts.parse_only;
926 let no_trans = debugging_opts.no_trans;
927 let treat_err_as_bug = debugging_opts.treat_err_as_bug;
928 let no_analysis = debugging_opts.no_analysis;
930 if debugging_opts.debug_llvm {
931 unsafe { llvm::LLVMSetDebug(1); }
934 let mut output_types = HashMap::new();
935 if !debugging_opts.parse_only && !no_trans {
936 for list in matches.opt_strs("emit") {
937 for output_type in list.split(',') {
938 let mut parts = output_type.splitn(2, '=');
939 let output_type = match parts.next().unwrap() {
940 "asm" => OutputType::Assembly,
941 "llvm-ir" => OutputType::LlvmAssembly,
942 "llvm-bc" => OutputType::Bitcode,
943 "obj" => OutputType::Object,
944 "link" => OutputType::Exe,
945 "dep-info" => OutputType::DepInfo,
947 early_error(color, &format!("unknown emission type: `{}`",
951 let path = parts.next().map(PathBuf::from);
952 output_types.insert(output_type, path);
956 if output_types.is_empty() {
957 output_types.insert(OutputType::Exe, None);
960 let mut cg = build_codegen_options(matches, color);
962 // Issue #30063: if user requests llvm-related output to one
963 // particular path, disable codegen-units.
964 if matches.opt_present("o") && cg.codegen_units != 1 {
965 let incompatible: Vec<_> = output_types.iter()
966 .map(|ot_path| ot_path.0)
968 !ot.is_compatible_with_codegen_units_and_single_output_file()
970 if !incompatible.is_empty() {
971 for ot in &incompatible {
972 early_warn(color, &format!("--emit={} with -o incompatible with \
973 -C codegen-units=N for N > 1",
976 early_warn(color, "resetting to default -C codegen-units=1");
977 cg.codegen_units = 1;
983 let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
984 let target = matches.opt_str("target").unwrap_or(
985 host_triple().to_string());
987 if matches.opt_present("O") {
988 if cg.opt_level.is_some() {
989 early_error(color, "-O and -C opt-level both provided");
998 Some(3) => Aggressive,
1000 early_error(color, &format!("optimization level needs to be \
1001 between 0-3 (instead was `{}`)",
1007 let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == No);
1008 let gc = debugging_opts.gc;
1009 let debuginfo = if matches.opt_present("g") {
1010 if cg.debuginfo.is_some() {
1011 early_error(color, "-g and -C debuginfo both provided");
1015 match cg.debuginfo {
1016 None | Some(0) => NoDebugInfo,
1017 Some(1) => LimitedDebugInfo,
1018 Some(2) => FullDebugInfo,
1020 early_error(color, &format!("debug info level needs to be between \
1021 0-2 (instead was `{}`)",
1027 let mut search_paths = SearchPaths::new();
1028 for s in &matches.opt_strs("L") {
1029 search_paths.add_path(&s[..], color);
1032 let libs = matches.opt_strs("l").into_iter().map(|s| {
1033 let mut parts = s.splitn(2, '=');
1034 let kind = parts.next().unwrap();
1035 let (name, kind) = match (parts.next(), kind) {
1037 (Some(name), "dylib") => (name, cstore::NativeUnknown),
1038 (Some(name), "framework") => (name, cstore::NativeFramework),
1039 (Some(name), "static") => (name, cstore::NativeStatic),
1041 early_error(color, &format!("unknown library kind `{}`, expected \
1042 one of dylib, framework, or static",
1046 (name.to_string(), kind)
1049 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
1050 let test = matches.opt_present("test");
1052 let prints = matches.opt_strs("print").into_iter().map(|s| {
1054 "crate-name" => PrintRequest::CrateName,
1055 "file-names" => PrintRequest::FileNames,
1056 "sysroot" => PrintRequest::Sysroot,
1058 early_error(color, &format!("unknown print request `{}`", req))
1061 }).collect::<Vec<_>>();
1063 if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
1064 early_warn(color, "-C remark will not show source locations without \
1068 let mut externs = HashMap::new();
1069 for arg in &matches.opt_strs("extern") {
1070 let mut parts = arg.splitn(2, '=');
1071 let name = match parts.next() {
1073 None => early_error(color, "--extern value must not be empty"),
1075 let location = match parts.next() {
1077 None => early_error(color, "--extern value must be of the format `foo=bar`"),
1080 externs.entry(name.to_string()).or_insert(vec![]).push(location.to_string());
1083 let crate_name = matches.opt_str("crate-name");
1086 crate_types: crate_types,
1088 optimize: opt_level,
1089 debuginfo: debuginfo,
1090 lint_opts: lint_opts,
1092 describe_lints: describe_lints,
1093 output_types: output_types,
1094 search_paths: search_paths,
1095 maybe_sysroot: sysroot_opt,
1096 target_triple: target,
1099 parse_only: parse_only,
1101 treat_err_as_bug: treat_err_as_bug,
1102 no_analysis: no_analysis,
1103 debugging_opts: debugging_opts,
1109 crate_name: crate_name,
1112 unstable_features: get_unstable_features_setting(),
1113 debug_assertions: debug_assertions,
1117 pub fn get_unstable_features_setting() -> UnstableFeatures {
1118 // Whether this is a feature-staged build, i.e. on the beta or stable channel
1119 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
1120 // The secret key needed to get through the rustc build itself by
1121 // subverting the unstable features lints
1122 let bootstrap_secret_key = option_env!("CFG_BOOTSTRAP_KEY");
1123 // The matching key to the above, only known by the build system
1124 let bootstrap_provided_key = env::var("RUSTC_BOOTSTRAP_KEY").ok();
1125 match (disable_unstable_features, bootstrap_secret_key, bootstrap_provided_key) {
1126 (_, Some(ref s), Some(ref p)) if s == p => UnstableFeatures::Cheat,
1127 (true, _, _) => UnstableFeatures::Disallow,
1128 (false, _, _) => UnstableFeatures::Allow
1132 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
1134 let mut crate_types: Vec<CrateType> = Vec::new();
1135 for unparsed_crate_type in &list_list {
1136 for part in unparsed_crate_type.split(',') {
1137 let new_part = match part {
1138 "lib" => default_lib_output(),
1139 "rlib" => CrateTypeRlib,
1140 "staticlib" => CrateTypeStaticlib,
1141 "dylib" => CrateTypeDylib,
1142 "bin" => CrateTypeExecutable,
1144 return Err(format!("unknown crate type: `{}`",
1148 if !crate_types.contains(&new_part) {
1149 crate_types.push(new_part)
1154 return Ok(crate_types);
1157 impl fmt::Display for CrateType {
1158 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1160 CrateTypeExecutable => "bin".fmt(f),
1161 CrateTypeDylib => "dylib".fmt(f),
1162 CrateTypeRlib => "rlib".fmt(f),
1163 CrateTypeStaticlib => "staticlib".fmt(f)
1170 use middle::cstore::DummyCrateStore;
1171 use session::config::{build_configuration, optgroups, build_session_options};
1172 use session::build_session;
1175 use getopts::getopts;
1177 use syntax::attr::AttrMetaMethods;
1178 use syntax::diagnostics;
1180 // When the user supplies --test we should implicitly supply --cfg test
1182 fn test_switch_implies_cfg_test() {
1184 &match getopts(&["--test".to_string()], &optgroups()) {
1186 Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
1188 let registry = diagnostics::registry::Registry::new(&[]);
1189 let sessopts = build_session_options(matches);
1190 let sess = build_session(sessopts, None, registry, Rc::new(DummyCrateStore));
1191 let cfg = build_configuration(&sess);
1192 assert!((attr::contains_name(&cfg[..], "test")));
1195 // When the user supplies --test and --cfg test, don't implicitly add
1196 // another --cfg test
1198 fn test_switch_implies_cfg_test_unless_cfg_test() {
1200 &match getopts(&["--test".to_string(), "--cfg=test".to_string()],
1204 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
1207 let registry = diagnostics::registry::Registry::new(&[]);
1208 let sessopts = build_session_options(matches);
1209 let sess = build_session(sessopts, None, registry,
1210 Rc::new(DummyCrateStore));
1211 let cfg = build_configuration(&sess);
1212 let mut test_items = cfg.iter().filter(|m| m.name() == "test");
1213 assert!(test_items.next().is_some());
1214 assert!(test_items.next().is_none());
1218 fn test_can_print_warnings() {
1220 let matches = getopts(&[
1221 "-Awarnings".to_string()
1222 ], &optgroups()).unwrap();
1223 let registry = diagnostics::registry::Registry::new(&[]);
1224 let sessopts = build_session_options(&matches);
1225 let sess = build_session(sessopts, None, registry,
1226 Rc::new(DummyCrateStore));
1227 assert!(!sess.can_print_warnings);
1231 let matches = getopts(&[
1232 "-Awarnings".to_string(),
1233 "-Dwarnings".to_string()
1234 ], &optgroups()).unwrap();
1235 let registry = diagnostics::registry::Registry::new(&[]);
1236 let sessopts = build_session_options(&matches);
1237 let sess = build_session(sessopts, None, registry,
1238 Rc::new(DummyCrateStore));
1239 assert!(sess.can_print_warnings);
1243 let matches = getopts(&[
1244 "-Adead_code".to_string()
1245 ], &optgroups()).unwrap();
1246 let registry = diagnostics::registry::Registry::new(&[]);
1247 let sessopts = build_session_options(&matches);
1248 let sess = build_session(sessopts, None, registry,
1249 Rc::new(DummyCrateStore));
1250 assert!(sess.can_print_warnings);