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: DebuggingOptions,
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 #[derive(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(),
227 debugging_opts: basic_debugging_options(),
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, Show)]
263 SomePasses(Vec<String>),
268 pub fn is_empty(&self) -> bool {
270 SomePasses(ref v) => v.is_empty(),
276 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
277 /// at once. The goal of this macro is to define an interface that can be
278 /// programmatically used by the option parser in order to initialize the struct
279 /// without hardcoding field names all over the place.
281 /// The goal is to invoke this macro once with the correct fields, and then this
282 /// macro generates all necessary code. The main gotcha of this macro is the
283 /// cgsetters module which is a bunch of generated code to parse an option into
284 /// its respective field in the struct. There are a few hand-written parsers for
285 /// parsing specific types of values in this module.
286 macro_rules! options {
287 ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
288 $buildfn:ident, $prefix:expr, $outputname:expr,
289 $stat:ident, $mod_desc:ident, $mod_set:ident,
290 $($opt:ident : $t:ty = ($init:expr, $parse:ident, $desc:expr)),* ,) =>
293 #[allow(missing_copy_implementations)]
294 pub struct $struct_name { $(pub $opt: $t),* }
296 pub fn $defaultfn() -> $struct_name {
297 $struct_name { $($opt: $init),* }
300 pub fn $buildfn(matches: &getopts::Matches) -> $struct_name
302 let mut op = $defaultfn();
303 for option in matches.opt_strs($prefix).into_iter() {
304 let mut iter = option.splitn(1, '=');
305 let key = iter.next().unwrap();
306 let value = iter.next();
307 let option_to_lookup = key.replace("-", "_");
308 let mut found = false;
309 for &(candidate, setter, opt_type_desc, _) in $stat.iter() {
310 if option_to_lookup != candidate { continue }
311 if !setter(&mut op, value) {
312 match (value, opt_type_desc) {
313 (Some(..), None) => {
314 early_error(&format!("{} option `{}` takes no \
315 value", $outputname, key)[])
317 (None, Some(type_desc)) => {
318 early_error(&format!("{0} option `{1}` requires \
319 {2} ({3} {1}=<value>)",
321 type_desc, $prefix)[])
323 (Some(value), Some(type_desc)) => {
324 early_error(&format!("incorrect value `{}` for {} \
325 option `{}` - {} was expected",
329 (None, None) => unreachable!()
336 early_error(&format!("unknown codegen option: `{}`",
343 pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
344 pub const $stat: &'static [(&'static str, $setter_name,
345 Option<&'static str>, &'static str)] =
346 &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
348 #[allow(non_upper_case_globals, dead_code)]
350 pub const parse_bool: Option<&'static str> = None;
351 pub const parse_opt_bool: Option<&'static str> = None;
352 pub const parse_string: Option<&'static str> = Some("a string");
353 pub const parse_opt_string: Option<&'static str> = Some("a string");
354 pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
355 pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
356 pub const parse_uint: Option<&'static str> = Some("a number");
357 pub const parse_passes: Option<&'static str> =
358 Some("a space-separated list of passes, or `all`");
359 pub const parse_opt_uint: Option<&'static str> =
365 use super::{$struct_name, Passes, SomePasses, AllPasses};
368 pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
369 $parse(&mut cg.$opt, v)
373 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
376 None => { *slot = true; true }
380 fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
383 None => { *slot = Some(true); true }
387 fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
389 Some(s) => { *slot = Some(s.to_string()); true },
394 fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
396 Some(s) => { *slot = s.to_string(); true },
401 fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
406 slot.push(s.to_string());
414 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
418 let v = s.words().map(|s| s.to_string()).collect();
426 fn parse_uint(slot: &mut uint, v: Option<&str>) -> bool {
427 match v.and_then(|s| s.parse()) {
428 Some(i) => { *slot = i; true },
433 fn parse_opt_uint(slot: &mut Option<uint>, v: Option<&str>) -> bool {
435 Some(s) => { *slot = s.parse(); slot.is_some() }
436 None => { *slot = None; true }
440 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
447 let mut passes = vec!();
448 if parse_list(&mut passes, v) {
449 *slot = SomePasses(passes);
460 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
461 build_codegen_options, "C", "codegen",
462 CG_OPTIONS, cg_type_desc, cgsetters,
463 ar: Option<String> = (None, parse_opt_string,
464 "tool to assemble archives with"),
465 linker: Option<String> = (None, parse_opt_string,
466 "system linker to link outputs with"),
467 link_args: Option<Vec<String>> = (None, parse_opt_list,
468 "extra arguments to pass to the linker (space separated)"),
469 lto: bool = (false, parse_bool,
470 "perform LLVM link-time optimizations"),
471 target_cpu: Option<String> = (None, parse_opt_string,
472 "select target processor (llc -mcpu=help for details)"),
473 target_feature: String = ("".to_string(), parse_string,
474 "target specific attributes (llc -mattr=help for details)"),
475 passes: Vec<String> = (Vec::new(), parse_list,
476 "a list of extra LLVM passes to run (space separated)"),
477 llvm_args: Vec<String> = (Vec::new(), parse_list,
478 "a list of arguments to pass to llvm (space separated)"),
479 save_temps: bool = (false, parse_bool,
480 "save all temporary output files during compilation"),
481 rpath: bool = (false, parse_bool,
482 "set rpath values in libs/exes"),
483 no_prepopulate_passes: bool = (false, parse_bool,
484 "don't pre-populate the pass manager with a list of passes"),
485 no_vectorize_loops: bool = (false, parse_bool,
486 "don't run the loop vectorization optimization passes"),
487 no_vectorize_slp: bool = (false, parse_bool,
488 "don't run LLVM's SLP vectorization pass"),
489 soft_float: bool = (false, parse_bool,
490 "generate software floating point library calls"),
491 prefer_dynamic: bool = (false, parse_bool,
492 "prefer dynamic linking to static linking"),
493 no_integrated_as: bool = (false, parse_bool,
494 "use an external assembler rather than LLVM's integrated one"),
495 no_redzone: Option<bool> = (None, parse_opt_bool,
496 "disable the use of the redzone"),
497 relocation_model: Option<String> = (None, parse_opt_string,
498 "choose the relocation model to use (llc -relocation-model for details)"),
499 code_model: Option<String> = (None, parse_opt_string,
500 "choose the code model to use (llc -code-model for details)"),
501 metadata: Vec<String> = (Vec::new(), parse_list,
502 "metadata to mangle symbol names with"),
503 extra_filename: String = ("".to_string(), parse_string,
504 "extra data to put in each output filename"),
505 codegen_units: uint = (1, parse_uint,
506 "divide crate into N units to optimize in parallel"),
507 remark: Passes = (SomePasses(Vec::new()), parse_passes,
508 "print remarks for these optimization passes (space separated, or \"all\")"),
509 no_stack_check: bool = (false, parse_bool,
510 "disable checks for stack exhaustion (a memory-safety hazard!)"),
511 debuginfo: Option<uint> = (None, parse_opt_uint,
512 "debug info emission level, 0 = no debug info, 1 = line tables only, \
513 2 = full debug info with variable and type information"),
514 opt_level: Option<uint> = (None, parse_opt_uint,
515 "Optimize with possible levels 0-3"),
519 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
520 build_debugging_options, "Z", "debugging",
521 DB_OPTIONS, db_type_desc, dbsetters,
522 verbose: bool = (false, parse_bool,
523 "in general, enable more debug printouts"),
524 time_passes: bool = (false, parse_bool,
525 "measure time of each rustc pass"),
526 count_llvm_insns: bool = (false, parse_bool,
527 "count where LLVM instrs originate"),
528 time_llvm_passes: bool = (false, parse_bool,
529 "measure time of each LLVM pass"),
530 trans_stats: bool = (false, parse_bool,
531 "gather trans statistics"),
532 asm_comments: bool = (false, parse_bool,
533 "generate comments into the assembly (may change behavior)"),
534 no_verify: bool = (false, parse_bool,
535 "skip LLVM verification"),
536 borrowck_stats: bool = (false, parse_bool,
537 "gather borrowck statistics"),
538 no_landing_pads: bool = (false, parse_bool,
539 "omit landing pads for unwinding"),
540 debug_llvm: bool = (false, parse_bool,
541 "enable debug output from LLVM"),
542 count_type_sizes: bool = (false, parse_bool,
543 "count the sizes of aggregate types"),
544 meta_stats: bool = (false, parse_bool,
545 "gather metadata statistics"),
546 print_link_args: bool = (false, parse_bool,
547 "Print the arguments passed to the linker"),
548 gc: bool = (false, parse_bool,
549 "Garbage collect shared data (experimental)"),
550 print_llvm_passes: bool = (false, parse_bool,
551 "Prints the llvm optimization passes being run"),
552 ast_json: bool = (false, parse_bool,
553 "Print the AST as JSON and halt"),
554 ast_json_noexpand: bool = (false, parse_bool,
555 "Print the pre-expansion AST as JSON and halt"),
556 ls: bool = (false, parse_bool,
557 "List the symbols defined by a library crate"),
558 save_analysis: bool = (false, parse_bool,
559 "Write syntax and type analysis information in addition to normal output"),
560 print_move_fragments: bool = (false, parse_bool,
561 "Print out move-fragment data for every fn"),
562 flowgraph_print_loans: bool = (false, parse_bool,
563 "Include loan analysis data in --pretty flowgraph output"),
564 flowgraph_print_moves: bool = (false, parse_bool,
565 "Include move analysis data in --pretty flowgraph output"),
566 flowgraph_print_assigns: bool = (false, parse_bool,
567 "Include assignment analysis data in --pretty flowgraph output"),
568 flowgraph_print_all: bool = (false, parse_bool,
569 "Include all dataflow analysis data in --pretty flowgraph output"),
570 print_region_graph: bool = (false, parse_bool,
571 "Prints region inference graph. \
572 Use with RUST_REGION_GRAPH=help for more info"),
573 parse_only: bool = (false, parse_bool,
574 "Parse only; do not compile, assemble, or link"),
575 no_trans: bool = (false, parse_bool,
576 "Run all passes except translation; no output"),
577 no_analysis: bool = (false, parse_bool,
578 "Parse and expand the source, but run no analysis"),
579 extra_plugins: Vec<String> = (Vec::new(), parse_list,
580 "load extra plugins"),
581 unstable_options: bool = (false, parse_bool,
582 "Adds unstable command line options to rustc interface"),
583 print_enum_sizes: bool = (false, parse_bool,
584 "Print the size of enums and their variants"),
587 pub fn default_lib_output() -> CrateType {
591 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
592 use syntax::parse::token::intern_and_get_ident as intern;
594 let end = &sess.target.target.target_endian[];
595 let arch = &sess.target.target.arch[];
596 let wordsz = &sess.target.target.target_pointer_width[];
597 let os = &sess.target.target.target_os[];
599 let fam = match sess.target.target.options.is_like_windows {
600 true => InternedString::new("windows"),
601 false => InternedString::new("unix")
604 let mk = attr::mk_name_value_item_str;
605 return vec!(// Target bindings.
606 attr::mk_word_item(fam.clone()),
607 mk(InternedString::new("target_os"), intern(os)),
608 mk(InternedString::new("target_family"), fam),
609 mk(InternedString::new("target_arch"), intern(arch)),
610 mk(InternedString::new("target_endian"), intern(end)),
611 mk(InternedString::new("target_pointer_width"),
616 pub fn append_configuration(cfg: &mut ast::CrateConfig,
617 name: InternedString) {
618 if !cfg.iter().any(|mi| mi.name() == name) {
619 cfg.push(attr::mk_word_item(name))
623 pub fn build_configuration(sess: &Session) -> ast::CrateConfig {
624 // Combine the configuration requested by the session (command line) with
625 // some default and generated configuration items
626 let default_cfg = default_configuration(sess);
627 let mut user_cfg = sess.opts.cfg.clone();
628 // If the user wants a test runner, then add the test cfg
630 append_configuration(&mut user_cfg, InternedString::new("test"))
632 let mut v = user_cfg.into_iter().collect::<Vec<_>>();
633 v.push_all(&default_cfg[]);
637 pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config {
638 let target = match Target::search(&opts.target_triple[]) {
641 sp.handler().fatal((format!("Error loading target specification: {}", e)).as_slice());
645 let (int_type, uint_type) = match &target.target_pointer_width[] {
646 "32" => (ast::TyI32, ast::TyU32),
647 "64" => (ast::TyI64, ast::TyU64),
648 w => sp.handler().fatal(&format!("target specification was invalid: unrecognized \
649 target-word-size {}", w)[])
655 uint_type: uint_type,
659 /// Returns the "short" subset of the stable rustc command line options.
660 pub fn short_optgroups() -> Vec<getopts::OptGroup> {
661 rustc_short_optgroups().into_iter()
662 .filter(|g|g.is_stable())
667 /// Returns all of the stable rustc command line options.
668 pub fn optgroups() -> Vec<getopts::OptGroup> {
669 rustc_optgroups().into_iter()
670 .filter(|g|g.is_stable())
675 #[derive(Copy, Clone, PartialEq, Eq, Show)]
676 pub enum OptionStability { Stable, Unstable }
678 #[derive(Clone, PartialEq, Eq)]
679 pub struct RustcOptGroup {
680 pub opt_group: getopts::OptGroup,
681 pub stability: OptionStability,
685 pub fn is_stable(&self) -> bool {
686 self.stability == OptionStability::Stable
689 fn stable(g: getopts::OptGroup) -> RustcOptGroup {
690 RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
693 fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
694 RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
698 // The `opt` local module holds wrappers around the `getopts` API that
699 // adds extra rustc-specific metadata to each option; such metadata
700 // is exposed by . The public
701 // functions below ending with `_u` are the functions that return
702 // *unstable* options, i.e. options that are only enabled when the
703 // user also passes the `-Z unstable-options` debugging flag.
705 // The `fn opt_u` etc below are written so that we can use them
706 // in the future; do not warn about them not being used right now.
710 use super::RustcOptGroup;
712 type R = RustcOptGroup;
713 type S<'a> = &'a str;
715 fn stable(g: getopts::OptGroup) -> R { RustcOptGroup::stable(g) }
716 fn unstable(g: getopts::OptGroup) -> R { RustcOptGroup::unstable(g) }
718 // FIXME (pnkfelix): We default to stable since the current set of
719 // options is defacto stable. However, it would be good to revise the
720 // code so that a stable option is the thing that takes extra effort
723 pub fn opt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optopt(a, b, c, d)) }
724 pub fn multi(a: S, b: S, c: S, d: S) -> R { stable(getopts::optmulti(a, b, c, d)) }
725 pub fn flag(a: S, b: S, c: S) -> R { stable(getopts::optflag(a, b, c)) }
726 pub fn flagopt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optflagopt(a, b, c, d)) }
728 pub fn opt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optopt(a, b, c, d)) }
729 pub fn multi_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optmulti(a, b, c, d)) }
730 pub fn flag_u(a: S, b: S, c: S) -> R { unstable(getopts::optflag(a, b, c)) }
731 pub fn flagopt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optflagopt(a, b, c, d)) }
734 /// Returns the "short" subset of the rustc command line options,
735 /// including metadata for each option, such as whether the option is
736 /// part of the stable long-term interface for rustc.
737 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
739 opt::flag("h", "help", "Display this message"),
740 opt::multi("", "cfg", "Configure the compilation environment", "SPEC"),
741 opt::multi("L", "", "Add a directory to the library search path", "PATH"),
742 opt::multi("l", "", "Link the generated crate(s) to the specified native
743 library NAME. The optional KIND can be one of,
744 static, dylib, or framework. If omitted, dylib is
745 assumed.", "[KIND=]NAME"),
746 opt::multi("", "crate-type", "Comma separated list of types of crates
747 for the compiler to emit",
748 "[bin|lib|rlib|dylib|staticlib]"),
749 opt::opt("", "crate-name", "Specify the name of the crate being built",
751 opt::multi("", "emit", "Comma separated list of types of output for \
752 the compiler to emit",
753 "[asm|llvm-bc|llvm-ir|obj|link|dep-info]"),
754 opt::multi("", "print", "Comma separated list of compiler information to \
756 "[crate-name|file-names|sysroot]"),
757 opt::flag("g", "", "Equivalent to -C debuginfo=2"),
758 opt::flag("O", "", "Equivalent to -C opt-level=2"),
759 opt::opt("o", "", "Write output to <filename>", "FILENAME"),
760 opt::opt("", "out-dir", "Write output to compiler-chosen filename \
762 opt::opt("", "explain", "Provide a detailed explanation of an error \
764 opt::flag("", "test", "Build a test harness"),
765 opt::opt("", "target", "Target triple cpu-manufacturer-kernel[-os] \
766 to compile for (see chapter 3.4 of \
767 http://www.sourceware.org/autobook/
770 opt::multi("W", "warn", "Set lint warnings", "OPT"),
771 opt::multi("A", "allow", "Set lint allowed", "OPT"),
772 opt::multi("D", "deny", "Set lint denied", "OPT"),
773 opt::multi("F", "forbid", "Set lint forbidden", "OPT"),
774 opt::multi("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
775 opt::flag("V", "version", "Print version info and exit"),
776 opt::flag("v", "verbose", "Use verbose output"),
780 /// Returns all rustc command line options, including metadata for
781 /// each option, such as whether the option is part of the stable
782 /// long-term interface for rustc.
783 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
784 let mut opts = rustc_short_optgroups();
786 opt::multi("", "extern", "Specify where an external rust library is \
789 opt::opt("", "sysroot", "Override the system root", "PATH"),
790 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
791 opt::opt("", "color", "Configure coloring of output:
792 auto = colorize, if output goes to a tty (default);
793 always = always colorize output;
794 never = never colorize output", "auto|always|never"),
796 opt::flagopt_u("", "pretty",
797 "Pretty-print the input instead of compiling;
798 valid types are: `normal` (un-annotated source),
799 `expanded` (crates expanded),
800 `typed` (crates expanded, with type annotations), or
801 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
803 opt::flagopt_u("", "xpretty",
804 "Pretty-print the input instead of compiling, unstable variants;
805 valid types are any of the types for `--pretty`, as well as:
806 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node), or
807 `everybody_loops` (all function bodies replaced with `loop {}`).",
809 opt::opt_u("", "show-span", "Show spans for compiler debugging", "expr|pat|ty"),
814 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
815 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
816 cfgspecs.into_iter().map(|s| {
817 parse::parse_meta_from_source_str("cfgspec".to_string(),
820 &parse::new_parse_sess())
821 }).collect::<ast::CrateConfig>()
824 pub fn build_session_options(matches: &getopts::Matches) -> Options {
826 let unparsed_crate_types = matches.opt_strs("crate-type");
827 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
828 .unwrap_or_else(|e| early_error(&e[]));
830 let mut lint_opts = vec!();
831 let mut describe_lints = false;
833 for &level in [lint::Allow, lint::Warn, lint::Deny, lint::Forbid].iter() {
834 for lint_name in matches.opt_strs(level.as_str()).into_iter() {
835 if lint_name == "help" {
836 describe_lints = true;
838 lint_opts.push((lint_name.replace("-", "_"), level));
843 let debugging_opts = build_debugging_options(matches);
845 let parse_only = debugging_opts.parse_only;
846 let no_trans = debugging_opts.no_trans;
847 let no_analysis = debugging_opts.no_analysis;
849 if debugging_opts.debug_llvm {
850 unsafe { llvm::LLVMSetDebug(1); }
853 let mut output_types = Vec::new();
854 if !debugging_opts.parse_only && !no_trans {
855 let unparsed_output_types = matches.opt_strs("emit");
856 for unparsed_output_type in unparsed_output_types.iter() {
857 for part in unparsed_output_type.split(',') {
858 let output_type = match part.as_slice() {
859 "asm" => OutputTypeAssembly,
860 "llvm-ir" => OutputTypeLlvmAssembly,
861 "llvm-bc" => OutputTypeBitcode,
862 "obj" => OutputTypeObject,
863 "link" => OutputTypeExe,
864 "dep-info" => OutputTypeDepInfo,
866 early_error(&format!("unknown emission type: `{}`",
870 output_types.push(output_type)
875 output_types.dedup();
876 if output_types.len() == 0 {
877 output_types.push(OutputTypeExe);
880 let cg = build_codegen_options(matches);
882 let sysroot_opt = matches.opt_str("sysroot").map(|m| Path::new(m));
883 let target = matches.opt_str("target").unwrap_or(
884 host_triple().to_string());
886 if matches.opt_present("O") {
887 if cg.opt_level.is_some() {
888 early_error("-O and -C opt-level both provided");
897 Some(3) => Aggressive,
899 early_error(format!("optimization level needs to be \
900 between 0-3 (instead was `{}`)",
906 let gc = debugging_opts.gc;
907 let debuginfo = if matches.opt_present("g") {
908 if cg.debuginfo.is_some() {
909 early_error("-g and -C debuginfo both provided");
914 None | Some(0) => NoDebugInfo,
915 Some(1) => LimitedDebugInfo,
916 Some(2) => FullDebugInfo,
918 early_error(format!("debug info level needs to be between \
919 0-2 (instead was `{}`)",
925 let mut search_paths = SearchPaths::new();
926 for s in matches.opt_strs("L").iter() {
927 search_paths.add_path(&s[]);
930 let libs = matches.opt_strs("l").into_iter().map(|s| {
931 let mut parts = s.splitn(1, '=');
932 let kind = parts.next().unwrap();
933 if let Some(name) = parts.next() {
934 let kind = match kind {
935 "dylib" => cstore::NativeUnknown,
936 "framework" => cstore::NativeFramework,
937 "static" => cstore::NativeStatic,
939 early_error(format!("unknown library kind `{}`, expected \
940 one of dylib, framework, or static",
944 return (name.to_string(), kind)
947 // FIXME(acrichto) remove this once crates have stopped using it, this
948 // is deprecated behavior now.
949 let mut parts = s.rsplitn(1, ':');
950 let kind = parts.next().unwrap();
951 let (name, kind) = match (parts.next(), kind) {
953 (Some(name), "dylib") => (name, cstore::NativeUnknown),
954 (Some(name), "framework") => (name, cstore::NativeFramework),
955 (Some(name), "static") => (name, cstore::NativeStatic),
957 early_error(&format!("unknown library kind `{}`, expected \
958 one of dylib, framework, or static",
962 (name.to_string(), kind)
965 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
966 let test = matches.opt_present("test");
967 let write_dependency_info = (output_types.contains(&OutputTypeDepInfo), None);
969 let prints = matches.opt_strs("print").into_iter().map(|s| {
971 "crate-name" => PrintRequest::CrateName,
972 "file-names" => PrintRequest::FileNames,
973 "sysroot" => PrintRequest::Sysroot,
975 early_error(format!("unknown print request `{}`", req).as_slice())
978 }).collect::<Vec<_>>();
980 if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
981 early_warn("-C remark will not show source locations without \
985 let color = match matches.opt_str("color").as_ref().map(|s| &s[]) {
986 Some("auto") => Auto,
987 Some("always") => Always,
988 Some("never") => Never,
993 early_error(&format!("argument for --color must be auto, always \
994 or never (instead was `{}`)",
999 let mut externs = HashMap::new();
1000 for arg in matches.opt_strs("extern").iter() {
1001 let mut parts = arg.splitn(1, '=');
1002 let name = match parts.next() {
1004 None => early_error("--extern value must not be empty"),
1006 let location = match parts.next() {
1008 None => early_error("--extern value must be of the format `foo=bar`"),
1011 match externs.entry(name.to_string()) {
1012 Vacant(entry) => { entry.insert(vec![location.to_string()]); },
1013 Occupied(mut entry) => { entry.get_mut().push(location.to_string()); },
1017 let crate_name = matches.opt_str("crate-name");
1020 crate_types: crate_types,
1022 optimize: opt_level,
1023 debuginfo: debuginfo,
1024 lint_opts: lint_opts,
1025 describe_lints: describe_lints,
1026 output_types: output_types,
1027 search_paths: search_paths,
1028 maybe_sysroot: sysroot_opt,
1029 target_triple: target,
1032 parse_only: parse_only,
1034 no_analysis: no_analysis,
1035 debugging_opts: debugging_opts,
1036 write_dependency_info: write_dependency_info,
1042 crate_name: crate_name,
1045 unstable_features: UnstableFeatures::Disallow
1049 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
1051 let mut crate_types: Vec<CrateType> = Vec::new();
1052 for unparsed_crate_type in list_list.iter() {
1053 for part in unparsed_crate_type.split(',') {
1054 let new_part = match part {
1055 "lib" => default_lib_output(),
1056 "rlib" => CrateTypeRlib,
1057 "staticlib" => CrateTypeStaticlib,
1058 "dylib" => CrateTypeDylib,
1059 "bin" => CrateTypeExecutable,
1061 return Err(format!("unknown crate type: `{}`",
1065 crate_types.push(new_part)
1069 return Ok(crate_types);
1072 impl fmt::Display for CrateType {
1073 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1075 CrateTypeExecutable => "bin".fmt(f),
1076 CrateTypeDylib => "dylib".fmt(f),
1077 CrateTypeRlib => "rlib".fmt(f),
1078 CrateTypeStaticlib => "staticlib".fmt(f)
1086 use session::config::{build_configuration, optgroups, build_session_options};
1087 use session::build_session;
1089 use getopts::getopts;
1091 use syntax::attr::AttrMetaMethods;
1092 use syntax::diagnostics;
1094 // When the user supplies --test we should implicitly supply --cfg test
1096 fn test_switch_implies_cfg_test() {
1098 &match getopts(&["--test".to_string()], &optgroups()[]) {
1100 Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
1102 let registry = diagnostics::registry::Registry::new(&[]);
1103 let sessopts = build_session_options(matches);
1104 let sess = build_session(sessopts, None, registry);
1105 let cfg = build_configuration(&sess);
1106 assert!((attr::contains_name(&cfg[], "test")));
1109 // When the user supplies --test and --cfg test, don't implicitly add
1110 // another --cfg test
1112 fn test_switch_implies_cfg_test_unless_cfg_test() {
1114 &match getopts(&["--test".to_string(), "--cfg=test".to_string()],
1118 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
1121 let registry = diagnostics::registry::Registry::new(&[]);
1122 let sessopts = build_session_options(matches);
1123 let sess = build_session(sessopts, None, registry);
1124 let cfg = build_configuration(&sess);
1125 let mut test_items = cfg.iter().filter(|m| m.name() == "test");
1126 assert!(test_items.next().is_some());
1127 assert!(test_items.next().is_none());
1131 fn test_can_print_warnings() {
1133 let matches = getopts(&[
1134 "-Awarnings".to_string()
1135 ], &optgroups()[]).unwrap();
1136 let registry = diagnostics::registry::Registry::new(&[]);
1137 let sessopts = build_session_options(&matches);
1138 let sess = build_session(sessopts, None, registry);
1139 assert!(!sess.can_print_warnings);
1143 let matches = getopts(&[
1144 "-Awarnings".to_string(),
1145 "-Dwarnings".to_string()
1146 ], &optgroups()[]).unwrap();
1147 let registry = diagnostics::registry::Registry::new(&[]);
1148 let sessopts = build_session_options(&matches);
1149 let sess = build_session(sessopts, None, registry);
1150 assert!(sess.can_print_warnings);
1154 let matches = getopts(&[
1155 "-Adead_code".to_string()
1156 ], &optgroups()[]).unwrap();
1157 let registry = diagnostics::registry::Registry::new(&[]);
1158 let sessopts = build_session_options(&matches);
1159 let sess = build_session(sessopts, None, registry);
1160 assert!(sess.can_print_warnings);