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::OutputType::*;
19 pub use self::DebugInfoLevel::*;
21 use session::{early_error, early_warn, Session};
22 use session::search_paths::SearchPaths;
24 use rustc_back::target::Target;
29 use syntax::ast::{IntTy, UintTy};
31 use syntax::attr::AttrMetaMethods;
32 use syntax::diagnostic::{ColorConfig, Auto, Always, Never, SpanHandler};
34 use syntax::parse::token::InternedString;
36 use std::collections::HashMap;
37 use std::collections::hash_map::Entry::{Occupied, Vacant};
46 pub uint_type: UintTy,
49 #[derive(Clone, Copy, PartialEq)]
57 #[derive(Clone, Copy, PartialEq)]
58 pub enum DebugInfoLevel {
64 #[derive(Clone, Copy, PartialEq, PartialOrd, Ord, Eq)]
68 OutputTypeLlvmAssembly,
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 debuginfo: DebugInfoLevel,
83 pub lint_opts: Vec<(String, lint::Level)>,
84 pub describe_lints: bool,
85 pub output_types: Vec<OutputType> ,
86 // This was mutable for rustpkg, which updates search paths based on the
87 // parsed code. It remains mutable in case its replacements wants to use
89 pub search_paths: SearchPaths,
90 pub libs: Vec<(String, cstore::NativeLibraryKind)>,
91 pub maybe_sysroot: Option<Path>,
92 pub target_triple: String,
93 // User-specified cfg meta items. The compiler itself will add additional
94 // items to the crate config, and during parsing the entire crate config
95 // will be added to the crate AST node. This should not be used for
96 // anything except building the full crate config prior to parsing.
97 pub cfg: ast::CrateConfig,
101 pub no_analysis: bool,
102 pub debugging_opts: u64,
103 /// Whether to write dependency files. It's (enabled, optional filename).
104 pub write_dependency_info: (bool, Option<Path>),
105 pub prints: Vec<PrintRequest>,
106 pub cg: CodegenOptions,
107 pub color: ColorConfig,
108 pub show_span: Option<String>,
109 pub externs: HashMap<String, Vec<String>>,
110 pub crate_name: Option<String>,
111 /// An optional name to use as the crate for std during std injection,
112 /// written `extern crate std = "name"`. Default to "std". Used by
113 /// out-of-tree drivers.
114 pub alt_std_name: Option<String>,
115 /// Indicates how the compiler should treat unstable features
116 pub unstable_features: UnstableFeatures
119 #[deriving(Clone, Copy)]
120 pub enum UnstableFeatures {
121 /// Hard errors for unstable features are active, as on
122 /// beta/stable channels.
124 /// Use the default lint levels
126 /// Errors are bypassed for bootstrapping. This is required any time
127 /// during the build that feature-related lints are set to warn or above
128 /// because the build turns on warnings-as-errors and uses lots of unstable
129 /// features. As a result, this this is always required for building Rust
134 #[derive(Clone, PartialEq, Eq)]
135 #[allow(missing_copy_implementations)]
136 pub enum PrintRequest {
143 /// Load source from file
145 /// The string is the source
150 pub fn filestem(&self) -> String {
152 Input::File(ref ifile) => ifile.filestem_str().unwrap().to_string(),
153 Input::Str(_) => "rust_out".to_string(),
159 pub struct OutputFilenames {
160 pub out_directory: Path,
161 pub out_filestem: String,
162 pub single_output_file: Option<Path>,
166 impl OutputFilenames {
167 pub fn path(&self, flavor: OutputType) -> Path {
168 match self.single_output_file {
169 Some(ref path) => return path.clone(),
172 self.temp_path(flavor)
175 pub fn temp_path(&self, flavor: OutputType) -> Path {
176 let base = self.out_directory.join(self.filestem());
178 OutputTypeBitcode => base.with_extension("bc"),
179 OutputTypeAssembly => base.with_extension("s"),
180 OutputTypeLlvmAssembly => base.with_extension("ll"),
181 OutputTypeObject => base.with_extension("o"),
182 OutputTypeDepInfo => base.with_extension("d"),
183 OutputTypeExe => base,
187 pub fn with_extension(&self, extension: &str) -> Path {
188 self.out_directory.join(self.filestem()).with_extension(extension)
191 pub fn filestem(&self) -> String {
192 format!("{}{}", self.out_filestem, self.extra)
196 pub fn host_triple() -> &'static str {
197 // Get the host triple out of the build environment. This ensures that our
198 // idea of the host triple is the same as for the set of libraries we've
199 // actually built. We can't just take LLVM's host triple because they
200 // normalize all ix86 architectures to i386.
202 // Instead of grabbing the host triple (for the current host), we grab (at
203 // compile time) the target triple that this rustc is built with and
204 // calling that (at runtime) the host triple.
205 (option_env!("CFG_COMPILER_HOST_TRIPLE")).
206 expect("CFG_COMPILER_HOST_TRIPLE")
209 /// Some reasonable defaults
210 pub fn basic_options() -> Options {
212 crate_types: Vec::new(),
215 debuginfo: NoDebugInfo,
216 lint_opts: Vec::new(),
217 describe_lints: false,
218 output_types: Vec::new(),
219 search_paths: SearchPaths::new(),
221 target_triple: host_triple().to_string(),
228 write_dependency_info: (false, None),
230 cg: basic_codegen_options(),
233 externs: HashMap::new(),
237 unstable_features: UnstableFeatures::Disallow
241 // The type of entry function, so
242 // users can have their own entry
243 // functions that don't start a
245 #[derive(Copy, PartialEq)]
246 pub enum EntryFnType {
252 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash)]
260 macro_rules! debugging_opts {
261 ([ $opt:ident ] $cnt:expr ) => (
262 pub const $opt: u64 = 1 << $cnt;
264 ([ $opt:ident, $($rest:ident),* ] $cnt:expr ) => (
265 pub const $opt: u64 = 1 << $cnt;
266 debugging_opts! { [ $($rest),* ] $cnt + 1 }
291 PRINT_MOVE_FRAGMENTS,
292 FLOWGRAPH_PRINT_LOANS,
293 FLOWGRAPH_PRINT_MOVES,
294 FLOWGRAPH_PRINT_ASSIGNS,
306 pub fn debugging_opts_map() -> Vec<(&'static str, &'static str, u64)> {
307 vec![("verbose", "in general, enable more debug printouts", VERBOSE),
308 ("time-passes", "measure time of each rustc pass", TIME_PASSES),
309 ("count-llvm-insns", "count where LLVM \
310 instrs originate", COUNT_LLVM_INSNS),
311 ("time-llvm-passes", "measure time of each LLVM pass",
313 ("trans-stats", "gather trans statistics", TRANS_STATS),
314 ("asm-comments", "generate comments into the assembly (may change behavior)",
316 ("no-verify", "skip LLVM verification", NO_VERIFY),
317 ("borrowck-stats", "gather borrowck statistics", BORROWCK_STATS),
318 ("no-landing-pads", "omit landing pads for unwinding",
320 ("debug-llvm", "enable debug output from LLVM", DEBUG_LLVM),
321 ("count-type-sizes", "count the sizes of aggregate types",
323 ("meta-stats", "gather metadata statistics", META_STATS),
324 ("print-link-args", "Print the arguments passed to the linker",
326 ("gc", "Garbage collect shared data (experimental)", GC),
327 ("print-llvm-passes",
328 "Prints the llvm optimization passes being run",
330 ("ast-json", "Print the AST as JSON and halt", AST_JSON),
331 ("ast-json-noexpand", "Print the pre-expansion AST as JSON and halt", AST_JSON_NOEXPAND),
332 ("ls", "List the symbols defined by a library crate", LS),
333 ("save-analysis", "Write syntax and type analysis information \
334 in addition to normal output", SAVE_ANALYSIS),
335 ("print-move-fragments", "Print out move-fragment data for every fn",
336 PRINT_MOVE_FRAGMENTS),
337 ("flowgraph-print-loans", "Include loan analysis data in \
338 --pretty flowgraph output", FLOWGRAPH_PRINT_LOANS),
339 ("flowgraph-print-moves", "Include move analysis data in \
340 --pretty flowgraph output", FLOWGRAPH_PRINT_MOVES),
341 ("flowgraph-print-assigns", "Include assignment analysis data in \
342 --pretty flowgraph output", FLOWGRAPH_PRINT_ASSIGNS),
343 ("flowgraph-print-all", "Include all dataflow analysis data in \
344 --pretty flowgraph output", FLOWGRAPH_PRINT_ALL),
345 ("print-region-graph", "Prints region inference graph. \
346 Use with RUST_REGION_GRAPH=help for more info",
348 ("parse-only", "Parse only; do not compile, assemble, or link", PARSE_ONLY),
349 ("no-trans", "Run all passes except translation; no output", NO_TRANS),
350 ("no-analysis", "Parse and expand the source, but run no analysis and",
352 ("unstable-options", "Adds unstable command line options to rustc interface",
354 ("print-enum-sizes", "Print the size of enums and their variants", PRINT_ENUM_SIZES),
360 SomePasses(Vec<String>),
365 pub fn is_empty(&self) -> bool {
367 SomePasses(ref v) => v.is_empty(),
373 /// Declare a macro that will define all CodegenOptions fields and parsers all
374 /// at once. The goal of this macro is to define an interface that can be
375 /// programmatically used by the option parser in order to initialize the struct
376 /// without hardcoding field names all over the place.
378 /// The goal is to invoke this macro once with the correct fields, and then this
379 /// macro generates all necessary code. The main gotcha of this macro is the
380 /// cgsetters module which is a bunch of generated code to parse an option into
381 /// its respective field in the struct. There are a few hand-written parsers for
382 /// parsing specific types of values in this module.
383 macro_rules! cgoptions {
384 ($($opt:ident : $t:ty = ($init:expr, $parse:ident, $desc:expr)),* ,) =>
387 pub struct CodegenOptions { $(pub $opt: $t),* }
389 pub fn basic_codegen_options() -> CodegenOptions {
390 CodegenOptions { $($opt: $init),* }
393 pub type CodegenSetter = fn(&mut CodegenOptions, v: Option<&str>) -> bool;
394 pub const CG_OPTIONS: &'static [(&'static str, CodegenSetter,
395 Option<&'static str>, &'static str)] =
396 &[ $( (stringify!($opt), cgsetters::$opt, cg_type_descs::$parse, $desc) ),* ];
398 #[allow(non_upper_case_globals)]
400 pub const parse_bool: Option<&'static str> = None;
401 pub const parse_opt_bool: Option<&'static str> = None;
402 pub const parse_string: Option<&'static str> = Some("a string");
403 pub const parse_opt_string: Option<&'static str> = Some("a string");
404 pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
405 pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
406 pub const parse_uint: Option<&'static str> = Some("a number");
407 pub const parse_passes: Option<&'static str> =
408 Some("a space-separated list of passes, or `all`");
409 pub const parse_opt_uint: Option<&'static str> =
414 use super::{CodegenOptions, Passes, SomePasses, AllPasses};
417 pub fn $opt(cg: &mut CodegenOptions, v: Option<&str>) -> bool {
418 $parse(&mut cg.$opt, v)
422 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
425 None => { *slot = true; true }
429 fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
432 None => { *slot = Some(true); true }
436 fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
438 Some(s) => { *slot = Some(s.to_string()); true },
443 fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
445 Some(s) => { *slot = s.to_string(); true },
450 fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
455 slot.push(s.to_string());
463 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
467 let v = s.words().map(|s| s.to_string()).collect();
475 fn parse_uint(slot: &mut uint, v: Option<&str>) -> bool {
476 match v.and_then(|s| s.parse()) {
477 Some(i) => { *slot = i; true },
482 fn parse_opt_uint(slot: &mut Option<uint>, v: Option<&str>) -> bool {
484 Some(s) => { *slot = s.parse(); slot.is_some() }
485 None => { *slot = None; true }
489 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
496 let mut passes = vec!();
497 if parse_list(&mut passes, v) {
498 *slot = SomePasses(passes);
510 ar: Option<String> = (None, parse_opt_string,
511 "tool to assemble archives with"),
512 linker: Option<String> = (None, parse_opt_string,
513 "system linker to link outputs with"),
514 link_args: Option<Vec<String>> = (None, parse_opt_list,
515 "extra arguments to pass to the linker (space separated)"),
516 lto: bool = (false, parse_bool,
517 "perform LLVM link-time optimizations"),
518 target_cpu: Option<String> = (None, parse_opt_string,
519 "select target processor (llc -mcpu=help for details)"),
520 target_feature: String = ("".to_string(), parse_string,
521 "target specific attributes (llc -mattr=help for details)"),
522 passes: Vec<String> = (Vec::new(), parse_list,
523 "a list of extra LLVM passes to run (space separated)"),
524 llvm_args: Vec<String> = (Vec::new(), parse_list,
525 "a list of arguments to pass to llvm (space separated)"),
526 save_temps: bool = (false, parse_bool,
527 "save all temporary output files during compilation"),
528 rpath: bool = (false, parse_bool,
529 "set rpath values in libs/exes"),
530 no_prepopulate_passes: bool = (false, parse_bool,
531 "don't pre-populate the pass manager with a list of passes"),
532 no_vectorize_loops: bool = (false, parse_bool,
533 "don't run the loop vectorization optimization passes"),
534 no_vectorize_slp: bool = (false, parse_bool,
535 "don't run LLVM's SLP vectorization pass"),
536 soft_float: bool = (false, parse_bool,
537 "generate software floating point library calls"),
538 prefer_dynamic: bool = (false, parse_bool,
539 "prefer dynamic linking to static linking"),
540 no_integrated_as: bool = (false, parse_bool,
541 "use an external assembler rather than LLVM's integrated one"),
542 no_redzone: Option<bool> = (None, parse_opt_bool,
543 "disable the use of the redzone"),
544 relocation_model: Option<String> = (None, parse_opt_string,
545 "choose the relocation model to use (llc -relocation-model for details)"),
546 code_model: Option<String> = (None, parse_opt_string,
547 "choose the code model to use (llc -code-model for details)"),
548 metadata: Vec<String> = (Vec::new(), parse_list,
549 "metadata to mangle symbol names with"),
550 extra_filename: String = ("".to_string(), parse_string,
551 "extra data to put in each output filename"),
552 codegen_units: uint = (1, parse_uint,
553 "divide crate into N units to optimize in parallel"),
554 remark: Passes = (SomePasses(Vec::new()), parse_passes,
555 "print remarks for these optimization passes (space separated, or \"all\")"),
556 no_stack_check: bool = (false, parse_bool,
557 "disable checks for stack exhaustion (a memory-safety hazard!)"),
558 debuginfo: Option<uint> = (None, parse_opt_uint,
559 "debug info emission level, 0 = no debug info, 1 = line tables only, \
560 2 = full debug info with variable and type information"),
561 opt_level: Option<uint> = (None, parse_opt_uint,
562 "Optimize with possible levels 0-3"),
565 pub fn build_codegen_options(matches: &getopts::Matches) -> CodegenOptions
567 let mut cg = basic_codegen_options();
568 for option in matches.opt_strs("C").into_iter() {
569 let mut iter = option.splitn(1, '=');
570 let key = iter.next().unwrap();
571 let value = iter.next();
572 let option_to_lookup = key.replace("-", "_");
573 let mut found = false;
574 for &(candidate, setter, opt_type_desc, _) in CG_OPTIONS.iter() {
575 if option_to_lookup != candidate { continue }
576 if !setter(&mut cg, value) {
577 match (value, opt_type_desc) {
578 (Some(..), None) => {
579 early_error(&format!("codegen option `{}` takes no \
582 (None, Some(type_desc)) => {
583 early_error(&format!("codegen option `{0}` requires \
584 {1} (-C {0}=<value>)",
587 (Some(value), Some(type_desc)) => {
588 early_error(&format!("incorrect value `{}` for codegen \
589 option `{}` - {} was expected",
590 value, key, type_desc)[])
592 (None, None) => unreachable!()
599 early_error(&format!("unknown codegen option: `{}`",
606 pub fn default_lib_output() -> CrateType {
610 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
611 use syntax::parse::token::intern_and_get_ident as intern;
613 let end = &sess.target.target.target_endian[];
614 let arch = &sess.target.target.arch[];
615 let wordsz = &sess.target.target.target_pointer_width[];
616 let os = &sess.target.target.target_os[];
618 let fam = match sess.target.target.options.is_like_windows {
619 true => InternedString::new("windows"),
620 false => InternedString::new("unix")
623 let mk = attr::mk_name_value_item_str;
624 return vec!(// Target bindings.
625 attr::mk_word_item(fam.clone()),
626 mk(InternedString::new("target_os"), intern(os)),
627 mk(InternedString::new("target_family"), fam),
628 mk(InternedString::new("target_arch"), intern(arch)),
629 mk(InternedString::new("target_endian"), intern(end)),
630 mk(InternedString::new("target_pointer_width"),
635 pub fn append_configuration(cfg: &mut ast::CrateConfig,
636 name: InternedString) {
637 if !cfg.iter().any(|mi| mi.name() == name) {
638 cfg.push(attr::mk_word_item(name))
642 pub fn build_configuration(sess: &Session) -> ast::CrateConfig {
643 // Combine the configuration requested by the session (command line) with
644 // some default and generated configuration items
645 let default_cfg = default_configuration(sess);
646 let mut user_cfg = sess.opts.cfg.clone();
647 // If the user wants a test runner, then add the test cfg
649 append_configuration(&mut user_cfg, InternedString::new("test"))
651 let mut v = user_cfg.into_iter().collect::<Vec<_>>();
652 v.push_all(&default_cfg[]);
656 pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config {
657 let target = match Target::search(&opts.target_triple[]) {
660 sp.handler().fatal((format!("Error loading target specification: {}", e)).as_slice());
664 let (int_type, uint_type) = match &target.target_pointer_width[] {
665 "32" => (ast::TyI32, ast::TyU32),
666 "64" => (ast::TyI64, ast::TyU64),
667 w => sp.handler().fatal(&format!("target specification was invalid: unrecognized \
668 target-word-size {}", w)[])
674 uint_type: uint_type,
678 /// Returns the "short" subset of the stable rustc command line options.
679 pub fn short_optgroups() -> Vec<getopts::OptGroup> {
680 rustc_short_optgroups().into_iter()
681 .filter(|g|g.is_stable())
686 /// Returns all of the stable rustc command line options.
687 pub fn optgroups() -> Vec<getopts::OptGroup> {
688 rustc_optgroups().into_iter()
689 .filter(|g|g.is_stable())
694 #[derive(Copy, Clone, PartialEq, Eq, Show)]
695 pub enum OptionStability { Stable, Unstable }
697 #[derive(Clone, PartialEq, Eq)]
698 pub struct RustcOptGroup {
699 pub opt_group: getopts::OptGroup,
700 pub stability: OptionStability,
704 pub fn is_stable(&self) -> bool {
705 self.stability == OptionStability::Stable
708 fn stable(g: getopts::OptGroup) -> RustcOptGroup {
709 RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
712 fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
713 RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
717 // The `opt` local module holds wrappers around the `getopts` API that
718 // adds extra rustc-specific metadata to each option; such metadata
719 // is exposed by . The public
720 // functions below ending with `_u` are the functions that return
721 // *unstable* options, i.e. options that are only enabled when the
722 // user also passes the `-Z unstable-options` debugging flag.
724 // The `fn opt_u` etc below are written so that we can use them
725 // in the future; do not warn about them not being used right now.
729 use super::RustcOptGroup;
731 type R = RustcOptGroup;
732 type S<'a> = &'a str;
734 fn stable(g: getopts::OptGroup) -> R { RustcOptGroup::stable(g) }
735 fn unstable(g: getopts::OptGroup) -> R { RustcOptGroup::unstable(g) }
737 // FIXME (pnkfelix): We default to stable since the current set of
738 // options is defacto stable. However, it would be good to revise the
739 // code so that a stable option is the thing that takes extra effort
742 pub fn opt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optopt(a, b, c, d)) }
743 pub fn multi(a: S, b: S, c: S, d: S) -> R { stable(getopts::optmulti(a, b, c, d)) }
744 pub fn flag(a: S, b: S, c: S) -> R { stable(getopts::optflag(a, b, c)) }
745 pub fn flagopt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optflagopt(a, b, c, d)) }
747 pub fn opt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optopt(a, b, c, d)) }
748 pub fn multi_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optmulti(a, b, c, d)) }
749 pub fn flag_u(a: S, b: S, c: S) -> R { unstable(getopts::optflag(a, b, c)) }
750 pub fn flagopt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optflagopt(a, b, c, d)) }
753 /// Returns the "short" subset of the rustc command line options,
754 /// including metadata for each option, such as whether the option is
755 /// part of the stable long-term interface for rustc.
756 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
758 opt::flag("h", "help", "Display this message"),
759 opt::multi("", "cfg", "Configure the compilation environment", "SPEC"),
760 opt::multi("L", "", "Add a directory to the library search path", "PATH"),
761 opt::multi("l", "", "Link the generated crate(s) to the specified native
762 library NAME. The optional KIND can be one of,
763 static, dylib, or framework. If omitted, dylib is
764 assumed.", "[KIND=]NAME"),
765 opt::multi("", "crate-type", "Comma separated list of types of crates
766 for the compiler to emit",
767 "[bin|lib|rlib|dylib|staticlib]"),
768 opt::opt("", "crate-name", "Specify the name of the crate being built",
770 opt::multi("", "emit", "Comma separated list of types of output for \
771 the compiler to emit",
772 "[asm|llvm-bc|llvm-ir|obj|link|dep-info]"),
773 opt::multi("", "print", "Comma separated list of compiler information to \
775 "[crate-name|file-names|sysroot]"),
776 opt::flag("g", "", "Equivalent to -C debuginfo=2"),
777 opt::flag("O", "", "Equivalent to -C opt-level=2"),
778 opt::opt("o", "", "Write output to <filename>", "FILENAME"),
779 opt::opt("", "out-dir", "Write output to compiler-chosen filename \
781 opt::opt("", "explain", "Provide a detailed explanation of an error \
783 opt::flag("", "test", "Build a test harness"),
784 opt::opt("", "target", "Target triple cpu-manufacturer-kernel[-os] \
785 to compile for (see chapter 3.4 of \
786 http://www.sourceware.org/autobook/
789 opt::multi("W", "warn", "Set lint warnings", "OPT"),
790 opt::multi("A", "allow", "Set lint allowed", "OPT"),
791 opt::multi("D", "deny", "Set lint denied", "OPT"),
792 opt::multi("F", "forbid", "Set lint forbidden", "OPT"),
793 opt::multi("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
794 opt::flag("V", "version", "Print version info and exit"),
795 opt::flag("v", "verbose", "Use verbose output"),
799 /// Returns all rustc command line options, including metadata for
800 /// each option, such as whether the option is part of the stable
801 /// long-term interface for rustc.
802 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
803 let mut opts = rustc_short_optgroups();
805 opt::multi("", "extern", "Specify where an external rust library is \
808 opt::opt("", "opt-level", "Optimize with possible levels 0-3", "LEVEL"),
809 opt::opt("", "sysroot", "Override the system root", "PATH"),
810 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
811 opt::opt("", "color", "Configure coloring of output:
812 auto = colorize, if output goes to a tty (default);
813 always = always colorize output;
814 never = never colorize output", "auto|always|never"),
817 opt::flag("", "print-crate-name", "Output the crate name and exit"),
818 opt::flag("", "print-file-name", "Output the file(s) that would be \
819 written if compilation \
820 continued and exit"),
821 opt::opt("", "debuginfo", "Emit DWARF debug info to the objects created:
823 1 = line-tables only (for stacktraces and breakpoints),
824 2 = full debug info with variable and type information \
825 (same as -g)", "LEVEL"),
826 opt::flag("", "no-trans", "Run all passes except translation; no output"),
827 opt::flag("", "no-analysis", "Parse and expand the source, but run no \
828 analysis and produce no output"),
829 opt::flag("", "parse-only", "Parse only; do not compile, assemble, \
831 opt::flagopt("", "pretty",
832 "Pretty-print the input instead of compiling;
833 valid types are: `normal` (un-annotated source),
834 `expanded` (crates expanded),
835 `typed` (crates expanded, with type annotations), or
836 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
838 opt::flagopt_u("", "xpretty",
839 "Pretty-print the input instead of compiling, unstable variants;
840 valid types are any of the types for `--pretty`, as well as:
841 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node), or
842 `everybody_loops` (all function bodies replaced with `loop {}`).",
844 opt::opt_u("", "show-span", "Show spans for compiler debugging", "expr|pat|ty"),
845 opt::flagopt("", "dep-info",
846 "Output dependency info to <filename> after compiling, \
847 in a format suitable for use by Makefiles", "FILENAME"),
852 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
853 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
854 cfgspecs.into_iter().map(|s| {
855 parse::parse_meta_from_source_str("cfgspec".to_string(),
858 &parse::new_parse_sess())
859 }).collect::<ast::CrateConfig>()
862 pub fn build_session_options(matches: &getopts::Matches) -> Options {
864 let unparsed_crate_types = matches.opt_strs("crate-type");
865 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
866 .unwrap_or_else(|e| early_error(&e[]));
868 let mut lint_opts = vec!();
869 let mut describe_lints = false;
871 for &level in [lint::Allow, lint::Warn, lint::Deny, lint::Forbid].iter() {
872 for lint_name in matches.opt_strs(level.as_str()).into_iter() {
873 if lint_name == "help" {
874 describe_lints = true;
876 lint_opts.push((lint_name.replace("-", "_"), level));
881 let mut debugging_opts = 0;
882 let debug_flags = matches.opt_strs("Z");
883 let debug_map = debugging_opts_map();
884 for debug_flag in debug_flags.iter() {
885 let mut this_bit = 0;
886 for &(name, _, bit) in debug_map.iter() {
887 if name == *debug_flag {
893 early_error(&format!("unknown debug flag: {}",
896 debugging_opts |= this_bit;
899 let parse_only = if matches.opt_present("parse-only") {
900 // FIXME(acrichto) remove this eventually
901 early_warn("--parse-only is deprecated in favor of -Z parse-only");
904 debugging_opts & PARSE_ONLY != 0
906 let no_trans = if matches.opt_present("no-trans") {
907 // FIXME(acrichto) remove this eventually
908 early_warn("--no-trans is deprecated in favor of -Z no-trans");
911 debugging_opts & NO_TRANS != 0
913 let no_analysis = if matches.opt_present("no-analysis") {
914 // FIXME(acrichto) remove this eventually
915 early_warn("--no-analysis is deprecated in favor of -Z no-analysis");
918 debugging_opts & NO_ANALYSIS != 0
921 if debugging_opts & DEBUG_LLVM != 0 {
922 unsafe { llvm::LLVMSetDebug(1); }
925 let mut output_types = Vec::new();
926 if !parse_only && !no_trans {
927 let unparsed_output_types = matches.opt_strs("emit");
928 for unparsed_output_type in unparsed_output_types.iter() {
929 for part in unparsed_output_type.split(',') {
930 let output_type = match part.as_slice() {
931 "asm" => OutputTypeAssembly,
932 "llvm-ir" => OutputTypeLlvmAssembly,
933 "llvm-bc" => OutputTypeBitcode,
934 "obj" => OutputTypeObject,
935 "link" => OutputTypeExe,
936 "dep-info" => OutputTypeDepInfo,
938 early_error(&format!("unknown emission type: `{}`",
942 output_types.push(output_type)
947 output_types.dedup();
948 if output_types.len() == 0 {
949 output_types.push(OutputTypeExe);
952 let cg = build_codegen_options(matches);
954 let sysroot_opt = matches.opt_str("sysroot").map(|m| Path::new(m));
955 let target = matches.opt_str("target").unwrap_or(
956 host_triple().to_string());
958 if matches.opt_present("O") {
959 if matches.opt_present("opt-level") {
960 early_error("-O and --opt-level both provided");
962 if cg.opt_level.is_some() {
963 early_error("-O and -C opt-level both provided");
966 } else if matches.opt_present("opt-level") {
967 // FIXME(acrichto) remove this eventually
968 early_warn("--opt-level=N is deprecated in favor of -C opt-level=N");
969 match matches.opt_str("opt-level").as_ref().map(|s| s.as_slice()) {
973 Some("2") => Default,
974 Some("3") => Aggressive,
976 early_error(&format!("optimization level needs to be \
977 between 0-3 (instead was `{}`)",
987 Some(3) => Aggressive,
989 early_error(format!("optimization level needs to be \
990 between 0-3 (instead was `{}`)",
996 let gc = debugging_opts & GC != 0;
997 let debuginfo = if matches.opt_present("g") {
998 if matches.opt_present("debuginfo") {
999 early_error("-g and --debuginfo both provided");
1001 if cg.debuginfo.is_some() {
1002 early_error("-g and -C debuginfo both provided");
1005 } else if matches.opt_present("debuginfo") {
1006 // FIXME(acrichto) remove this eventually
1007 early_warn("--debuginfo=N is deprecated in favor of -C debuginfo=N");
1008 match matches.opt_str("debuginfo").as_ref().map(|s| s.as_slice()) {
1009 Some("0") => NoDebugInfo,
1010 Some("1") => LimitedDebugInfo,
1012 Some("2") => FullDebugInfo,
1014 early_error(&format!("debug info level needs to be between \
1015 0-2 (instead was `{}`)",
1020 match cg.debuginfo {
1021 None | Some(0) => NoDebugInfo,
1022 Some(1) => LimitedDebugInfo,
1023 Some(2) => FullDebugInfo,
1025 early_error(format!("debug info level needs to be between \
1026 0-2 (instead was `{}`)",
1032 let mut search_paths = SearchPaths::new();
1033 for s in matches.opt_strs("L").iter() {
1034 search_paths.add_path(&s[]);
1037 let libs = matches.opt_strs("l").into_iter().map(|s| {
1038 let mut parts = s.splitn(1, '=');
1039 let kind = parts.next().unwrap();
1040 if let Some(name) = parts.next() {
1041 let kind = match kind {
1042 "dylib" => cstore::NativeUnknown,
1043 "framework" => cstore::NativeFramework,
1044 "static" => cstore::NativeStatic,
1046 early_error(format!("unknown library kind `{}`, expected \
1047 one of dylib, framework, or static",
1051 return (name.to_string(), kind)
1054 // FIXME(acrichto) remove this once crates have stopped using it, this
1055 // is deprecated behavior now.
1056 let mut parts = s.rsplitn(1, ':');
1057 let kind = parts.next().unwrap();
1058 let (name, kind) = match (parts.next(), kind) {
1060 (Some(name), "dylib") => (name, cstore::NativeUnknown),
1061 (Some(name), "framework") => (name, cstore::NativeFramework),
1062 (Some(name), "static") => (name, cstore::NativeStatic),
1064 early_error(&format!("unknown library kind `{}`, expected \
1065 one of dylib, framework, or static",
1069 (name.to_string(), kind)
1072 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
1073 let test = matches.opt_present("test");
1074 let write_dependency_info = if matches.opt_present("dep-info") {
1075 // FIXME(acrichto) remove this eventually
1076 early_warn("--dep-info has been deprecated in favor of --emit");
1077 (true, matches.opt_str("dep-info").map(|p| Path::new(p)))
1079 (output_types.contains(&OutputTypeDepInfo), None)
1082 let mut prints = matches.opt_strs("print").into_iter().map(|s| {
1083 match s.as_slice() {
1084 "crate-name" => PrintRequest::CrateName,
1085 "file-names" => PrintRequest::FileNames,
1086 "sysroot" => PrintRequest::Sysroot,
1088 early_error(format!("unknown print request `{}`", req).as_slice())
1091 }).collect::<Vec<_>>();
1092 if matches.opt_present("print-crate-name") {
1093 // FIXME(acrichto) remove this eventually
1094 early_warn("--print-crate-name has been deprecated in favor of \
1095 --print crate-name");
1096 prints.push(PrintRequest::CrateName);
1098 if matches.opt_present("print-file-name") {
1099 // FIXME(acrichto) remove this eventually
1100 early_warn("--print-file-name has been deprecated in favor of \
1101 --print file-names");
1102 prints.push(PrintRequest::FileNames);
1105 if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
1106 early_warn("-C remark will not show source locations without \
1110 let color = match matches.opt_str("color").as_ref().map(|s| &s[]) {
1111 Some("auto") => Auto,
1112 Some("always") => Always,
1113 Some("never") => Never,
1118 early_error(&format!("argument for --color must be auto, always \
1119 or never (instead was `{}`)",
1124 let mut externs = HashMap::new();
1125 for arg in matches.opt_strs("extern").iter() {
1126 let mut parts = arg.splitn(1, '=');
1127 let name = match parts.next() {
1129 None => early_error("--extern value must not be empty"),
1131 let location = match parts.next() {
1133 None => early_error("--extern value must be of the format `foo=bar`"),
1136 match externs.entry(name.to_string()) {
1137 Vacant(entry) => { entry.insert(vec![location.to_string()]); },
1138 Occupied(mut entry) => { entry.get_mut().push(location.to_string()); },
1142 let crate_name = matches.opt_str("crate-name");
1145 crate_types: crate_types,
1147 optimize: opt_level,
1148 debuginfo: debuginfo,
1149 lint_opts: lint_opts,
1150 describe_lints: describe_lints,
1151 output_types: output_types,
1152 search_paths: search_paths,
1153 maybe_sysroot: sysroot_opt,
1154 target_triple: target,
1157 parse_only: parse_only,
1159 no_analysis: no_analysis,
1160 debugging_opts: debugging_opts,
1161 write_dependency_info: write_dependency_info,
1167 crate_name: crate_name,
1170 unstable_features: UnstableFeatures::Disallow
1174 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
1176 let mut crate_types: Vec<CrateType> = Vec::new();
1177 for unparsed_crate_type in list_list.iter() {
1178 for part in unparsed_crate_type.split(',') {
1179 let new_part = match part {
1180 "lib" => default_lib_output(),
1181 "rlib" => CrateTypeRlib,
1182 "staticlib" => CrateTypeStaticlib,
1183 "dylib" => CrateTypeDylib,
1184 "bin" => CrateTypeExecutable,
1186 return Err(format!("unknown crate type: `{}`",
1190 crate_types.push(new_part)
1194 return Ok(crate_types);
1197 impl fmt::Show for CrateType {
1198 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1200 CrateTypeExecutable => "bin".fmt(f),
1201 CrateTypeDylib => "dylib".fmt(f),
1202 CrateTypeRlib => "rlib".fmt(f),
1203 CrateTypeStaticlib => "staticlib".fmt(f)
1211 use session::config::{build_configuration, optgroups, build_session_options};
1212 use session::build_session;
1214 use getopts::getopts;
1216 use syntax::attr::AttrMetaMethods;
1217 use syntax::diagnostics;
1219 // When the user supplies --test we should implicitly supply --cfg test
1221 fn test_switch_implies_cfg_test() {
1223 &match getopts(&["--test".to_string()], &optgroups()[]) {
1225 Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
1227 let registry = diagnostics::registry::Registry::new(&[]);
1228 let sessopts = build_session_options(matches);
1229 let sess = build_session(sessopts, None, registry);
1230 let cfg = build_configuration(&sess);
1231 assert!((attr::contains_name(&cfg[], "test")));
1234 // When the user supplies --test and --cfg test, don't implicitly add
1235 // another --cfg test
1237 fn test_switch_implies_cfg_test_unless_cfg_test() {
1239 &match getopts(&["--test".to_string(), "--cfg=test".to_string()],
1243 panic!("test_switch_implies_cfg_test_unless_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);
1249 let cfg = build_configuration(&sess);
1250 let mut test_items = cfg.iter().filter(|m| m.name() == "test");
1251 assert!(test_items.next().is_some());
1252 assert!(test_items.next().is_none());
1256 fn test_can_print_warnings() {
1258 let matches = getopts(&[
1259 "-Awarnings".to_string()
1260 ], &optgroups()[]).unwrap();
1261 let registry = diagnostics::registry::Registry::new(&[]);
1262 let sessopts = build_session_options(&matches);
1263 let sess = build_session(sessopts, None, registry);
1264 assert!(!sess.can_print_warnings);
1268 let matches = getopts(&[
1269 "-Awarnings".to_string(),
1270 "-Dwarnings".to_string()
1271 ], &optgroups()[]).unwrap();
1272 let registry = diagnostics::registry::Registry::new(&[]);
1273 let sessopts = build_session_options(&matches);
1274 let sess = build_session(sessopts, None, registry);
1275 assert!(sess.can_print_warnings);
1279 let matches = getopts(&[
1280 "-Adead_code".to_string()
1281 ], &optgroups()[]).unwrap();
1282 let registry = diagnostics::registry::Registry::new(&[]);
1283 let sessopts = build_session_options(&matches);
1284 let sess = build_session(sessopts, None, registry);
1285 assert!(sess.can_print_warnings);