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)]
76 // The crate config requested for the session, which may be combined
77 // with additional crate configurations during the compile process
78 pub crate_types: Vec<CrateType>,
81 pub optimize: OptLevel,
82 pub debug_assertions: bool,
83 pub debuginfo: DebugInfoLevel,
84 pub lint_opts: Vec<(String, lint::Level)>,
85 pub lint_cap: Option<lint::Level>,
86 pub describe_lints: bool,
87 pub output_types: HashMap<OutputType, Option<PathBuf>>,
88 // This was mutable for rustpkg, which updates search paths based on the
89 // parsed code. It remains mutable in case its replacements wants to use
91 pub search_paths: SearchPaths,
92 pub libs: Vec<(String, cstore::NativeLibraryKind)>,
93 pub maybe_sysroot: Option<PathBuf>,
94 pub target_triple: String,
95 // User-specified cfg meta items. The compiler itself will add additional
96 // items to the crate config, and during parsing the entire crate config
97 // will be added to the crate AST node. This should not be used for
98 // anything except building the full crate config prior to parsing.
99 pub cfg: ast::CrateConfig,
101 pub parse_only: bool,
103 pub treat_err_as_bug: bool,
104 pub no_analysis: bool,
105 pub debugging_opts: DebuggingOptions,
106 pub prints: Vec<PrintRequest>,
107 pub cg: CodegenOptions,
108 pub color: ColorConfig,
109 pub show_span: Option<String>,
110 pub externs: HashMap<String, Vec<String>>,
111 pub crate_name: Option<String>,
112 /// An optional name to use as the crate for std during std injection,
113 /// written `extern crate std = "name"`. Default to "std". Used by
114 /// out-of-tree drivers.
115 pub alt_std_name: Option<String>,
116 /// Indicates how the compiler should treat unstable features
117 pub unstable_features: UnstableFeatures
120 #[derive(Clone, PartialEq, Eq)]
121 pub enum PrintRequest {
128 /// Load source from file
130 /// The string is the source
135 pub fn filestem(&self) -> String {
137 Input::File(ref ifile) => ifile.file_stem().unwrap()
138 .to_str().unwrap().to_string(),
139 Input::Str(_) => "rust_out".to_string(),
145 pub struct OutputFilenames {
146 pub out_directory: PathBuf,
147 pub out_filestem: String,
148 pub single_output_file: Option<PathBuf>,
150 pub outputs: HashMap<OutputType, Option<PathBuf>>,
153 impl OutputFilenames {
154 pub fn path(&self, flavor: OutputType) -> PathBuf {
155 self.outputs.get(&flavor).and_then(|p| p.to_owned())
156 .or_else(|| self.single_output_file.clone())
157 .unwrap_or_else(|| self.temp_path(flavor))
160 pub fn temp_path(&self, flavor: OutputType) -> PathBuf {
161 let base = self.out_directory.join(&self.filestem());
163 OutputType::Bitcode => base.with_extension("bc"),
164 OutputType::Assembly => base.with_extension("s"),
165 OutputType::LlvmAssembly => base.with_extension("ll"),
166 OutputType::Object => base.with_extension("o"),
167 OutputType::DepInfo => base.with_extension("d"),
168 OutputType::Exe => base,
172 pub fn with_extension(&self, extension: &str) -> PathBuf {
173 self.out_directory.join(&self.filestem()).with_extension(extension)
176 pub fn filestem(&self) -> String {
177 format!("{}{}", self.out_filestem, self.extra)
181 pub fn host_triple() -> &'static str {
182 // Get the host triple out of the build environment. This ensures that our
183 // idea of the host triple is the same as for the set of libraries we've
184 // actually built. We can't just take LLVM's host triple because they
185 // normalize all ix86 architectures to i386.
187 // Instead of grabbing the host triple (for the current host), we grab (at
188 // compile time) the target triple that this rustc is built with and
189 // calling that (at runtime) the host triple.
190 (option_env!("CFG_COMPILER_HOST_TRIPLE")).
191 expect("CFG_COMPILER_HOST_TRIPLE")
194 /// Some reasonable defaults
195 pub fn basic_options() -> Options {
197 crate_types: Vec::new(),
200 debuginfo: NoDebugInfo,
201 lint_opts: Vec::new(),
203 describe_lints: false,
204 output_types: HashMap::new(),
205 search_paths: SearchPaths::new(),
207 target_triple: host_triple().to_string(),
212 treat_err_as_bug: false,
214 debugging_opts: basic_debugging_options(),
216 cg: basic_codegen_options(),
219 externs: HashMap::new(),
223 unstable_features: UnstableFeatures::Disallow,
224 debug_assertions: true,
228 // The type of entry function, so
229 // users can have their own entry
230 // functions that don't start a
232 #[derive(Copy, Clone, PartialEq)]
233 pub enum EntryFnType {
239 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
249 SomePasses(Vec<String>),
254 pub fn is_empty(&self) -> bool {
256 SomePasses(ref v) => v.is_empty(),
262 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
263 /// at once. The goal of this macro is to define an interface that can be
264 /// programmatically used by the option parser in order to initialize the struct
265 /// without hardcoding field names all over the place.
267 /// The goal is to invoke this macro once with the correct fields, and then this
268 /// macro generates all necessary code. The main gotcha of this macro is the
269 /// cgsetters module which is a bunch of generated code to parse an option into
270 /// its respective field in the struct. There are a few hand-written parsers for
271 /// parsing specific types of values in this module.
272 macro_rules! options {
273 ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
274 $buildfn:ident, $prefix:expr, $outputname:expr,
275 $stat:ident, $mod_desc:ident, $mod_set:ident,
276 $($opt:ident : $t:ty = ($init:expr, $parse:ident, $desc:expr)),* ,) =>
279 pub struct $struct_name { $(pub $opt: $t),* }
281 pub fn $defaultfn() -> $struct_name {
282 $struct_name { $($opt: $init),* }
285 pub fn $buildfn(matches: &getopts::Matches, color: ColorConfig) -> $struct_name
287 let mut op = $defaultfn();
288 for option in matches.opt_strs($prefix) {
289 let mut iter = option.splitn(2, '=');
290 let key = iter.next().unwrap();
291 let value = iter.next();
292 let option_to_lookup = key.replace("-", "_");
293 let mut found = false;
294 for &(candidate, setter, opt_type_desc, _) in $stat {
295 if option_to_lookup != candidate { continue }
296 if !setter(&mut op, value) {
297 match (value, opt_type_desc) {
298 (Some(..), None) => {
299 early_error(color, &format!("{} option `{}` takes no \
300 value", $outputname, key))
302 (None, Some(type_desc)) => {
303 early_error(color, &format!("{0} option `{1}` requires \
304 {2} ({3} {1}=<value>)",
308 (Some(value), Some(type_desc)) => {
309 early_error(color, &format!("incorrect value `{}` for {} \
310 option `{}` - {} was expected",
314 (None, None) => unreachable!()
321 early_error(color, &format!("unknown {} option: `{}`",
328 pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
329 pub const $stat: &'static [(&'static str, $setter_name,
330 Option<&'static str>, &'static str)] =
331 &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
333 #[allow(non_upper_case_globals, dead_code)]
335 pub const parse_bool: Option<&'static str> = None;
336 pub const parse_opt_bool: Option<&'static str> =
337 Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
338 pub const parse_string: Option<&'static str> = Some("a string");
339 pub const parse_opt_string: Option<&'static str> = Some("a string");
340 pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
341 pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
342 pub const parse_uint: Option<&'static str> = Some("a number");
343 pub const parse_passes: Option<&'static str> =
344 Some("a space-separated list of passes, or `all`");
345 pub const parse_opt_uint: Option<&'static str> =
351 use super::{$struct_name, Passes, SomePasses, AllPasses};
354 pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
355 $parse(&mut cg.$opt, v)
359 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
362 None => { *slot = true; true }
366 fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
370 "n" | "no" | "off" => {
373 "y" | "yes" | "on" => {
376 _ => { return false; }
381 None => { *slot = Some(true); true }
385 fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
387 Some(s) => { *slot = Some(s.to_string()); true },
392 fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
394 Some(s) => { *slot = s.to_string(); true },
399 fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
403 for s in s.split_whitespace() {
404 slot.push(s.to_string());
412 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
416 let v = s.split_whitespace().map(|s| s.to_string()).collect();
424 fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
425 match v.and_then(|s| s.parse().ok()) {
426 Some(i) => { *slot = i; true },
431 fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
433 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
434 None => { *slot = None; true }
438 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
445 let mut passes = vec!();
446 if parse_list(&mut passes, v) {
447 *slot = SomePasses(passes);
458 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
459 build_codegen_options, "C", "codegen",
460 CG_OPTIONS, cg_type_desc, cgsetters,
461 ar: Option<String> = (None, parse_opt_string,
462 "tool to assemble archives with"),
463 linker: Option<String> = (None, parse_opt_string,
464 "system linker to link outputs with"),
465 link_args: Option<Vec<String>> = (None, parse_opt_list,
466 "extra arguments to pass to the linker (space separated)"),
467 lto: bool = (false, parse_bool,
468 "perform LLVM link-time optimizations"),
469 target_cpu: Option<String> = (None, parse_opt_string,
470 "select target processor (llc -mcpu=help for details)"),
471 target_feature: String = ("".to_string(), parse_string,
472 "target specific attributes (llc -mattr=help for details)"),
473 passes: Vec<String> = (Vec::new(), parse_list,
474 "a list of extra LLVM passes to run (space separated)"),
475 llvm_args: Vec<String> = (Vec::new(), parse_list,
476 "a list of arguments to pass to llvm (space separated)"),
477 save_temps: bool = (false, parse_bool,
478 "save all temporary output files during compilation"),
479 rpath: bool = (false, parse_bool,
480 "set rpath values in libs/exes"),
481 no_prepopulate_passes: bool = (false, parse_bool,
482 "don't pre-populate the pass manager with a list of passes"),
483 no_vectorize_loops: bool = (false, parse_bool,
484 "don't run the loop vectorization optimization passes"),
485 no_vectorize_slp: bool = (false, parse_bool,
486 "don't run LLVM's SLP vectorization pass"),
487 soft_float: bool = (false, parse_bool,
488 "generate software floating point library calls"),
489 prefer_dynamic: bool = (false, parse_bool,
490 "prefer dynamic linking to static linking"),
491 no_integrated_as: bool = (false, parse_bool,
492 "use an external assembler rather than LLVM's integrated one"),
493 no_redzone: Option<bool> = (None, parse_opt_bool,
494 "disable the use of the redzone"),
495 relocation_model: Option<String> = (None, parse_opt_string,
496 "choose the relocation model to use (llc -relocation-model for details)"),
497 code_model: Option<String> = (None, parse_opt_string,
498 "choose the code model to use (llc -code-model for details)"),
499 metadata: Vec<String> = (Vec::new(), parse_list,
500 "metadata to mangle symbol names with"),
501 extra_filename: String = ("".to_string(), parse_string,
502 "extra data to put in each output filename"),
503 codegen_units: usize = (1, parse_uint,
504 "divide crate into N units to optimize in parallel"),
505 remark: Passes = (SomePasses(Vec::new()), parse_passes,
506 "print remarks for these optimization passes (space separated, or \"all\")"),
507 no_stack_check: bool = (false, parse_bool,
508 "disable checks for stack exhaustion (a memory-safety hazard!)"),
509 debuginfo: Option<usize> = (None, parse_opt_uint,
510 "debug info emission level, 0 = no debug info, 1 = line tables only, \
511 2 = full debug info with variable and type information"),
512 opt_level: Option<usize> = (None, parse_opt_uint,
513 "optimize with possible levels 0-3"),
514 debug_assertions: Option<bool> = (None, parse_opt_bool,
515 "explicitly enable the cfg(debug_assertions) directive"),
516 inline_threshold: Option<usize> = (None, parse_opt_uint,
517 "set the inlining threshold for"),
521 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
522 build_debugging_options, "Z", "debugging",
523 DB_OPTIONS, db_type_desc, dbsetters,
524 verbose: bool = (false, parse_bool,
525 "in general, enable more debug printouts"),
526 time_passes: bool = (false, parse_bool,
527 "measure time of each rustc pass"),
528 count_llvm_insns: bool = (false, parse_bool,
529 "count where LLVM instrs originate"),
530 time_llvm_passes: bool = (false, parse_bool,
531 "measure time of each LLVM pass"),
532 input_stats: bool = (false, parse_bool,
533 "gather statistics about the input"),
534 trans_stats: bool = (false, parse_bool,
535 "gather trans statistics"),
536 asm_comments: bool = (false, parse_bool,
537 "generate comments into the assembly (may change behavior)"),
538 no_verify: bool = (false, parse_bool,
539 "skip LLVM verification"),
540 borrowck_stats: bool = (false, parse_bool,
541 "gather borrowck statistics"),
542 no_landing_pads: bool = (false, parse_bool,
543 "omit landing pads for unwinding"),
544 debug_llvm: bool = (false, parse_bool,
545 "enable debug output from LLVM"),
546 count_type_sizes: bool = (false, parse_bool,
547 "count the sizes of aggregate types"),
548 meta_stats: bool = (false, parse_bool,
549 "gather metadata statistics"),
550 print_link_args: bool = (false, parse_bool,
551 "print the arguments passed to the linker"),
552 gc: bool = (false, parse_bool,
553 "garbage collect shared data (experimental)"),
554 print_llvm_passes: bool = (false, parse_bool,
555 "prints the llvm optimization passes being run"),
556 ast_json: bool = (false, parse_bool,
557 "print the AST as JSON and halt"),
558 ast_json_noexpand: bool = (false, parse_bool,
559 "print the pre-expansion AST as JSON and halt"),
560 ls: bool = (false, parse_bool,
561 "list the symbols defined by a library crate"),
562 save_analysis: bool = (false, parse_bool,
563 "write syntax and type analysis information in addition to normal output"),
564 print_move_fragments: bool = (false, parse_bool,
565 "print out move-fragment data for every fn"),
566 flowgraph_print_loans: bool = (false, parse_bool,
567 "include loan analysis data in --unpretty flowgraph output"),
568 flowgraph_print_moves: bool = (false, parse_bool,
569 "include move analysis data in --unpretty flowgraph output"),
570 flowgraph_print_assigns: bool = (false, parse_bool,
571 "include assignment analysis data in --unpretty flowgraph output"),
572 flowgraph_print_all: bool = (false, parse_bool,
573 "include all dataflow analysis data in --unpretty flowgraph output"),
574 print_region_graph: bool = (false, parse_bool,
575 "prints region inference graph. \
576 Use with RUST_REGION_GRAPH=help for more info"),
577 parse_only: bool = (false, parse_bool,
578 "parse only; do not compile, assemble, or link"),
579 no_trans: bool = (false, parse_bool,
580 "run all passes except translation; no output"),
581 treat_err_as_bug: bool = (false, parse_bool,
582 "treat all errors that occur as bugs"),
583 no_analysis: bool = (false, parse_bool,
584 "parse and expand the source, but run no analysis"),
585 extra_plugins: Vec<String> = (Vec::new(), parse_list,
586 "load extra plugins"),
587 unstable_options: bool = (false, parse_bool,
588 "adds unstable command line options to rustc interface"),
589 print_enum_sizes: bool = (false, parse_bool,
590 "print the size of enums and their variants"),
591 force_overflow_checks: Option<bool> = (None, parse_opt_bool,
592 "force overflow checks on or off"),
593 force_dropflag_checks: Option<bool> = (None, parse_opt_bool,
594 "force drop flag checks on or off"),
595 trace_macros: bool = (false, parse_bool,
596 "for every macro invocation, print its name and arguments"),
597 enable_nonzeroing_move_hints: bool = (false, parse_bool,
598 "force nonzeroing move optimization on"),
599 keep_mtwt_tables: bool = (false, parse_bool,
600 "don't clear the resolution tables after analysis"),
603 pub fn default_lib_output() -> CrateType {
607 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
608 use syntax::parse::token::intern_and_get_ident as intern;
610 let end = &sess.target.target.target_endian;
611 let arch = &sess.target.target.arch;
612 let wordsz = &sess.target.target.target_pointer_width;
613 let os = &sess.target.target.target_os;
614 let env = &sess.target.target.target_env;
615 let vendor = &sess.target.target.target_vendor;
617 let fam = if let Some(ref fam) = sess.target.target.options.target_family {
619 } else if sess.target.target.options.is_like_windows {
620 InternedString::new("windows")
622 InternedString::new("unix")
625 let mk = attr::mk_name_value_item_str;
626 let mut ret = vec![ // Target bindings.
627 mk(InternedString::new("target_os"), intern(os)),
628 mk(InternedString::new("target_family"), fam.clone()),
629 mk(InternedString::new("target_arch"), intern(arch)),
630 mk(InternedString::new("target_endian"), intern(end)),
631 mk(InternedString::new("target_pointer_width"), intern(wordsz)),
632 mk(InternedString::new("target_env"), intern(env)),
633 mk(InternedString::new("target_vendor"), intern(vendor)),
636 "windows" | "unix" => ret.push(attr::mk_word_item(fam)),
639 if sess.opts.debug_assertions {
640 ret.push(attr::mk_word_item(InternedString::new("debug_assertions")));
645 pub fn append_configuration(cfg: &mut ast::CrateConfig,
646 name: InternedString) {
647 if !cfg.iter().any(|mi| mi.name() == name) {
648 cfg.push(attr::mk_word_item(name))
652 pub fn build_configuration(sess: &Session) -> ast::CrateConfig {
653 // Combine the configuration requested by the session (command line) with
654 // some default and generated configuration items
655 let default_cfg = default_configuration(sess);
656 let mut user_cfg = sess.opts.cfg.clone();
657 // If the user wants a test runner, then add the test cfg
659 append_configuration(&mut user_cfg, InternedString::new("test"))
661 let mut v = user_cfg.into_iter().collect::<Vec<_>>();
662 v.push_all(&default_cfg[..]);
666 pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config {
667 let target = match Target::search(&opts.target_triple) {
670 panic!(sp.handler().fatal(&format!("Error loading target specification: {}", e)));
674 let (int_type, uint_type) = match &target.target_pointer_width[..] {
675 "32" => (ast::TyI32, ast::TyU32),
676 "64" => (ast::TyI64, ast::TyU64),
677 w => panic!(sp.handler().fatal(&format!("target specification was invalid: \
678 unrecognized target-pointer-width {}", w))),
684 uint_type: uint_type,
688 /// Returns the "short" subset of the stable rustc command line options.
689 pub fn short_optgroups() -> Vec<getopts::OptGroup> {
690 rustc_short_optgroups().into_iter()
691 .filter(|g|g.is_stable())
696 /// Returns all of the stable rustc command line options.
697 pub fn optgroups() -> Vec<getopts::OptGroup> {
698 rustc_optgroups().into_iter()
699 .filter(|g|g.is_stable())
704 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
705 pub enum OptionStability { Stable, Unstable }
707 #[derive(Clone, PartialEq, Eq)]
708 pub struct RustcOptGroup {
709 pub opt_group: getopts::OptGroup,
710 pub stability: OptionStability,
714 pub fn is_stable(&self) -> bool {
715 self.stability == OptionStability::Stable
718 fn stable(g: getopts::OptGroup) -> RustcOptGroup {
719 RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
722 fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
723 RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
727 // The `opt` local module holds wrappers around the `getopts` API that
728 // adds extra rustc-specific metadata to each option; such metadata
729 // is exposed by . The public
730 // functions below ending with `_u` are the functions that return
731 // *unstable* options, i.e. options that are only enabled when the
732 // user also passes the `-Z unstable-options` debugging flag.
734 // The `fn opt_u` etc below are written so that we can use them
735 // in the future; do not warn about them not being used right now.
739 use super::RustcOptGroup;
741 pub type R = RustcOptGroup;
742 pub type S<'a> = &'a str;
744 fn stable(g: getopts::OptGroup) -> R { RustcOptGroup::stable(g) }
745 fn unstable(g: getopts::OptGroup) -> R { RustcOptGroup::unstable(g) }
747 // FIXME (pnkfelix): We default to stable since the current set of
748 // options is defacto stable. However, it would be good to revise the
749 // code so that a stable option is the thing that takes extra effort
752 pub fn opt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optopt(a, b, c, d)) }
753 pub fn multi(a: S, b: S, c: S, d: S) -> R { stable(getopts::optmulti(a, b, c, d)) }
754 pub fn flag(a: S, b: S, c: S) -> R { stable(getopts::optflag(a, b, c)) }
755 pub fn flagopt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optflagopt(a, b, c, d)) }
756 pub fn flagmulti(a: S, b: S, c: S) -> R { stable(getopts::optflagmulti(a, b, c)) }
759 pub fn opt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optopt(a, b, c, d)) }
760 pub fn multi_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optmulti(a, b, c, d)) }
761 pub fn flag_u(a: S, b: S, c: S) -> R { unstable(getopts::optflag(a, b, c)) }
762 pub fn flagopt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optflagopt(a, b, c, d)) }
763 pub fn flagmulti_u(a: S, b: S, c: S) -> R { unstable(getopts::optflagmulti(a, b, c)) }
766 /// Returns the "short" subset of the rustc command line options,
767 /// including metadata for each option, such as whether the option is
768 /// part of the stable long-term interface for rustc.
769 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
771 opt::flag("h", "help", "Display this message"),
772 opt::multi("", "cfg", "Configure the compilation environment", "SPEC"),
773 opt::multi("L", "", "Add a directory to the library search path",
775 opt::multi("l", "", "Link the generated crate(s) to the specified native
776 library NAME. The optional KIND can be one of,
777 static, dylib, or framework. If omitted, dylib is
778 assumed.", "[KIND=]NAME"),
779 opt::multi("", "crate-type", "Comma separated list of types of crates
780 for the compiler to emit",
781 "[bin|lib|rlib|dylib|staticlib]"),
782 opt::opt("", "crate-name", "Specify the name of the crate being built",
784 opt::multi("", "emit", "Comma separated list of types of output for \
785 the compiler to emit",
786 "[asm|llvm-bc|llvm-ir|obj|link|dep-info]"),
787 opt::multi("", "print", "Comma separated list of compiler information to \
789 "[crate-name|file-names|sysroot]"),
790 opt::flagmulti("g", "", "Equivalent to -C debuginfo=2"),
791 opt::flagmulti("O", "", "Equivalent to -C opt-level=2"),
792 opt::opt("o", "", "Write output to <filename>", "FILENAME"),
793 opt::opt("", "out-dir", "Write output to compiler-chosen filename \
795 opt::opt("", "explain", "Provide a detailed explanation of an error \
797 opt::flag("", "test", "Build a test harness"),
798 opt::opt("", "target", "Target triple cpu-manufacturer-kernel[-os] \
799 to compile for (see chapter 3.4 of \
800 http://www.sourceware.org/autobook/
803 opt::multi("W", "warn", "Set lint warnings", "OPT"),
804 opt::multi("A", "allow", "Set lint allowed", "OPT"),
805 opt::multi("D", "deny", "Set lint denied", "OPT"),
806 opt::multi("F", "forbid", "Set lint forbidden", "OPT"),
807 opt::multi("", "cap-lints", "Set the most restrictive lint level. \
808 More restrictive lints are capped at this \
810 opt::multi("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
811 opt::flag("V", "version", "Print version info and exit"),
812 opt::flag("v", "verbose", "Use verbose output"),
816 /// Returns all rustc command line options, including metadata for
817 /// each option, such as whether the option is part of the stable
818 /// long-term interface for rustc.
819 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
820 let mut opts = rustc_short_optgroups();
822 opt::multi("", "extern", "Specify where an external rust library is \
825 opt::opt("", "sysroot", "Override the system root", "PATH"),
826 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
827 opt::opt("", "color", "Configure coloring of output:
828 auto = colorize, if output goes to a tty (default);
829 always = always colorize output;
830 never = never colorize output", "auto|always|never"),
832 opt::flagopt_u("", "pretty",
833 "Pretty-print the input instead of compiling;
834 valid types are: `normal` (un-annotated source),
835 `expanded` (crates expanded), or
836 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
838 opt::flagopt_u("", "unpretty",
839 "Present the input source, unstable (and less-pretty) variants;
840 valid types are any of the types for `--pretty`, as well as:
841 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
842 `everybody_loops` (all function bodies replaced with `loop {}`),
843 `hir` (the HIR), `hir,identified`, or
844 `hir,typed` (HIR with types for each node).",
846 opt::opt_u("", "show-span", "Show spans for compiler debugging", "expr|pat|ty"),
851 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
852 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
853 cfgspecs.into_iter().map(|s| {
854 parse::parse_meta_from_source_str("cfgspec".to_string(),
857 &parse::ParseSess::new())
858 }).collect::<ast::CrateConfig>()
861 pub fn build_session_options(matches: &getopts::Matches) -> Options {
862 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
863 Some("auto") => Auto,
864 Some("always") => Always,
865 Some("never") => Never,
870 early_error(Auto, &format!("argument for --color must be auto, always \
871 or never (instead was `{}`)",
876 let unparsed_crate_types = matches.opt_strs("crate-type");
877 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
878 .unwrap_or_else(|e| early_error(color, &e[..]));
880 let mut lint_opts = vec!();
881 let mut describe_lints = false;
883 for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
884 for lint_name in matches.opt_strs(level.as_str()) {
885 if lint_name == "help" {
886 describe_lints = true;
888 lint_opts.push((lint_name.replace("-", "_"), level));
893 let lint_cap = matches.opt_str("cap-lints").map(|cap| {
894 lint::Level::from_str(&cap).unwrap_or_else(|| {
895 early_error(color, &format!("unknown lint level: `{}`", cap))
899 let debugging_opts = build_debugging_options(matches, color);
901 let parse_only = debugging_opts.parse_only;
902 let no_trans = debugging_opts.no_trans;
903 let treat_err_as_bug = debugging_opts.treat_err_as_bug;
904 let no_analysis = debugging_opts.no_analysis;
906 if debugging_opts.debug_llvm {
907 unsafe { llvm::LLVMSetDebug(1); }
910 let mut output_types = HashMap::new();
911 if !debugging_opts.parse_only && !no_trans {
912 for list in matches.opt_strs("emit") {
913 for output_type in list.split(',') {
914 let mut parts = output_type.splitn(2, '=');
915 let output_type = match parts.next().unwrap() {
916 "asm" => OutputType::Assembly,
917 "llvm-ir" => OutputType::LlvmAssembly,
918 "llvm-bc" => OutputType::Bitcode,
919 "obj" => OutputType::Object,
920 "link" => OutputType::Exe,
921 "dep-info" => OutputType::DepInfo,
923 early_error(color, &format!("unknown emission type: `{}`",
927 let path = parts.next().map(PathBuf::from);
928 output_types.insert(output_type, path);
932 if output_types.is_empty() {
933 output_types.insert(OutputType::Exe, None);
936 let cg = build_codegen_options(matches, color);
938 let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
939 let target = matches.opt_str("target").unwrap_or(
940 host_triple().to_string());
942 if matches.opt_present("O") {
943 if cg.opt_level.is_some() {
944 early_error(color, "-O and -C opt-level both provided");
953 Some(3) => Aggressive,
955 early_error(color, &format!("optimization level needs to be \
956 between 0-3 (instead was `{}`)",
962 let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == No);
963 let gc = debugging_opts.gc;
964 let debuginfo = if matches.opt_present("g") {
965 if cg.debuginfo.is_some() {
966 early_error(color, "-g and -C debuginfo both provided");
971 None | Some(0) => NoDebugInfo,
972 Some(1) => LimitedDebugInfo,
973 Some(2) => FullDebugInfo,
975 early_error(color, &format!("debug info level needs to be between \
976 0-2 (instead was `{}`)",
982 let mut search_paths = SearchPaths::new();
983 for s in &matches.opt_strs("L") {
984 search_paths.add_path(&s[..], color);
987 let libs = matches.opt_strs("l").into_iter().map(|s| {
988 let mut parts = s.splitn(2, '=');
989 let kind = parts.next().unwrap();
990 let (name, kind) = match (parts.next(), kind) {
992 (Some(name), "dylib") => (name, cstore::NativeUnknown),
993 (Some(name), "framework") => (name, cstore::NativeFramework),
994 (Some(name), "static") => (name, cstore::NativeStatic),
996 early_error(color, &format!("unknown library kind `{}`, expected \
997 one of dylib, framework, or static",
1001 (name.to_string(), kind)
1004 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
1005 let test = matches.opt_present("test");
1007 let prints = matches.opt_strs("print").into_iter().map(|s| {
1009 "crate-name" => PrintRequest::CrateName,
1010 "file-names" => PrintRequest::FileNames,
1011 "sysroot" => PrintRequest::Sysroot,
1013 early_error(color, &format!("unknown print request `{}`", req))
1016 }).collect::<Vec<_>>();
1018 if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
1019 early_warn(color, "-C remark will not show source locations without \
1023 let mut externs = HashMap::new();
1024 for arg in &matches.opt_strs("extern") {
1025 let mut parts = arg.splitn(2, '=');
1026 let name = match parts.next() {
1028 None => early_error(color, "--extern value must not be empty"),
1030 let location = match parts.next() {
1032 None => early_error(color, "--extern value must be of the format `foo=bar`"),
1035 externs.entry(name.to_string()).or_insert(vec![]).push(location.to_string());
1038 let crate_name = matches.opt_str("crate-name");
1041 crate_types: crate_types,
1043 optimize: opt_level,
1044 debuginfo: debuginfo,
1045 lint_opts: lint_opts,
1047 describe_lints: describe_lints,
1048 output_types: output_types,
1049 search_paths: search_paths,
1050 maybe_sysroot: sysroot_opt,
1051 target_triple: target,
1054 parse_only: parse_only,
1056 treat_err_as_bug: treat_err_as_bug,
1057 no_analysis: no_analysis,
1058 debugging_opts: debugging_opts,
1064 crate_name: crate_name,
1067 unstable_features: get_unstable_features_setting(),
1068 debug_assertions: debug_assertions,
1072 pub fn get_unstable_features_setting() -> UnstableFeatures {
1073 // Whether this is a feature-staged build, i.e. on the beta or stable channel
1074 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
1075 // The secret key needed to get through the rustc build itself by
1076 // subverting the unstable features lints
1077 let bootstrap_secret_key = option_env!("CFG_BOOTSTRAP_KEY");
1078 // The matching key to the above, only known by the build system
1079 let bootstrap_provided_key = env::var("RUSTC_BOOTSTRAP_KEY").ok();
1080 match (disable_unstable_features, bootstrap_secret_key, bootstrap_provided_key) {
1081 (_, Some(ref s), Some(ref p)) if s == p => UnstableFeatures::Cheat,
1082 (true, _, _) => UnstableFeatures::Disallow,
1083 (false, _, _) => UnstableFeatures::Allow
1087 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
1089 let mut crate_types: Vec<CrateType> = Vec::new();
1090 for unparsed_crate_type in &list_list {
1091 for part in unparsed_crate_type.split(',') {
1092 let new_part = match part {
1093 "lib" => default_lib_output(),
1094 "rlib" => CrateTypeRlib,
1095 "staticlib" => CrateTypeStaticlib,
1096 "dylib" => CrateTypeDylib,
1097 "bin" => CrateTypeExecutable,
1099 return Err(format!("unknown crate type: `{}`",
1103 if !crate_types.contains(&new_part) {
1104 crate_types.push(new_part)
1109 return Ok(crate_types);
1112 impl fmt::Display for CrateType {
1113 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1115 CrateTypeExecutable => "bin".fmt(f),
1116 CrateTypeDylib => "dylib".fmt(f),
1117 CrateTypeRlib => "rlib".fmt(f),
1118 CrateTypeStaticlib => "staticlib".fmt(f)
1126 use session::config::{build_configuration, optgroups, build_session_options};
1127 use session::build_session;
1129 use getopts::getopts;
1131 use syntax::attr::AttrMetaMethods;
1132 use syntax::diagnostics;
1134 // When the user supplies --test we should implicitly supply --cfg test
1136 fn test_switch_implies_cfg_test() {
1138 &match getopts(&["--test".to_string()], &optgroups()) {
1140 Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
1142 let registry = diagnostics::registry::Registry::new(&[]);
1143 let sessopts = build_session_options(matches);
1144 let sess = build_session(sessopts, None, registry);
1145 let cfg = build_configuration(&sess);
1146 assert!((attr::contains_name(&cfg[..], "test")));
1149 // When the user supplies --test and --cfg test, don't implicitly add
1150 // another --cfg test
1152 fn test_switch_implies_cfg_test_unless_cfg_test() {
1154 &match getopts(&["--test".to_string(), "--cfg=test".to_string()],
1158 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
1161 let registry = diagnostics::registry::Registry::new(&[]);
1162 let sessopts = build_session_options(matches);
1163 let sess = build_session(sessopts, None, registry);
1164 let cfg = build_configuration(&sess);
1165 let mut test_items = cfg.iter().filter(|m| m.name() == "test");
1166 assert!(test_items.next().is_some());
1167 assert!(test_items.next().is_none());
1171 fn test_can_print_warnings() {
1173 let matches = getopts(&[
1174 "-Awarnings".to_string()
1175 ], &optgroups()).unwrap();
1176 let registry = diagnostics::registry::Registry::new(&[]);
1177 let sessopts = build_session_options(&matches);
1178 let sess = build_session(sessopts, None, registry);
1179 assert!(!sess.can_print_warnings);
1183 let matches = getopts(&[
1184 "-Awarnings".to_string(),
1185 "-Dwarnings".to_string()
1186 ], &optgroups()).unwrap();
1187 let registry = diagnostics::registry::Registry::new(&[]);
1188 let sessopts = build_session_options(&matches);
1189 let sess = build_session(sessopts, None, registry);
1190 assert!(sess.can_print_warnings);
1194 let matches = getopts(&[
1195 "-Adead_code".to_string()
1196 ], &optgroups()).unwrap();
1197 let registry = diagnostics::registry::Registry::new(&[]);
1198 let sessopts = build_session_options(&matches);
1199 let sess = build_session(sessopts, None, registry);
1200 assert!(sess.can_print_warnings);