1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Contains infrastructure for configuring the compiler, including parsing
12 //! command line options.
14 pub use self::EntryFnType::*;
15 pub use self::CrateType::*;
16 pub use self::Passes::*;
17 pub use self::DebugInfoLevel::*;
19 use session::{early_error, early_warn, Session};
20 use session::search_paths::SearchPaths;
22 use rustc_back::target::Target;
26 use syntax::ast::{self, IntTy, UintTy};
28 use syntax::attr::AttrMetaMethods;
29 use syntax::errors::{ColorConfig, Handler};
31 use syntax::parse::token::InternedString;
32 use syntax::feature_gate::UnstableFeatures;
35 use std::collections::HashMap;
38 use std::path::PathBuf;
45 pub uint_type: UintTy,
48 #[derive(Clone, Copy, PartialEq)]
56 #[derive(Clone, Copy, PartialEq)]
57 pub enum DebugInfoLevel {
63 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
73 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
74 pub enum ErrorOutputType {
75 HumanReadable(ColorConfig),
79 impl Default for ErrorOutputType {
80 fn default() -> ErrorOutputType {
81 ErrorOutputType::HumanReadable(ColorConfig::Auto)
86 fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
89 OutputType::DepInfo => true,
91 OutputType::Assembly |
92 OutputType::LlvmAssembly |
93 OutputType::Object => false,
97 fn shorthand(&self) -> &'static str {
99 OutputType::Bitcode => "llvm-bc",
100 OutputType::Assembly => "asm",
101 OutputType::LlvmAssembly => "llvm-ir",
102 OutputType::Object => "obj",
103 OutputType::Exe => "link",
104 OutputType::DepInfo => "dep-info",
111 // The crate config requested for the session, which may be combined
112 // with additional crate configurations during the compile process
113 pub crate_types: Vec<CrateType>,
116 pub optimize: OptLevel,
117 pub debug_assertions: bool,
118 pub debuginfo: DebugInfoLevel,
119 pub lint_opts: Vec<(String, lint::Level)>,
120 pub lint_cap: Option<lint::Level>,
121 pub describe_lints: bool,
122 pub output_types: HashMap<OutputType, Option<PathBuf>>,
123 // This was mutable for rustpkg, which updates search paths based on the
124 // parsed code. It remains mutable in case its replacements wants to use
126 pub search_paths: SearchPaths,
127 pub libs: Vec<(String, cstore::NativeLibraryKind)>,
128 pub maybe_sysroot: Option<PathBuf>,
129 pub target_triple: String,
130 // User-specified cfg meta items. The compiler itself will add additional
131 // items to the crate config, and during parsing the entire crate config
132 // will be added to the crate AST node. This should not be used for
133 // anything except building the full crate config prior to parsing.
134 pub cfg: ast::CrateConfig,
136 pub parse_only: bool,
138 pub error_format: ErrorOutputType,
139 pub treat_err_as_bug: bool,
141 /// if true, build up the dep-graph
142 pub build_dep_graph: bool,
144 /// if true, -Z dump-dep-graph was passed to dump out the dep-graph
145 pub dump_dep_graph: bool,
147 pub no_analysis: bool,
148 pub debugging_opts: DebuggingOptions,
149 pub prints: Vec<PrintRequest>,
150 pub cg: CodegenOptions,
151 pub externs: HashMap<String, Vec<String>>,
152 pub crate_name: Option<String>,
153 /// An optional name to use as the crate for std during std injection,
154 /// written `extern crate std = "name"`. Default to "std". Used by
155 /// out-of-tree drivers.
156 pub alt_std_name: Option<String>,
157 /// Indicates how the compiler should treat unstable features
158 pub unstable_features: UnstableFeatures
161 #[derive(Clone, PartialEq, Eq)]
162 pub enum PrintRequest {
171 /// Load source from file
173 /// The string is the source
178 pub fn filestem(&self) -> String {
180 Input::File(ref ifile) => ifile.file_stem().unwrap()
181 .to_str().unwrap().to_string(),
182 Input::Str(_) => "rust_out".to_string(),
188 pub struct OutputFilenames {
189 pub out_directory: PathBuf,
190 pub out_filestem: String,
191 pub single_output_file: Option<PathBuf>,
193 pub outputs: HashMap<OutputType, Option<PathBuf>>,
196 impl OutputFilenames {
197 pub fn path(&self, flavor: OutputType) -> PathBuf {
198 self.outputs.get(&flavor).and_then(|p| p.to_owned())
199 .or_else(|| self.single_output_file.clone())
200 .unwrap_or_else(|| self.temp_path(flavor))
203 pub fn temp_path(&self, flavor: OutputType) -> PathBuf {
204 let base = self.out_directory.join(&self.filestem());
206 OutputType::Bitcode => base.with_extension("bc"),
207 OutputType::Assembly => base.with_extension("s"),
208 OutputType::LlvmAssembly => base.with_extension("ll"),
209 OutputType::Object => base.with_extension("o"),
210 OutputType::DepInfo => base.with_extension("d"),
211 OutputType::Exe => base,
215 pub fn with_extension(&self, extension: &str) -> PathBuf {
216 self.out_directory.join(&self.filestem()).with_extension(extension)
219 pub fn filestem(&self) -> String {
220 format!("{}{}", self.out_filestem, self.extra)
224 pub fn host_triple() -> &'static str {
225 // Get the host triple out of the build environment. This ensures that our
226 // idea of the host triple is the same as for the set of libraries we've
227 // actually built. We can't just take LLVM's host triple because they
228 // normalize all ix86 architectures to i386.
230 // Instead of grabbing the host triple (for the current host), we grab (at
231 // compile time) the target triple that this rustc is built with and
232 // calling that (at runtime) the host triple.
233 (option_env!("CFG_COMPILER_HOST_TRIPLE")).
234 expect("CFG_COMPILER_HOST_TRIPLE")
237 /// Some reasonable defaults
238 pub fn basic_options() -> Options {
240 crate_types: Vec::new(),
242 optimize: OptLevel::No,
243 debuginfo: NoDebugInfo,
244 lint_opts: Vec::new(),
246 describe_lints: false,
247 output_types: HashMap::new(),
248 search_paths: SearchPaths::new(),
250 target_triple: host_triple().to_string(),
255 treat_err_as_bug: false,
256 build_dep_graph: false,
257 dump_dep_graph: false,
259 debugging_opts: basic_debugging_options(),
261 cg: basic_codegen_options(),
262 error_format: ErrorOutputType::default(),
263 externs: HashMap::new(),
267 unstable_features: UnstableFeatures::Disallow,
268 debug_assertions: true,
272 // The type of entry function, so
273 // users can have their own entry
274 // functions that don't start a
276 #[derive(Copy, Clone, PartialEq)]
277 pub enum EntryFnType {
283 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
293 SomePasses(Vec<String>),
298 pub fn is_empty(&self) -> bool {
300 SomePasses(ref v) => v.is_empty(),
306 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
307 /// at once. The goal of this macro is to define an interface that can be
308 /// programmatically used by the option parser in order to initialize the struct
309 /// without hardcoding field names all over the place.
311 /// The goal is to invoke this macro once with the correct fields, and then this
312 /// macro generates all necessary code. The main gotcha of this macro is the
313 /// cgsetters module which is a bunch of generated code to parse an option into
314 /// its respective field in the struct. There are a few hand-written parsers for
315 /// parsing specific types of values in this module.
316 macro_rules! options {
317 ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
318 $buildfn:ident, $prefix:expr, $outputname:expr,
319 $stat:ident, $mod_desc:ident, $mod_set:ident,
320 $($opt:ident : $t:ty = ($init:expr, $parse:ident, $desc:expr)),* ,) =>
323 pub struct $struct_name { $(pub $opt: $t),* }
325 pub fn $defaultfn() -> $struct_name {
326 $struct_name { $($opt: $init),* }
329 pub fn $buildfn(matches: &getopts::Matches, error_format: ErrorOutputType) -> $struct_name
331 let mut op = $defaultfn();
332 for option in matches.opt_strs($prefix) {
333 let mut iter = option.splitn(2, '=');
334 let key = iter.next().unwrap();
335 let value = iter.next();
336 let option_to_lookup = key.replace("-", "_");
337 let mut found = false;
338 for &(candidate, setter, opt_type_desc, _) in $stat {
339 if option_to_lookup != candidate { continue }
340 if !setter(&mut op, value) {
341 match (value, opt_type_desc) {
342 (Some(..), None) => {
343 early_error(error_format, &format!("{} option `{}` takes no \
344 value", $outputname, key))
346 (None, Some(type_desc)) => {
347 early_error(error_format, &format!("{0} option `{1}` requires \
348 {2} ({3} {1}=<value>)",
352 (Some(value), Some(type_desc)) => {
353 early_error(error_format, &format!("incorrect value `{}` for {} \
354 option `{}` - {} was expected",
358 (None, None) => unreachable!()
365 early_error(error_format, &format!("unknown {} option: `{}`",
372 pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
373 pub const $stat: &'static [(&'static str, $setter_name,
374 Option<&'static str>, &'static str)] =
375 &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
377 #[allow(non_upper_case_globals, dead_code)]
379 pub const parse_bool: Option<&'static str> = None;
380 pub const parse_opt_bool: Option<&'static str> =
381 Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
382 pub const parse_string: Option<&'static str> = Some("a string");
383 pub const parse_opt_string: Option<&'static str> = Some("a string");
384 pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
385 pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
386 pub const parse_uint: Option<&'static str> = Some("a number");
387 pub const parse_passes: Option<&'static str> =
388 Some("a space-separated list of passes, or `all`");
389 pub const parse_opt_uint: Option<&'static str> =
395 use super::{$struct_name, Passes, SomePasses, AllPasses};
398 pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
399 $parse(&mut cg.$opt, v)
403 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
406 None => { *slot = true; true }
410 fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
414 "n" | "no" | "off" => {
417 "y" | "yes" | "on" => {
420 _ => { return false; }
425 None => { *slot = Some(true); true }
429 fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
431 Some(s) => { *slot = Some(s.to_string()); true },
436 fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
438 Some(s) => { *slot = s.to_string(); true },
443 fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
447 for s in s.split_whitespace() {
448 slot.push(s.to_string());
456 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
460 let v = s.split_whitespace().map(|s| s.to_string()).collect();
468 fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
469 match v.and_then(|s| s.parse().ok()) {
470 Some(i) => { *slot = i; true },
475 fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
477 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
478 None => { *slot = None; true }
482 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
489 let mut passes = vec!();
490 if parse_list(&mut passes, v) {
491 *slot = SomePasses(passes);
502 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
503 build_codegen_options, "C", "codegen",
504 CG_OPTIONS, cg_type_desc, cgsetters,
505 ar: Option<String> = (None, parse_opt_string,
506 "tool to assemble archives with"),
507 linker: Option<String> = (None, parse_opt_string,
508 "system linker to link outputs with"),
509 link_args: Option<Vec<String>> = (None, parse_opt_list,
510 "extra arguments to pass to the linker (space separated)"),
511 link_dead_code: bool = (false, parse_bool,
512 "let the linker strip dead coded (turning it on can be used for code coverage)"),
513 lto: bool = (false, parse_bool,
514 "perform LLVM link-time optimizations"),
515 target_cpu: Option<String> = (None, parse_opt_string,
516 "select target processor (llc -mcpu=help for details)"),
517 target_feature: String = ("".to_string(), parse_string,
518 "target specific attributes (llc -mattr=help for details)"),
519 passes: Vec<String> = (Vec::new(), parse_list,
520 "a list of extra LLVM passes to run (space separated)"),
521 llvm_args: Vec<String> = (Vec::new(), parse_list,
522 "a list of arguments to pass to llvm (space separated)"),
523 save_temps: bool = (false, parse_bool,
524 "save all temporary output files during compilation"),
525 rpath: bool = (false, parse_bool,
526 "set rpath values in libs/exes"),
527 no_prepopulate_passes: bool = (false, parse_bool,
528 "don't pre-populate the pass manager with a list of passes"),
529 no_vectorize_loops: bool = (false, parse_bool,
530 "don't run the loop vectorization optimization passes"),
531 no_vectorize_slp: bool = (false, parse_bool,
532 "don't run LLVM's SLP vectorization pass"),
533 soft_float: bool = (false, parse_bool,
534 "generate software floating point library calls"),
535 prefer_dynamic: bool = (false, parse_bool,
536 "prefer dynamic linking to static linking"),
537 no_integrated_as: bool = (false, parse_bool,
538 "use an external assembler rather than LLVM's integrated one"),
539 no_redzone: Option<bool> = (None, parse_opt_bool,
540 "disable the use of the redzone"),
541 relocation_model: Option<String> = (None, parse_opt_string,
542 "choose the relocation model to use (llc -relocation-model for details)"),
543 code_model: Option<String> = (None, parse_opt_string,
544 "choose the code model to use (llc -code-model for details)"),
545 metadata: Vec<String> = (Vec::new(), parse_list,
546 "metadata to mangle symbol names with"),
547 extra_filename: String = ("".to_string(), parse_string,
548 "extra data to put in each output filename"),
549 codegen_units: usize = (1, parse_uint,
550 "divide crate into N units to optimize in parallel"),
551 remark: Passes = (SomePasses(Vec::new()), parse_passes,
552 "print remarks for these optimization passes (space separated, or \"all\")"),
553 no_stack_check: bool = (false, parse_bool,
554 "disable checks for stack exhaustion (a memory-safety hazard!)"),
555 debuginfo: Option<usize> = (None, parse_opt_uint,
556 "debug info emission level, 0 = no debug info, 1 = line tables only, \
557 2 = full debug info with variable and type information"),
558 opt_level: Option<usize> = (None, parse_opt_uint,
559 "optimize with possible levels 0-3"),
560 debug_assertions: Option<bool> = (None, parse_opt_bool,
561 "explicitly enable the cfg(debug_assertions) directive"),
562 inline_threshold: Option<usize> = (None, parse_opt_uint,
563 "set the inlining threshold for"),
567 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
568 build_debugging_options, "Z", "debugging",
569 DB_OPTIONS, db_type_desc, dbsetters,
570 verbose: bool = (false, parse_bool,
571 "in general, enable more debug printouts"),
572 time_passes: bool = (false, parse_bool,
573 "measure time of each rustc pass"),
574 count_llvm_insns: bool = (false, parse_bool,
575 "count where LLVM instrs originate"),
576 time_llvm_passes: bool = (false, parse_bool,
577 "measure time of each LLVM pass"),
578 input_stats: bool = (false, parse_bool,
579 "gather statistics about the input"),
580 trans_stats: bool = (false, parse_bool,
581 "gather trans statistics"),
582 asm_comments: bool = (false, parse_bool,
583 "generate comments into the assembly (may change behavior)"),
584 no_verify: bool = (false, parse_bool,
585 "skip LLVM verification"),
586 borrowck_stats: bool = (false, parse_bool,
587 "gather borrowck statistics"),
588 no_landing_pads: bool = (false, parse_bool,
589 "omit landing pads for unwinding"),
590 debug_llvm: bool = (false, parse_bool,
591 "enable debug output from LLVM"),
592 count_type_sizes: bool = (false, parse_bool,
593 "count the sizes of aggregate types"),
594 meta_stats: bool = (false, parse_bool,
595 "gather metadata statistics"),
596 print_link_args: bool = (false, parse_bool,
597 "print the arguments passed to the linker"),
598 gc: bool = (false, parse_bool,
599 "garbage collect shared data (experimental)"),
600 print_llvm_passes: bool = (false, parse_bool,
601 "prints the llvm optimization passes being run"),
602 ast_json: bool = (false, parse_bool,
603 "print the AST as JSON and halt"),
604 ast_json_noexpand: bool = (false, parse_bool,
605 "print the pre-expansion AST as JSON and halt"),
606 ls: bool = (false, parse_bool,
607 "list the symbols defined by a library crate"),
608 save_analysis: bool = (false, parse_bool,
609 "write syntax and type analysis information in addition to normal output"),
610 print_move_fragments: bool = (false, parse_bool,
611 "print out move-fragment data for every fn"),
612 flowgraph_print_loans: bool = (false, parse_bool,
613 "include loan analysis data in --unpretty flowgraph output"),
614 flowgraph_print_moves: bool = (false, parse_bool,
615 "include move analysis data in --unpretty flowgraph output"),
616 flowgraph_print_assigns: bool = (false, parse_bool,
617 "include assignment analysis data in --unpretty flowgraph output"),
618 flowgraph_print_all: bool = (false, parse_bool,
619 "include all dataflow analysis data in --unpretty flowgraph output"),
620 print_region_graph: bool = (false, parse_bool,
621 "prints region inference graph. \
622 Use with RUST_REGION_GRAPH=help for more info"),
623 parse_only: bool = (false, parse_bool,
624 "parse only; do not compile, assemble, or link"),
625 no_trans: bool = (false, parse_bool,
626 "run all passes except translation; no output"),
627 treat_err_as_bug: bool = (false, parse_bool,
628 "treat all errors that occur as bugs"),
629 incr_comp: bool = (false, parse_bool,
630 "enable incremental compilation (experimental)"),
631 dump_dep_graph: bool = (false, parse_bool,
632 "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
633 no_analysis: bool = (false, parse_bool,
634 "parse and expand the source, but run no analysis"),
635 extra_plugins: Vec<String> = (Vec::new(), parse_list,
636 "load extra plugins"),
637 unstable_options: bool = (false, parse_bool,
638 "adds unstable command line options to rustc interface"),
639 print_enum_sizes: bool = (false, parse_bool,
640 "print the size of enums and their variants"),
641 force_overflow_checks: Option<bool> = (None, parse_opt_bool,
642 "force overflow checks on or off"),
643 force_dropflag_checks: Option<bool> = (None, parse_opt_bool,
644 "force drop flag checks on or off"),
645 trace_macros: bool = (false, parse_bool,
646 "for every macro invocation, print its name and arguments"),
647 enable_nonzeroing_move_hints: bool = (false, parse_bool,
648 "force nonzeroing move optimization on"),
649 keep_mtwt_tables: bool = (false, parse_bool,
650 "don't clear the resolution tables after analysis"),
651 keep_ast: bool = (false, parse_bool,
652 "keep the AST after lowering it to HIR"),
653 show_span: Option<String> = (None, parse_opt_string,
654 "show spans for compiler debugging (expr|pat|ty)"),
655 print_trans_items: Option<String> = (None, parse_opt_string,
656 "print the result of the translation item collection pass"),
659 pub fn default_lib_output() -> CrateType {
663 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
664 use syntax::parse::token::intern_and_get_ident as intern;
666 let end = &sess.target.target.target_endian;
667 let arch = &sess.target.target.arch;
668 let wordsz = &sess.target.target.target_pointer_width;
669 let os = &sess.target.target.target_os;
670 let env = &sess.target.target.target_env;
671 let vendor = &sess.target.target.target_vendor;
673 let fam = if let Some(ref fam) = sess.target.target.options.target_family {
675 } else if sess.target.target.options.is_like_windows {
676 InternedString::new("windows")
678 InternedString::new("unix")
681 let mk = attr::mk_name_value_item_str;
682 let mut ret = vec![ // Target bindings.
683 mk(InternedString::new("target_os"), intern(os)),
684 mk(InternedString::new("target_family"), fam.clone()),
685 mk(InternedString::new("target_arch"), intern(arch)),
686 mk(InternedString::new("target_endian"), intern(end)),
687 mk(InternedString::new("target_pointer_width"), intern(wordsz)),
688 mk(InternedString::new("target_env"), intern(env)),
689 mk(InternedString::new("target_vendor"), intern(vendor)),
692 "windows" | "unix" => ret.push(attr::mk_word_item(fam)),
695 if sess.target.target.options.has_elf_tls {
696 ret.push(attr::mk_word_item(InternedString::new("target_thread_local")));
698 if sess.opts.debug_assertions {
699 ret.push(attr::mk_word_item(InternedString::new("debug_assertions")));
704 pub fn append_configuration(cfg: &mut ast::CrateConfig,
705 name: InternedString) {
706 if !cfg.iter().any(|mi| mi.name() == name) {
707 cfg.push(attr::mk_word_item(name))
711 pub fn build_configuration(sess: &Session) -> ast::CrateConfig {
712 // Combine the configuration requested by the session (command line) with
713 // some default and generated configuration items
714 let default_cfg = default_configuration(sess);
715 let mut user_cfg = sess.opts.cfg.clone();
716 // If the user wants a test runner, then add the test cfg
718 append_configuration(&mut user_cfg, InternedString::new("test"))
720 let mut v = user_cfg.into_iter().collect::<Vec<_>>();
721 v.extend_from_slice(&default_cfg[..]);
725 pub fn build_target_config(opts: &Options, sp: &Handler) -> Config {
726 let target = match Target::search(&opts.target_triple) {
729 panic!(sp.fatal(&format!("Error loading target specification: {}", e)));
733 let (int_type, uint_type) = match &target.target_pointer_width[..] {
734 "32" => (ast::IntTy::I32, ast::UintTy::U32),
735 "64" => (ast::IntTy::I64, ast::UintTy::U64),
736 w => panic!(sp.fatal(&format!("target specification was invalid: \
737 unrecognized target-pointer-width {}", w))),
743 uint_type: uint_type,
747 /// Returns the "short" subset of the stable rustc command line options.
748 pub fn short_optgroups() -> Vec<getopts::OptGroup> {
749 rustc_short_optgroups().into_iter()
750 .filter(|g|g.is_stable())
755 /// Returns all of the stable rustc command line options.
756 pub fn optgroups() -> Vec<getopts::OptGroup> {
757 rustc_optgroups().into_iter()
758 .filter(|g|g.is_stable())
763 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
764 pub enum OptionStability { Stable, Unstable }
766 #[derive(Clone, PartialEq, Eq)]
767 pub struct RustcOptGroup {
768 pub opt_group: getopts::OptGroup,
769 pub stability: OptionStability,
773 pub fn is_stable(&self) -> bool {
774 self.stability == OptionStability::Stable
777 fn stable(g: getopts::OptGroup) -> RustcOptGroup {
778 RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
781 fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
782 RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
786 // The `opt` local module holds wrappers around the `getopts` API that
787 // adds extra rustc-specific metadata to each option; such metadata
788 // is exposed by . The public
789 // functions below ending with `_u` are the functions that return
790 // *unstable* options, i.e. options that are only enabled when the
791 // user also passes the `-Z unstable-options` debugging flag.
793 // The `fn opt_u` etc below are written so that we can use them
794 // in the future; do not warn about them not being used right now.
798 use super::RustcOptGroup;
800 pub type R = RustcOptGroup;
801 pub type S<'a> = &'a str;
803 fn stable(g: getopts::OptGroup) -> R { RustcOptGroup::stable(g) }
804 fn unstable(g: getopts::OptGroup) -> R { RustcOptGroup::unstable(g) }
806 // FIXME (pnkfelix): We default to stable since the current set of
807 // options is defacto stable. However, it would be good to revise the
808 // code so that a stable option is the thing that takes extra effort
811 pub fn opt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optopt(a, b, c, d)) }
812 pub fn multi(a: S, b: S, c: S, d: S) -> R { stable(getopts::optmulti(a, b, c, d)) }
813 pub fn flag(a: S, b: S, c: S) -> R { stable(getopts::optflag(a, b, c)) }
814 pub fn flagopt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optflagopt(a, b, c, d)) }
815 pub fn flagmulti(a: S, b: S, c: S) -> R { stable(getopts::optflagmulti(a, b, c)) }
818 pub fn opt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optopt(a, b, c, d)) }
819 pub fn multi_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optmulti(a, b, c, d)) }
820 pub fn flag_u(a: S, b: S, c: S) -> R { unstable(getopts::optflag(a, b, c)) }
821 pub fn flagopt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optflagopt(a, b, c, d)) }
822 pub fn flagmulti_u(a: S, b: S, c: S) -> R { unstable(getopts::optflagmulti(a, b, c)) }
825 /// Returns the "short" subset of the rustc command line options,
826 /// including metadata for each option, such as whether the option is
827 /// part of the stable long-term interface for rustc.
828 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
830 opt::flag("h", "help", "Display this message"),
831 opt::multi("", "cfg", "Configure the compilation environment", "SPEC"),
832 opt::multi("L", "", "Add a directory to the library search path",
834 opt::multi("l", "", "Link the generated crate(s) to the specified native
835 library NAME. The optional KIND can be one of,
836 static, dylib, or framework. If omitted, dylib is
837 assumed.", "[KIND=]NAME"),
838 opt::multi("", "crate-type", "Comma separated list of types of crates
839 for the compiler to emit",
840 "[bin|lib|rlib|dylib|staticlib]"),
841 opt::opt("", "crate-name", "Specify the name of the crate being built",
843 opt::multi("", "emit", "Comma separated list of types of output for \
844 the compiler to emit",
845 "[asm|llvm-bc|llvm-ir|obj|link|dep-info]"),
846 opt::multi("", "print", "Comma separated list of compiler information to \
848 "[crate-name|file-names|sysroot|target-list]"),
849 opt::flagmulti("g", "", "Equivalent to -C debuginfo=2"),
850 opt::flagmulti("O", "", "Equivalent to -C opt-level=2"),
851 opt::opt("o", "", "Write output to <filename>", "FILENAME"),
852 opt::opt("", "out-dir", "Write output to compiler-chosen filename \
854 opt::opt("", "explain", "Provide a detailed explanation of an error \
856 opt::flag("", "test", "Build a test harness"),
857 opt::opt("", "target", "Target triple for which the code is compiled", "TARGET"),
858 opt::multi("W", "warn", "Set lint warnings", "OPT"),
859 opt::multi("A", "allow", "Set lint allowed", "OPT"),
860 opt::multi("D", "deny", "Set lint denied", "OPT"),
861 opt::multi("F", "forbid", "Set lint forbidden", "OPT"),
862 opt::multi("", "cap-lints", "Set the most restrictive lint level. \
863 More restrictive lints are capped at this \
865 opt::multi("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
866 opt::flag("V", "version", "Print version info and exit"),
867 opt::flag("v", "verbose", "Use verbose output"),
871 /// Returns all rustc command line options, including metadata for
872 /// each option, such as whether the option is part of the stable
873 /// long-term interface for rustc.
874 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
875 let mut opts = rustc_short_optgroups();
876 opts.extend_from_slice(&[
877 opt::multi("", "extern", "Specify where an external rust library is \
880 opt::opt("", "sysroot", "Override the system root", "PATH"),
881 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
882 opt::opt_u("", "error-format", "How errors and other messages are produced", "human|json"),
883 opt::opt("", "color", "Configure coloring of output:
884 auto = colorize, if output goes to a tty (default);
885 always = always colorize output;
886 never = never colorize output", "auto|always|never"),
888 opt::flagopt_u("", "pretty",
889 "Pretty-print the input instead of compiling;
890 valid types are: `normal` (un-annotated source),
891 `expanded` (crates expanded), or
892 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
894 opt::flagopt_u("", "unpretty",
895 "Present the input source, unstable (and less-pretty) variants;
896 valid types are any of the types for `--pretty`, as well as:
897 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
898 `everybody_loops` (all function bodies replaced with `loop {}`),
899 `hir` (the HIR), `hir,identified`, or
900 `hir,typed` (HIR with types for each node).",
906 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
907 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
908 cfgspecs.into_iter().map(|s| {
909 parse::parse_meta_from_source_str("cfgspec".to_string(),
912 &parse::ParseSess::new())
913 }).collect::<ast::CrateConfig>()
916 pub fn build_session_options(matches: &getopts::Matches) -> Options {
917 let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
918 Some("auto") => ColorConfig::Auto,
919 Some("always") => ColorConfig::Always,
920 Some("never") => ColorConfig::Never,
922 None => ColorConfig::Auto,
925 early_error(ErrorOutputType::default(), &format!("argument for --color must be auto, \
926 always or never (instead was `{}`)",
931 // We need the opts_present check because the driver will send us Matches
932 // with only stable options if no unstable options are used. Since error-format
933 // is unstable, it will not be present. We have to use opts_present not
934 // opt_present because the latter will panic.
935 let error_format = if matches.opts_present(&["error-format".to_owned()]) {
936 match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
937 Some("human") => ErrorOutputType::HumanReadable(color),
938 Some("json") => ErrorOutputType::Json,
940 None => ErrorOutputType::HumanReadable(color),
943 early_error(ErrorOutputType::HumanReadable(color),
944 &format!("argument for --error-format must be human or json (instead \
950 ErrorOutputType::HumanReadable(color)
953 let unparsed_crate_types = matches.opt_strs("crate-type");
954 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
955 .unwrap_or_else(|e| early_error(error_format, &e[..]));
957 let mut lint_opts = vec!();
958 let mut describe_lints = false;
960 for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
961 for lint_name in matches.opt_strs(level.as_str()) {
962 if lint_name == "help" {
963 describe_lints = true;
965 lint_opts.push((lint_name.replace("-", "_"), level));
970 let lint_cap = matches.opt_str("cap-lints").map(|cap| {
971 lint::Level::from_str(&cap).unwrap_or_else(|| {
972 early_error(error_format, &format!("unknown lint level: `{}`", cap))
976 let debugging_opts = build_debugging_options(matches, error_format);
978 let parse_only = debugging_opts.parse_only;
979 let no_trans = debugging_opts.no_trans;
980 let treat_err_as_bug = debugging_opts.treat_err_as_bug;
981 let incremental_compilation = debugging_opts.incr_comp;
982 let dump_dep_graph = debugging_opts.dump_dep_graph;
983 let no_analysis = debugging_opts.no_analysis;
985 if debugging_opts.debug_llvm {
986 unsafe { llvm::LLVMSetDebug(1); }
989 let mut output_types = HashMap::new();
990 if !debugging_opts.parse_only && !no_trans {
991 for list in matches.opt_strs("emit") {
992 for output_type in list.split(',') {
993 let mut parts = output_type.splitn(2, '=');
994 let output_type = match parts.next().unwrap() {
995 "asm" => OutputType::Assembly,
996 "llvm-ir" => OutputType::LlvmAssembly,
997 "llvm-bc" => OutputType::Bitcode,
998 "obj" => OutputType::Object,
999 "link" => OutputType::Exe,
1000 "dep-info" => OutputType::DepInfo,
1002 early_error(error_format, &format!("unknown emission type: `{}`",
1006 let path = parts.next().map(PathBuf::from);
1007 output_types.insert(output_type, path);
1011 if output_types.is_empty() {
1012 output_types.insert(OutputType::Exe, None);
1015 let mut cg = build_codegen_options(matches, error_format);
1017 // Issue #30063: if user requests llvm-related output to one
1018 // particular path, disable codegen-units.
1019 if matches.opt_present("o") && cg.codegen_units != 1 {
1020 let incompatible: Vec<_> = output_types.iter()
1021 .map(|ot_path| ot_path.0)
1023 !ot.is_compatible_with_codegen_units_and_single_output_file()
1025 if !incompatible.is_empty() {
1026 for ot in &incompatible {
1027 early_warn(error_format, &format!("--emit={} with -o incompatible with \
1028 -C codegen-units=N for N > 1",
1031 early_warn(error_format, "resetting to default -C codegen-units=1");
1032 cg.codegen_units = 1;
1038 let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
1039 let target = matches.opt_str("target").unwrap_or(
1040 host_triple().to_string());
1042 if matches.opt_present("O") {
1043 if cg.opt_level.is_some() {
1044 early_error(error_format, "-O and -C opt-level both provided");
1048 match cg.opt_level {
1049 None => OptLevel::No,
1050 Some(0) => OptLevel::No,
1051 Some(1) => OptLevel::Less,
1052 Some(2) => OptLevel::Default,
1053 Some(3) => OptLevel::Aggressive,
1055 early_error(error_format, &format!("optimization level needs to be \
1056 between 0-3 (instead was `{}`)",
1062 let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == OptLevel::No);
1063 let gc = debugging_opts.gc;
1064 let debuginfo = if matches.opt_present("g") {
1065 if cg.debuginfo.is_some() {
1066 early_error(error_format, "-g and -C debuginfo both provided");
1070 match cg.debuginfo {
1071 None | Some(0) => NoDebugInfo,
1072 Some(1) => LimitedDebugInfo,
1073 Some(2) => FullDebugInfo,
1075 early_error(error_format, &format!("debug info level needs to be between \
1076 0-2 (instead was `{}`)",
1082 let mut search_paths = SearchPaths::new();
1083 for s in &matches.opt_strs("L") {
1084 search_paths.add_path(&s[..], error_format);
1087 let libs = matches.opt_strs("l").into_iter().map(|s| {
1088 let mut parts = s.splitn(2, '=');
1089 let kind = parts.next().unwrap();
1090 let (name, kind) = match (parts.next(), kind) {
1092 (Some(name), "dylib") => (name, cstore::NativeUnknown),
1093 (Some(name), "framework") => (name, cstore::NativeFramework),
1094 (Some(name), "static") => (name, cstore::NativeStatic),
1096 early_error(error_format, &format!("unknown library kind `{}`, expected \
1097 one of dylib, framework, or static",
1101 (name.to_string(), kind)
1104 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
1105 let test = matches.opt_present("test");
1107 let prints = matches.opt_strs("print").into_iter().map(|s| {
1109 "crate-name" => PrintRequest::CrateName,
1110 "file-names" => PrintRequest::FileNames,
1111 "sysroot" => PrintRequest::Sysroot,
1112 "cfg" => PrintRequest::Cfg,
1113 "target-list" => PrintRequest::TargetList,
1115 early_error(error_format, &format!("unknown print request `{}`", req))
1118 }).collect::<Vec<_>>();
1120 if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
1121 early_warn(error_format, "-C remark will not show source locations without \
1125 let mut externs = HashMap::new();
1126 for arg in &matches.opt_strs("extern") {
1127 let mut parts = arg.splitn(2, '=');
1128 let name = match parts.next() {
1130 None => early_error(error_format, "--extern value must not be empty"),
1132 let location = match parts.next() {
1134 None => early_error(error_format, "--extern value must be of the format `foo=bar`"),
1137 externs.entry(name.to_string()).or_insert(vec![]).push(location.to_string());
1140 let crate_name = matches.opt_str("crate-name");
1143 crate_types: crate_types,
1145 optimize: opt_level,
1146 debuginfo: debuginfo,
1147 lint_opts: lint_opts,
1149 describe_lints: describe_lints,
1150 output_types: output_types,
1151 search_paths: search_paths,
1152 maybe_sysroot: sysroot_opt,
1153 target_triple: target,
1156 parse_only: parse_only,
1158 treat_err_as_bug: treat_err_as_bug,
1159 build_dep_graph: incremental_compilation || dump_dep_graph,
1160 dump_dep_graph: dump_dep_graph,
1161 no_analysis: no_analysis,
1162 debugging_opts: debugging_opts,
1165 error_format: error_format,
1167 crate_name: crate_name,
1170 unstable_features: get_unstable_features_setting(),
1171 debug_assertions: debug_assertions,
1175 pub fn get_unstable_features_setting() -> UnstableFeatures {
1176 // Whether this is a feature-staged build, i.e. on the beta or stable channel
1177 let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
1178 // The secret key needed to get through the rustc build itself by
1179 // subverting the unstable features lints
1180 let bootstrap_secret_key = option_env!("CFG_BOOTSTRAP_KEY");
1181 // The matching key to the above, only known by the build system
1182 let bootstrap_provided_key = env::var("RUSTC_BOOTSTRAP_KEY").ok();
1183 match (disable_unstable_features, bootstrap_secret_key, bootstrap_provided_key) {
1184 (_, Some(ref s), Some(ref p)) if s == p => UnstableFeatures::Cheat,
1185 (true, _, _) => UnstableFeatures::Disallow,
1186 (false, _, _) => UnstableFeatures::Allow
1190 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
1192 let mut crate_types: Vec<CrateType> = Vec::new();
1193 for unparsed_crate_type in &list_list {
1194 for part in unparsed_crate_type.split(',') {
1195 let new_part = match part {
1196 "lib" => default_lib_output(),
1197 "rlib" => CrateTypeRlib,
1198 "staticlib" => CrateTypeStaticlib,
1199 "dylib" => CrateTypeDylib,
1200 "bin" => CrateTypeExecutable,
1202 return Err(format!("unknown crate type: `{}`",
1206 if !crate_types.contains(&new_part) {
1207 crate_types.push(new_part)
1212 return Ok(crate_types);
1215 impl fmt::Display for CrateType {
1216 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1218 CrateTypeExecutable => "bin".fmt(f),
1219 CrateTypeDylib => "dylib".fmt(f),
1220 CrateTypeRlib => "rlib".fmt(f),
1221 CrateTypeStaticlib => "staticlib".fmt(f)
1228 use middle::cstore::DummyCrateStore;
1229 use session::config::{build_configuration, optgroups, build_session_options};
1230 use session::build_session;
1233 use getopts::getopts;
1235 use syntax::attr::AttrMetaMethods;
1236 use syntax::diagnostics;
1238 // When the user supplies --test we should implicitly supply --cfg test
1240 fn test_switch_implies_cfg_test() {
1242 &match getopts(&["--test".to_string()], &optgroups()) {
1244 Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
1246 let registry = diagnostics::registry::Registry::new(&[]);
1247 let sessopts = build_session_options(matches);
1248 let sess = build_session(sessopts, None, registry, Rc::new(DummyCrateStore));
1249 let cfg = build_configuration(&sess);
1250 assert!((attr::contains_name(&cfg[..], "test")));
1253 // When the user supplies --test and --cfg test, don't implicitly add
1254 // another --cfg test
1256 fn test_switch_implies_cfg_test_unless_cfg_test() {
1258 &match getopts(&["--test".to_string(), "--cfg=test".to_string()],
1262 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
1265 let registry = diagnostics::registry::Registry::new(&[]);
1266 let sessopts = build_session_options(matches);
1267 let sess = build_session(sessopts, None, registry,
1268 Rc::new(DummyCrateStore));
1269 let cfg = build_configuration(&sess);
1270 let mut test_items = cfg.iter().filter(|m| m.name() == "test");
1271 assert!(test_items.next().is_some());
1272 assert!(test_items.next().is_none());
1276 fn test_can_print_warnings() {
1278 let matches = getopts(&[
1279 "-Awarnings".to_string()
1280 ], &optgroups()).unwrap();
1281 let registry = diagnostics::registry::Registry::new(&[]);
1282 let sessopts = build_session_options(&matches);
1283 let sess = build_session(sessopts, None, registry,
1284 Rc::new(DummyCrateStore));
1285 assert!(!sess.diagnostic().can_emit_warnings);
1289 let matches = getopts(&[
1290 "-Awarnings".to_string(),
1291 "-Dwarnings".to_string()
1292 ], &optgroups()).unwrap();
1293 let registry = diagnostics::registry::Registry::new(&[]);
1294 let sessopts = build_session_options(&matches);
1295 let sess = build_session(sessopts, None, registry,
1296 Rc::new(DummyCrateStore));
1297 assert!(sess.diagnostic().can_emit_warnings);
1301 let matches = getopts(&[
1302 "-Adead_code".to_string()
1303 ], &optgroups()).unwrap();
1304 let registry = diagnostics::registry::Registry::new(&[]);
1305 let sessopts = build_session_options(&matches);
1306 let sess = build_session(sessopts, None, registry,
1307 Rc::new(DummyCrateStore));
1308 assert!(sess.diagnostic().can_emit_warnings);