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::errors::{ColorConfig, Handler};
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 incremental_compilation: bool,
129 pub dump_dep_graph: bool,
130 pub no_analysis: bool,
131 pub debugging_opts: DebuggingOptions,
132 pub prints: Vec<PrintRequest>,
133 pub cg: CodegenOptions,
134 pub color: ColorConfig,
135 pub externs: HashMap<String, Vec<String>>,
136 pub crate_name: Option<String>,
137 /// An optional name to use as the crate for std during std injection,
138 /// written `extern crate std = "name"`. Default to "std". Used by
139 /// out-of-tree drivers.
140 pub alt_std_name: Option<String>,
141 /// Indicates how the compiler should treat unstable features
142 pub unstable_features: UnstableFeatures
145 #[derive(Clone, PartialEq, Eq)]
146 pub enum PrintRequest {
153 /// Load source from file
155 /// The string is the source
160 pub fn filestem(&self) -> String {
162 Input::File(ref ifile) => ifile.file_stem().unwrap()
163 .to_str().unwrap().to_string(),
164 Input::Str(_) => "rust_out".to_string(),
170 pub struct OutputFilenames {
171 pub out_directory: PathBuf,
172 pub out_filestem: String,
173 pub single_output_file: Option<PathBuf>,
175 pub outputs: HashMap<OutputType, Option<PathBuf>>,
178 impl OutputFilenames {
179 pub fn path(&self, flavor: OutputType) -> PathBuf {
180 self.outputs.get(&flavor).and_then(|p| p.to_owned())
181 .or_else(|| self.single_output_file.clone())
182 .unwrap_or_else(|| self.temp_path(flavor))
185 pub fn temp_path(&self, flavor: OutputType) -> PathBuf {
186 let base = self.out_directory.join(&self.filestem());
188 OutputType::Bitcode => base.with_extension("bc"),
189 OutputType::Assembly => base.with_extension("s"),
190 OutputType::LlvmAssembly => base.with_extension("ll"),
191 OutputType::Object => base.with_extension("o"),
192 OutputType::DepInfo => base.with_extension("d"),
193 OutputType::Exe => base,
197 pub fn with_extension(&self, extension: &str) -> PathBuf {
198 self.out_directory.join(&self.filestem()).with_extension(extension)
201 pub fn filestem(&self) -> String {
202 format!("{}{}", self.out_filestem, self.extra)
206 pub fn host_triple() -> &'static str {
207 // Get the host triple out of the build environment. This ensures that our
208 // idea of the host triple is the same as for the set of libraries we've
209 // actually built. We can't just take LLVM's host triple because they
210 // normalize all ix86 architectures to i386.
212 // Instead of grabbing the host triple (for the current host), we grab (at
213 // compile time) the target triple that this rustc is built with and
214 // calling that (at runtime) the host triple.
215 (option_env!("CFG_COMPILER_HOST_TRIPLE")).
216 expect("CFG_COMPILER_HOST_TRIPLE")
219 /// Some reasonable defaults
220 pub fn basic_options() -> Options {
222 crate_types: Vec::new(),
225 debuginfo: NoDebugInfo,
226 lint_opts: Vec::new(),
228 describe_lints: false,
229 output_types: HashMap::new(),
230 search_paths: SearchPaths::new(),
232 target_triple: host_triple().to_string(),
237 treat_err_as_bug: false,
238 incremental_compilation: false,
239 dump_dep_graph: false,
241 debugging_opts: basic_debugging_options(),
243 cg: basic_codegen_options(),
244 color: ColorConfig::Auto,
245 externs: HashMap::new(),
249 unstable_features: UnstableFeatures::Disallow,
250 debug_assertions: true,
254 // The type of entry function, so
255 // users can have their own entry
256 // functions that don't start a
258 #[derive(Copy, Clone, PartialEq)]
259 pub enum EntryFnType {
265 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
275 SomePasses(Vec<String>),
280 pub fn is_empty(&self) -> bool {
282 SomePasses(ref v) => v.is_empty(),
288 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
289 /// at once. The goal of this macro is to define an interface that can be
290 /// programmatically used by the option parser in order to initialize the struct
291 /// without hardcoding field names all over the place.
293 /// The goal is to invoke this macro once with the correct fields, and then this
294 /// macro generates all necessary code. The main gotcha of this macro is the
295 /// cgsetters module which is a bunch of generated code to parse an option into
296 /// its respective field in the struct. There are a few hand-written parsers for
297 /// parsing specific types of values in this module.
298 macro_rules! options {
299 ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
300 $buildfn:ident, $prefix:expr, $outputname:expr,
301 $stat:ident, $mod_desc:ident, $mod_set:ident,
302 $($opt:ident : $t:ty = ($init:expr, $parse:ident, $desc:expr)),* ,) =>
305 pub struct $struct_name { $(pub $opt: $t),* }
307 pub fn $defaultfn() -> $struct_name {
308 $struct_name { $($opt: $init),* }
311 pub fn $buildfn(matches: &getopts::Matches, color: ColorConfig) -> $struct_name
313 let mut op = $defaultfn();
314 for option in matches.opt_strs($prefix) {
315 let mut iter = option.splitn(2, '=');
316 let key = iter.next().unwrap();
317 let value = iter.next();
318 let option_to_lookup = key.replace("-", "_");
319 let mut found = false;
320 for &(candidate, setter, opt_type_desc, _) in $stat {
321 if option_to_lookup != candidate { continue }
322 if !setter(&mut op, value) {
323 match (value, opt_type_desc) {
324 (Some(..), None) => {
325 early_error(color, &format!("{} option `{}` takes no \
326 value", $outputname, key))
328 (None, Some(type_desc)) => {
329 early_error(color, &format!("{0} option `{1}` requires \
330 {2} ({3} {1}=<value>)",
334 (Some(value), Some(type_desc)) => {
335 early_error(color, &format!("incorrect value `{}` for {} \
336 option `{}` - {} was expected",
340 (None, None) => unreachable!()
347 early_error(color, &format!("unknown {} option: `{}`",
354 pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
355 pub const $stat: &'static [(&'static str, $setter_name,
356 Option<&'static str>, &'static str)] =
357 &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
359 #[allow(non_upper_case_globals, dead_code)]
361 pub const parse_bool: Option<&'static str> = None;
362 pub const parse_opt_bool: Option<&'static str> =
363 Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
364 pub const parse_string: Option<&'static str> = Some("a string");
365 pub const parse_opt_string: Option<&'static str> = Some("a string");
366 pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
367 pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
368 pub const parse_uint: Option<&'static str> = Some("a number");
369 pub const parse_passes: Option<&'static str> =
370 Some("a space-separated list of passes, or `all`");
371 pub const parse_opt_uint: Option<&'static str> =
377 use super::{$struct_name, Passes, SomePasses, AllPasses};
380 pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
381 $parse(&mut cg.$opt, v)
385 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
388 None => { *slot = true; true }
392 fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
396 "n" | "no" | "off" => {
399 "y" | "yes" | "on" => {
402 _ => { return false; }
407 None => { *slot = Some(true); true }
411 fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
413 Some(s) => { *slot = Some(s.to_string()); true },
418 fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
420 Some(s) => { *slot = s.to_string(); true },
425 fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
429 for s in s.split_whitespace() {
430 slot.push(s.to_string());
438 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
442 let v = s.split_whitespace().map(|s| s.to_string()).collect();
450 fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
451 match v.and_then(|s| s.parse().ok()) {
452 Some(i) => { *slot = i; true },
457 fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
459 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
460 None => { *slot = None; true }
464 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
471 let mut passes = vec!();
472 if parse_list(&mut passes, v) {
473 *slot = SomePasses(passes);
484 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
485 build_codegen_options, "C", "codegen",
486 CG_OPTIONS, cg_type_desc, cgsetters,
487 ar: Option<String> = (None, parse_opt_string,
488 "tool to assemble archives with"),
489 linker: Option<String> = (None, parse_opt_string,
490 "system linker to link outputs with"),
491 link_args: Option<Vec<String>> = (None, parse_opt_list,
492 "extra arguments to pass to the linker (space separated)"),
493 lto: bool = (false, parse_bool,
494 "perform LLVM link-time optimizations"),
495 target_cpu: Option<String> = (None, parse_opt_string,
496 "select target processor (llc -mcpu=help for details)"),
497 target_feature: String = ("".to_string(), parse_string,
498 "target specific attributes (llc -mattr=help for details)"),
499 passes: Vec<String> = (Vec::new(), parse_list,
500 "a list of extra LLVM passes to run (space separated)"),
501 llvm_args: Vec<String> = (Vec::new(), parse_list,
502 "a list of arguments to pass to llvm (space separated)"),
503 save_temps: bool = (false, parse_bool,
504 "save all temporary output files during compilation"),
505 rpath: bool = (false, parse_bool,
506 "set rpath values in libs/exes"),
507 no_prepopulate_passes: bool = (false, parse_bool,
508 "don't pre-populate the pass manager with a list of passes"),
509 no_vectorize_loops: bool = (false, parse_bool,
510 "don't run the loop vectorization optimization passes"),
511 no_vectorize_slp: bool = (false, parse_bool,
512 "don't run LLVM's SLP vectorization pass"),
513 soft_float: bool = (false, parse_bool,
514 "generate software floating point library calls"),
515 prefer_dynamic: bool = (false, parse_bool,
516 "prefer dynamic linking to static linking"),
517 no_integrated_as: bool = (false, parse_bool,
518 "use an external assembler rather than LLVM's integrated one"),
519 no_redzone: Option<bool> = (None, parse_opt_bool,
520 "disable the use of the redzone"),
521 relocation_model: Option<String> = (None, parse_opt_string,
522 "choose the relocation model to use (llc -relocation-model for details)"),
523 code_model: Option<String> = (None, parse_opt_string,
524 "choose the code model to use (llc -code-model for details)"),
525 metadata: Vec<String> = (Vec::new(), parse_list,
526 "metadata to mangle symbol names with"),
527 extra_filename: String = ("".to_string(), parse_string,
528 "extra data to put in each output filename"),
529 codegen_units: usize = (1, parse_uint,
530 "divide crate into N units to optimize in parallel"),
531 remark: Passes = (SomePasses(Vec::new()), parse_passes,
532 "print remarks for these optimization passes (space separated, or \"all\")"),
533 no_stack_check: bool = (false, parse_bool,
534 "disable checks for stack exhaustion (a memory-safety hazard!)"),
535 debuginfo: Option<usize> = (None, parse_opt_uint,
536 "debug info emission level, 0 = no debug info, 1 = line tables only, \
537 2 = full debug info with variable and type information"),
538 opt_level: Option<usize> = (None, parse_opt_uint,
539 "optimize with possible levels 0-3"),
540 debug_assertions: Option<bool> = (None, parse_opt_bool,
541 "explicitly enable the cfg(debug_assertions) directive"),
542 inline_threshold: Option<usize> = (None, parse_opt_uint,
543 "set the inlining threshold for"),
544 disable_gold: bool = (false, parse_bool,
545 "disable use of the ld.gold linker"),
549 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
550 build_debugging_options, "Z", "debugging",
551 DB_OPTIONS, db_type_desc, dbsetters,
552 verbose: bool = (false, parse_bool,
553 "in general, enable more debug printouts"),
554 time_passes: bool = (false, parse_bool,
555 "measure time of each rustc pass"),
556 count_llvm_insns: bool = (false, parse_bool,
557 "count where LLVM instrs originate"),
558 time_llvm_passes: bool = (false, parse_bool,
559 "measure time of each LLVM pass"),
560 input_stats: bool = (false, parse_bool,
561 "gather statistics about the input"),
562 trans_stats: bool = (false, parse_bool,
563 "gather trans statistics"),
564 asm_comments: bool = (false, parse_bool,
565 "generate comments into the assembly (may change behavior)"),
566 no_verify: bool = (false, parse_bool,
567 "skip LLVM verification"),
568 borrowck_stats: bool = (false, parse_bool,
569 "gather borrowck statistics"),
570 no_landing_pads: bool = (false, parse_bool,
571 "omit landing pads for unwinding"),
572 debug_llvm: bool = (false, parse_bool,
573 "enable debug output from LLVM"),
574 count_type_sizes: bool = (false, parse_bool,
575 "count the sizes of aggregate types"),
576 meta_stats: bool = (false, parse_bool,
577 "gather metadata statistics"),
578 print_link_args: bool = (false, parse_bool,
579 "print the arguments passed to the linker"),
580 gc: bool = (false, parse_bool,
581 "garbage collect shared data (experimental)"),
582 print_llvm_passes: bool = (false, parse_bool,
583 "prints the llvm optimization passes being run"),
584 ast_json: bool = (false, parse_bool,
585 "print the AST as JSON and halt"),
586 ast_json_noexpand: bool = (false, parse_bool,
587 "print the pre-expansion AST as JSON and halt"),
588 ls: bool = (false, parse_bool,
589 "list the symbols defined by a library crate"),
590 save_analysis: bool = (false, parse_bool,
591 "write syntax and type analysis information in addition to normal output"),
592 print_move_fragments: bool = (false, parse_bool,
593 "print out move-fragment data for every fn"),
594 flowgraph_print_loans: bool = (false, parse_bool,
595 "include loan analysis data in --unpretty flowgraph output"),
596 flowgraph_print_moves: bool = (false, parse_bool,
597 "include move analysis data in --unpretty flowgraph output"),
598 flowgraph_print_assigns: bool = (false, parse_bool,
599 "include assignment analysis data in --unpretty flowgraph output"),
600 flowgraph_print_all: bool = (false, parse_bool,
601 "include all dataflow analysis data in --unpretty flowgraph output"),
602 print_region_graph: bool = (false, parse_bool,
603 "prints region inference graph. \
604 Use with RUST_REGION_GRAPH=help for more info"),
605 parse_only: bool = (false, parse_bool,
606 "parse only; do not compile, assemble, or link"),
607 no_trans: bool = (false, parse_bool,
608 "run all passes except translation; no output"),
609 treat_err_as_bug: bool = (false, parse_bool,
610 "treat all errors that occur as bugs"),
611 incr_comp: bool = (false, parse_bool,
612 "enable incremental compilation (experimental)"),
613 dump_dep_graph: bool = (false, parse_bool,
614 "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
615 no_analysis: bool = (false, parse_bool,
616 "parse and expand the source, but run no analysis"),
617 extra_plugins: Vec<String> = (Vec::new(), parse_list,
618 "load extra plugins"),
619 unstable_options: bool = (false, parse_bool,
620 "adds unstable command line options to rustc interface"),
621 print_enum_sizes: bool = (false, parse_bool,
622 "print the size of enums and their variants"),
623 force_overflow_checks: Option<bool> = (None, parse_opt_bool,
624 "force overflow checks on or off"),
625 force_dropflag_checks: Option<bool> = (None, parse_opt_bool,
626 "force drop flag checks on or off"),
627 trace_macros: bool = (false, parse_bool,
628 "for every macro invocation, print its name and arguments"),
629 enable_nonzeroing_move_hints: bool = (false, parse_bool,
630 "force nonzeroing move optimization on"),
631 keep_mtwt_tables: bool = (false, parse_bool,
632 "don't clear the resolution tables after analysis"),
633 keep_ast: bool = (false, parse_bool,
634 "keep the AST after lowering it to HIR"),
635 show_span: Option<String> = (None, parse_opt_string,
636 "show spans for compiler debugging (expr|pat|ty)"),
639 pub fn default_lib_output() -> CrateType {
643 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
644 use syntax::parse::token::intern_and_get_ident as intern;
646 let end = &sess.target.target.target_endian;
647 let arch = &sess.target.target.arch;
648 let wordsz = &sess.target.target.target_pointer_width;
649 let os = &sess.target.target.target_os;
650 let env = &sess.target.target.target_env;
651 let vendor = &sess.target.target.target_vendor;
653 let fam = if let Some(ref fam) = sess.target.target.options.target_family {
655 } else if sess.target.target.options.is_like_windows {
656 InternedString::new("windows")
658 InternedString::new("unix")
661 let mk = attr::mk_name_value_item_str;
662 let mut ret = vec![ // Target bindings.
663 mk(InternedString::new("target_os"), intern(os)),
664 mk(InternedString::new("target_family"), fam.clone()),
665 mk(InternedString::new("target_arch"), intern(arch)),
666 mk(InternedString::new("target_endian"), intern(end)),
667 mk(InternedString::new("target_pointer_width"), intern(wordsz)),
668 mk(InternedString::new("target_env"), intern(env)),
669 mk(InternedString::new("target_vendor"), intern(vendor)),
672 "windows" | "unix" => ret.push(attr::mk_word_item(fam)),
675 if sess.target.target.options.has_elf_tls {
676 ret.push(attr::mk_word_item(InternedString::new("target_thread_local")));
678 if sess.opts.debug_assertions {
679 ret.push(attr::mk_word_item(InternedString::new("debug_assertions")));
684 pub fn append_configuration(cfg: &mut ast::CrateConfig,
685 name: InternedString) {
686 if !cfg.iter().any(|mi| mi.name() == name) {
687 cfg.push(attr::mk_word_item(name))
691 pub fn build_configuration(sess: &Session) -> ast::CrateConfig {
692 // Combine the configuration requested by the session (command line) with
693 // some default and generated configuration items
694 let default_cfg = default_configuration(sess);
695 let mut user_cfg = sess.opts.cfg.clone();
696 // If the user wants a test runner, then add the test cfg
698 append_configuration(&mut user_cfg, InternedString::new("test"))
700 let mut v = user_cfg.into_iter().collect::<Vec<_>>();
701 v.extend_from_slice(&default_cfg[..]);
705 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
706 let target = match Target::search(&opts.target_triple) {
709 panic!(sp.fatal(&format!("Error loading target specification: {}", e)));
713 let (int_type, uint_type) = match &target.target_pointer_width[..] {
714 "32" => (ast::TyI32, ast::TyU32),
715 "64" => (ast::TyI64, ast::TyU64),
716 w => panic!(sp.fatal(&format!("target specification was invalid: \
717 unrecognized target-pointer-width {}", w))),
723 uint_type: uint_type,
727 /// Returns the "short" subset of the stable rustc command line options.
728 pub fn short_optgroups() -> Vec<getopts::OptGroup> {
729 rustc_short_optgroups().into_iter()
730 .filter(|g|g.is_stable())
735 /// Returns all of the stable rustc command line options.
736 pub fn optgroups() -> Vec<getopts::OptGroup> {
737 rustc_optgroups().into_iter()
738 .filter(|g|g.is_stable())
743 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
744 pub enum OptionStability { Stable, Unstable }
746 #[derive(Clone, PartialEq, Eq)]
747 pub struct RustcOptGroup {
748 pub opt_group: getopts::OptGroup,
749 pub stability: OptionStability,
753 pub fn is_stable(&self) -> bool {
754 self.stability == OptionStability::Stable
757 fn stable(g: getopts::OptGroup) -> RustcOptGroup {
758 RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
761 fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
762 RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
766 // The `opt` local module holds wrappers around the `getopts` API that
767 // adds extra rustc-specific metadata to each option; such metadata
768 // is exposed by . The public
769 // functions below ending with `_u` are the functions that return
770 // *unstable* options, i.e. options that are only enabled when the
771 // user also passes the `-Z unstable-options` debugging flag.
773 // The `fn opt_u` etc below are written so that we can use them
774 // in the future; do not warn about them not being used right now.
778 use super::RustcOptGroup;
780 pub type R = RustcOptGroup;
781 pub type S<'a> = &'a str;
783 fn stable(g: getopts::OptGroup) -> R { RustcOptGroup::stable(g) }
784 fn unstable(g: getopts::OptGroup) -> R { RustcOptGroup::unstable(g) }
786 // FIXME (pnkfelix): We default to stable since the current set of
787 // options is defacto stable. However, it would be good to revise the
788 // code so that a stable option is the thing that takes extra effort
791 pub fn opt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optopt(a, b, c, d)) }
792 pub fn multi(a: S, b: S, c: S, d: S) -> R { stable(getopts::optmulti(a, b, c, d)) }
793 pub fn flag(a: S, b: S, c: S) -> R { stable(getopts::optflag(a, b, c)) }
794 pub fn flagopt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optflagopt(a, b, c, d)) }
795 pub fn flagmulti(a: S, b: S, c: S) -> R { stable(getopts::optflagmulti(a, b, c)) }
798 pub fn opt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optopt(a, b, c, d)) }
799 pub fn multi_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optmulti(a, b, c, d)) }
800 pub fn flag_u(a: S, b: S, c: S) -> R { unstable(getopts::optflag(a, b, c)) }
801 pub fn flagopt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optflagopt(a, b, c, d)) }
802 pub fn flagmulti_u(a: S, b: S, c: S) -> R { unstable(getopts::optflagmulti(a, b, c)) }
805 /// Returns the "short" subset of the rustc command line options,
806 /// including metadata for each option, such as whether the option is
807 /// part of the stable long-term interface for rustc.
808 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
810 opt::flag("h", "help", "Display this message"),
811 opt::multi("", "cfg", "Configure the compilation environment", "SPEC"),
812 opt::multi("L", "", "Add a directory to the library search path",
814 opt::multi("l", "", "Link the generated crate(s) to the specified native
815 library NAME. The optional KIND can be one of,
816 static, dylib, or framework. If omitted, dylib is
817 assumed.", "[KIND=]NAME"),
818 opt::multi("", "crate-type", "Comma separated list of types of crates
819 for the compiler to emit",
820 "[bin|lib|rlib|dylib|staticlib]"),
821 opt::opt("", "crate-name", "Specify the name of the crate being built",
823 opt::multi("", "emit", "Comma separated list of types of output for \
824 the compiler to emit",
825 "[asm|llvm-bc|llvm-ir|obj|link|dep-info]"),
826 opt::multi("", "print", "Comma separated list of compiler information to \
828 "[crate-name|file-names|sysroot]"),
829 opt::flagmulti("g", "", "Equivalent to -C debuginfo=2"),
830 opt::flagmulti("O", "", "Equivalent to -C opt-level=2"),
831 opt::opt("o", "", "Write output to <filename>", "FILENAME"),
832 opt::opt("", "out-dir", "Write output to compiler-chosen filename \
834 opt::opt("", "explain", "Provide a detailed explanation of an error \
836 opt::flag("", "test", "Build a test harness"),
837 opt::opt("", "target", "Target triple cpu-manufacturer-kernel[-os] \
838 to compile for (see chapter 3.4 of \
839 http://www.sourceware.org/autobook/
842 opt::multi("W", "warn", "Set lint warnings", "OPT"),
843 opt::multi("A", "allow", "Set lint allowed", "OPT"),
844 opt::multi("D", "deny", "Set lint denied", "OPT"),
845 opt::multi("F", "forbid", "Set lint forbidden", "OPT"),
846 opt::multi("", "cap-lints", "Set the most restrictive lint level. \
847 More restrictive lints are capped at this \
849 opt::multi("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
850 opt::flag("V", "version", "Print version info and exit"),
851 opt::flag("v", "verbose", "Use verbose output"),
855 /// Returns all rustc command line options, including metadata for
856 /// each option, such as whether the option is part of the stable
857 /// long-term interface for rustc.
858 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
859 let mut opts = rustc_short_optgroups();
860 opts.extend_from_slice(&[
861 opt::multi("", "extern", "Specify where an external rust library is \
864 opt::opt("", "sysroot", "Override the system root", "PATH"),
865 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
866 opt::opt("", "color", "Configure coloring of output:
867 auto = colorize, if output goes to a tty (default);
868 always = always colorize output;
869 never = never colorize output", "auto|always|never"),
871 opt::flagopt_u("", "pretty",
872 "Pretty-print the input instead of compiling;
873 valid types are: `normal` (un-annotated source),
874 `expanded` (crates expanded), or
875 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
877 opt::flagopt_u("", "unpretty",
878 "Present the input source, unstable (and less-pretty) variants;
879 valid types are any of the types for `--pretty`, as well as:
880 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
881 `everybody_loops` (all function bodies replaced with `loop {}`),
882 `hir` (the HIR), `hir,identified`, or
883 `hir,typed` (HIR with types for each node).",
889 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
890 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
891 cfgspecs.into_iter().map(|s| {
892 parse::parse_meta_from_source_str("cfgspec".to_string(),
895 &parse::ParseSess::new())
896 }).collect::<ast::CrateConfig>()
899 pub fn build_session_options(matches: &getopts::Matches) -> Options {
900 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
901 Some("auto") => ColorConfig::Auto,
902 Some("always") => ColorConfig::Always,
903 Some("never") => ColorConfig::Never,
905 None => ColorConfig::Auto,
908 early_error(ColorConfig::Auto, &format!("argument for --color must be auto, always \
909 or never (instead was `{}`)",
914 let unparsed_crate_types = matches.opt_strs("crate-type");
915 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
916 .unwrap_or_else(|e| early_error(color, &e[..]));
918 let mut lint_opts = vec!();
919 let mut describe_lints = false;
921 for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
922 for lint_name in matches.opt_strs(level.as_str()) {
923 if lint_name == "help" {
924 describe_lints = true;
926 lint_opts.push((lint_name.replace("-", "_"), level));
931 let lint_cap = matches.opt_str("cap-lints").map(|cap| {
932 lint::Level::from_str(&cap).unwrap_or_else(|| {
933 early_error(color, &format!("unknown lint level: `{}`", cap))
937 let debugging_opts = build_debugging_options(matches, color);
939 let parse_only = debugging_opts.parse_only;
940 let no_trans = debugging_opts.no_trans;
941 let treat_err_as_bug = debugging_opts.treat_err_as_bug;
942 let incremental_compilation = debugging_opts.incr_comp;
943 let dump_dep_graph = debugging_opts.dump_dep_graph;
944 let no_analysis = debugging_opts.no_analysis;
946 if debugging_opts.debug_llvm {
947 unsafe { llvm::LLVMSetDebug(1); }
950 let mut output_types = HashMap::new();
951 if !debugging_opts.parse_only && !no_trans {
952 for list in matches.opt_strs("emit") {
953 for output_type in list.split(',') {
954 let mut parts = output_type.splitn(2, '=');
955 let output_type = match parts.next().unwrap() {
956 "asm" => OutputType::Assembly,
957 "llvm-ir" => OutputType::LlvmAssembly,
958 "llvm-bc" => OutputType::Bitcode,
959 "obj" => OutputType::Object,
960 "link" => OutputType::Exe,
961 "dep-info" => OutputType::DepInfo,
963 early_error(color, &format!("unknown emission type: `{}`",
967 let path = parts.next().map(PathBuf::from);
968 output_types.insert(output_type, path);
972 if output_types.is_empty() {
973 output_types.insert(OutputType::Exe, None);
976 let mut cg = build_codegen_options(matches, color);
978 // Issue #30063: if user requests llvm-related output to one
979 // particular path, disable codegen-units.
980 if matches.opt_present("o") && cg.codegen_units != 1 {
981 let incompatible: Vec<_> = output_types.iter()
982 .map(|ot_path| ot_path.0)
984 !ot.is_compatible_with_codegen_units_and_single_output_file()
986 if !incompatible.is_empty() {
987 for ot in &incompatible {
988 early_warn(color, &format!("--emit={} with -o incompatible with \
989 -C codegen-units=N for N > 1",
992 early_warn(color, "resetting to default -C codegen-units=1");
993 cg.codegen_units = 1;
999 let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
1000 let target = matches.opt_str("target").unwrap_or(
1001 host_triple().to_string());
1003 if matches.opt_present("O") {
1004 if cg.opt_level.is_some() {
1005 early_error(color, "-O and -C opt-level both provided");
1009 match cg.opt_level {
1014 Some(3) => Aggressive,
1016 early_error(color, &format!("optimization level needs to be \
1017 between 0-3 (instead was `{}`)",
1023 let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == No);
1024 let gc = debugging_opts.gc;
1025 let debuginfo = if matches.opt_present("g") {
1026 if cg.debuginfo.is_some() {
1027 early_error(color, "-g and -C debuginfo both provided");
1031 match cg.debuginfo {
1032 None | Some(0) => NoDebugInfo,
1033 Some(1) => LimitedDebugInfo,
1034 Some(2) => FullDebugInfo,
1036 early_error(color, &format!("debug info level needs to be between \
1037 0-2 (instead was `{}`)",
1043 let mut search_paths = SearchPaths::new();
1044 for s in &matches.opt_strs("L") {
1045 search_paths.add_path(&s[..], color);
1048 let libs = matches.opt_strs("l").into_iter().map(|s| {
1049 let mut parts = s.splitn(2, '=');
1050 let kind = parts.next().unwrap();
1051 let (name, kind) = match (parts.next(), kind) {
1053 (Some(name), "dylib") => (name, cstore::NativeUnknown),
1054 (Some(name), "framework") => (name, cstore::NativeFramework),
1055 (Some(name), "static") => (name, cstore::NativeStatic),
1057 early_error(color, &format!("unknown library kind `{}`, expected \
1058 one of dylib, framework, or static",
1062 (name.to_string(), kind)
1065 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
1066 let test = matches.opt_present("test");
1068 let prints = matches.opt_strs("print").into_iter().map(|s| {
1070 "crate-name" => PrintRequest::CrateName,
1071 "file-names" => PrintRequest::FileNames,
1072 "sysroot" => PrintRequest::Sysroot,
1074 early_error(color, &format!("unknown print request `{}`", req))
1077 }).collect::<Vec<_>>();
1079 if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
1080 early_warn(color, "-C remark will not show source locations without \
1084 let mut externs = HashMap::new();
1085 for arg in &matches.opt_strs("extern") {
1086 let mut parts = arg.splitn(2, '=');
1087 let name = match parts.next() {
1089 None => early_error(color, "--extern value must not be empty"),
1091 let location = match parts.next() {
1093 None => early_error(color, "--extern value must be of the format `foo=bar`"),
1096 externs.entry(name.to_string()).or_insert(vec![]).push(location.to_string());
1099 let crate_name = matches.opt_str("crate-name");
1102 crate_types: crate_types,
1104 optimize: opt_level,
1105 debuginfo: debuginfo,
1106 lint_opts: lint_opts,
1108 describe_lints: describe_lints,
1109 output_types: output_types,
1110 search_paths: search_paths,
1111 maybe_sysroot: sysroot_opt,
1112 target_triple: target,
1115 parse_only: parse_only,
1117 treat_err_as_bug: treat_err_as_bug,
1118 incremental_compilation: incremental_compilation || dump_dep_graph,
1119 dump_dep_graph: dump_dep_graph,
1120 no_analysis: no_analysis,
1121 debugging_opts: debugging_opts,
1126 crate_name: crate_name,
1129 unstable_features: get_unstable_features_setting(),
1130 debug_assertions: debug_assertions,
1134 pub fn get_unstable_features_setting() -> UnstableFeatures {
1135 // Whether this is a feature-staged build, i.e. on the beta or stable channel
1136 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
1137 // The secret key needed to get through the rustc build itself by
1138 // subverting the unstable features lints
1139 let bootstrap_secret_key = option_env!("CFG_BOOTSTRAP_KEY");
1140 // The matching key to the above, only known by the build system
1141 let bootstrap_provided_key = env::var("RUSTC_BOOTSTRAP_KEY").ok();
1142 match (disable_unstable_features, bootstrap_secret_key, bootstrap_provided_key) {
1143 (_, Some(ref s), Some(ref p)) if s == p => UnstableFeatures::Cheat,
1144 (true, _, _) => UnstableFeatures::Disallow,
1145 (false, _, _) => UnstableFeatures::Allow
1149 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
1151 let mut crate_types: Vec<CrateType> = Vec::new();
1152 for unparsed_crate_type in &list_list {
1153 for part in unparsed_crate_type.split(',') {
1154 let new_part = match part {
1155 "lib" => default_lib_output(),
1156 "rlib" => CrateTypeRlib,
1157 "staticlib" => CrateTypeStaticlib,
1158 "dylib" => CrateTypeDylib,
1159 "bin" => CrateTypeExecutable,
1161 return Err(format!("unknown crate type: `{}`",
1165 if !crate_types.contains(&new_part) {
1166 crate_types.push(new_part)
1171 return Ok(crate_types);
1174 impl fmt::Display for CrateType {
1175 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1177 CrateTypeExecutable => "bin".fmt(f),
1178 CrateTypeDylib => "dylib".fmt(f),
1179 CrateTypeRlib => "rlib".fmt(f),
1180 CrateTypeStaticlib => "staticlib".fmt(f)
1187 use middle::cstore::DummyCrateStore;
1188 use session::config::{build_configuration, optgroups, build_session_options};
1189 use session::build_session;
1192 use getopts::getopts;
1194 use syntax::attr::AttrMetaMethods;
1195 use syntax::diagnostics;
1197 // When the user supplies --test we should implicitly supply --cfg test
1199 fn test_switch_implies_cfg_test() {
1201 &match getopts(&["--test".to_string()], &optgroups()) {
1203 Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
1205 let registry = diagnostics::registry::Registry::new(&[]);
1206 let sessopts = build_session_options(matches);
1207 let sess = build_session(sessopts, None, registry, Rc::new(DummyCrateStore));
1208 let cfg = build_configuration(&sess);
1209 assert!((attr::contains_name(&cfg[..], "test")));
1212 // When the user supplies --test and --cfg test, don't implicitly add
1213 // another --cfg test
1215 fn test_switch_implies_cfg_test_unless_cfg_test() {
1217 &match getopts(&["--test".to_string(), "--cfg=test".to_string()],
1221 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
1224 let registry = diagnostics::registry::Registry::new(&[]);
1225 let sessopts = build_session_options(matches);
1226 let sess = build_session(sessopts, None, registry,
1227 Rc::new(DummyCrateStore));
1228 let cfg = build_configuration(&sess);
1229 let mut test_items = cfg.iter().filter(|m| m.name() == "test");
1230 assert!(test_items.next().is_some());
1231 assert!(test_items.next().is_none());
1235 fn test_can_print_warnings() {
1237 let matches = getopts(&[
1238 "-Awarnings".to_string()
1239 ], &optgroups()).unwrap();
1240 let registry = diagnostics::registry::Registry::new(&[]);
1241 let sessopts = build_session_options(&matches);
1242 let sess = build_session(sessopts, None, registry,
1243 Rc::new(DummyCrateStore));
1244 assert!(!sess.diagnostic().can_emit_warnings);
1248 let matches = getopts(&[
1249 "-Awarnings".to_string(),
1250 "-Dwarnings".to_string()
1251 ], &optgroups()).unwrap();
1252 let registry = diagnostics::registry::Registry::new(&[]);
1253 let sessopts = build_session_options(&matches);
1254 let sess = build_session(sessopts, None, registry,
1255 Rc::new(DummyCrateStore));
1256 assert!(sess.diagnostic().can_emit_warnings);
1260 let matches = getopts(&[
1261 "-Adead_code".to_string()
1262 ], &optgroups()).unwrap();
1263 let registry = diagnostics::registry::Registry::new(&[]);
1264 let sessopts = build_session_options(&matches);
1265 let sess = build_session(sessopts, None, registry,
1266 Rc::new(DummyCrateStore));
1267 assert!(sess.diagnostic().can_emit_warnings);