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 externs: HashMap<String, Vec<String>>,
109 pub crate_name: Option<String>,
110 /// An optional name to use as the crate for std during std injection,
111 /// written `extern crate std = "name"`. Default to "std". Used by
112 /// out-of-tree drivers.
113 pub alt_std_name: Option<String>
116 #[derive(Clone, PartialEq, Eq)]
117 #[allow(missing_copy_implementations)]
118 pub enum PrintRequest {
125 /// Load source from file
127 /// The string is the source
132 pub fn filestem(&self) -> String {
134 Input::File(ref ifile) => ifile.filestem_str().unwrap().to_string(),
135 Input::Str(_) => "rust_out".to_string(),
141 pub struct OutputFilenames {
142 pub out_directory: Path,
143 pub out_filestem: String,
144 pub single_output_file: Option<Path>,
148 impl OutputFilenames {
149 pub fn path(&self, flavor: OutputType) -> Path {
150 match self.single_output_file {
151 Some(ref path) => return path.clone(),
154 self.temp_path(flavor)
157 pub fn temp_path(&self, flavor: OutputType) -> Path {
158 let base = self.out_directory.join(self.filestem());
160 OutputTypeBitcode => base.with_extension("bc"),
161 OutputTypeAssembly => base.with_extension("s"),
162 OutputTypeLlvmAssembly => base.with_extension("ll"),
163 OutputTypeObject => base.with_extension("o"),
164 OutputTypeDepInfo => base.with_extension("d"),
165 OutputTypeExe => base,
169 pub fn with_extension(&self, extension: &str) -> Path {
170 self.out_directory.join(self.filestem()).with_extension(extension)
173 pub fn filestem(&self) -> String {
174 format!("{}{}", self.out_filestem, self.extra)
178 pub fn host_triple() -> &'static str {
179 // Get the host triple out of the build environment. This ensures that our
180 // idea of the host triple is the same as for the set of libraries we've
181 // actually built. We can't just take LLVM's host triple because they
182 // normalize all ix86 architectures to i386.
184 // Instead of grabbing the host triple (for the current host), we grab (at
185 // compile time) the target triple that this rustc is built with and
186 // calling that (at runtime) the host triple.
187 (option_env!("CFG_COMPILER_HOST_TRIPLE")).
188 expect("CFG_COMPILER_HOST_TRIPLE")
191 /// Some reasonable defaults
192 pub fn basic_options() -> Options {
194 crate_types: Vec::new(),
197 debuginfo: NoDebugInfo,
198 lint_opts: Vec::new(),
199 describe_lints: false,
200 output_types: Vec::new(),
201 search_paths: SearchPaths::new(),
203 target_triple: host_triple().to_string(),
210 write_dependency_info: (false, None),
212 cg: basic_codegen_options(),
214 externs: HashMap::new(),
221 // The type of entry function, so
222 // users can have their own entry
223 // functions that don't start a
225 #[derive(Copy, PartialEq)]
226 pub enum EntryFnType {
232 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash)]
240 macro_rules! debugging_opts {
241 ([ $opt:ident ] $cnt:expr ) => (
242 pub const $opt: u64 = 1 << $cnt;
244 ([ $opt:ident, $($rest:ident),* ] $cnt:expr ) => (
245 pub const $opt: u64 = 1 << $cnt;
246 debugging_opts! { [ $($rest),* ] $cnt + 1 }
272 PRINT_MOVE_FRAGMENTS,
273 FLOWGRAPH_PRINT_LOANS,
274 FLOWGRAPH_PRINT_MOVES,
275 FLOWGRAPH_PRINT_ASSIGNS,
287 pub fn debugging_opts_map() -> Vec<(&'static str, &'static str, u64)> {
288 vec![("verbose", "in general, enable more debug printouts", VERBOSE),
289 ("time-passes", "measure time of each rustc pass", TIME_PASSES),
290 ("count-llvm-insns", "count where LLVM \
291 instrs originate", COUNT_LLVM_INSNS),
292 ("time-llvm-passes", "measure time of each LLVM pass",
294 ("trans-stats", "gather trans statistics", TRANS_STATS),
295 ("asm-comments", "generate comments into the assembly (may change behavior)",
297 ("no-verify", "skip LLVM verification", NO_VERIFY),
298 ("borrowck-stats", "gather borrowck statistics", BORROWCK_STATS),
299 ("no-landing-pads", "omit landing pads for unwinding",
301 ("debug-llvm", "enable debug output from LLVM", DEBUG_LLVM),
302 ("show-span", "show spans for compiler debugging", SHOW_SPAN),
303 ("count-type-sizes", "count the sizes of aggregate types",
305 ("meta-stats", "gather metadata statistics", META_STATS),
306 ("print-link-args", "Print the arguments passed to the linker",
308 ("gc", "Garbage collect shared data (experimental)", GC),
309 ("print-llvm-passes",
310 "Prints the llvm optimization passes being run",
312 ("ast-json", "Print the AST as JSON and halt", AST_JSON),
313 ("ast-json-noexpand", "Print the pre-expansion AST as JSON and halt", AST_JSON_NOEXPAND),
314 ("ls", "List the symbols defined by a library crate", LS),
315 ("save-analysis", "Write syntax and type analysis information \
316 in addition to normal output", SAVE_ANALYSIS),
317 ("print-move-fragments", "Print out move-fragment data for every fn",
318 PRINT_MOVE_FRAGMENTS),
319 ("flowgraph-print-loans", "Include loan analysis data in \
320 --pretty flowgraph output", FLOWGRAPH_PRINT_LOANS),
321 ("flowgraph-print-moves", "Include move analysis data in \
322 --pretty flowgraph output", FLOWGRAPH_PRINT_MOVES),
323 ("flowgraph-print-assigns", "Include assignment analysis data in \
324 --pretty flowgraph output", FLOWGRAPH_PRINT_ASSIGNS),
325 ("flowgraph-print-all", "Include all dataflow analysis data in \
326 --pretty flowgraph output", FLOWGRAPH_PRINT_ALL),
327 ("print-region-graph", "Prints region inference graph. \
328 Use with RUST_REGION_GRAPH=help for more info",
330 ("parse-only", "Parse only; do not compile, assemble, or link", PARSE_ONLY),
331 ("no-trans", "Run all passes except translation; no output", NO_TRANS),
332 ("no-analysis", "Parse and expand the source, but run no analysis and",
334 ("unstable-options", "Adds unstable command line options to rustc interface",
336 ("print-enum-sizes", "Print the size of enums and their variants", PRINT_ENUM_SIZES),
342 SomePasses(Vec<String>),
347 pub fn is_empty(&self) -> bool {
349 SomePasses(ref v) => v.is_empty(),
355 /// Declare a macro that will define all CodegenOptions fields and parsers all
356 /// at once. The goal of this macro is to define an interface that can be
357 /// programmatically used by the option parser in order to initialize the struct
358 /// without hardcoding field names all over the place.
360 /// The goal is to invoke this macro once with the correct fields, and then this
361 /// macro generates all necessary code. The main gotcha of this macro is the
362 /// cgsetters module which is a bunch of generated code to parse an option into
363 /// its respective field in the struct. There are a few hand-written parsers for
364 /// parsing specific types of values in this module.
365 macro_rules! cgoptions {
366 ($($opt:ident : $t:ty = ($init:expr, $parse:ident, $desc:expr)),* ,) =>
369 pub struct CodegenOptions { $(pub $opt: $t),* }
371 pub fn basic_codegen_options() -> CodegenOptions {
372 CodegenOptions { $($opt: $init),* }
375 pub type CodegenSetter = fn(&mut CodegenOptions, v: Option<&str>) -> bool;
376 pub const CG_OPTIONS: &'static [(&'static str, CodegenSetter,
377 Option<&'static str>, &'static str)] =
378 &[ $( (stringify!($opt), cgsetters::$opt, cg_type_descs::$parse, $desc) ),* ];
380 #[allow(non_upper_case_globals)]
382 pub const parse_bool: Option<&'static str> = None;
383 pub const parse_opt_bool: Option<&'static str> = None;
384 pub const parse_string: Option<&'static str> = Some("a string");
385 pub const parse_opt_string: Option<&'static str> = Some("a string");
386 pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
387 pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
388 pub const parse_uint: Option<&'static str> = Some("a number");
389 pub const parse_passes: Option<&'static str> =
390 Some("a space-separated list of passes, or `all`");
391 pub const parse_opt_uint: Option<&'static str> =
396 use super::{CodegenOptions, Passes, SomePasses, AllPasses};
399 pub fn $opt(cg: &mut CodegenOptions, v: Option<&str>) -> bool {
400 $parse(&mut cg.$opt, v)
404 fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
407 None => { *slot = true; true }
411 fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
414 None => { *slot = Some(true); true }
418 fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
420 Some(s) => { *slot = Some(s.to_string()); true },
425 fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
427 Some(s) => { *slot = s.to_string(); true },
432 fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
437 slot.push(s.to_string());
445 fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
449 let v = s.words().map(|s| s.to_string()).collect();
457 fn parse_uint(slot: &mut uint, v: Option<&str>) -> bool {
458 match v.and_then(|s| s.parse()) {
459 Some(i) => { *slot = i; true },
464 fn parse_opt_uint(slot: &mut Option<uint>, v: Option<&str>) -> bool {
466 Some(s) => { *slot = s.parse(); slot.is_some() }
467 None => { *slot = None; true }
471 fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
478 let mut passes = vec!();
479 if parse_list(&mut passes, v) {
480 *slot = SomePasses(passes);
492 ar: Option<String> = (None, parse_opt_string,
493 "tool to assemble archives with"),
494 linker: Option<String> = (None, parse_opt_string,
495 "system linker to link outputs with"),
496 link_args: Option<Vec<String>> = (None, parse_opt_list,
497 "extra arguments to pass to the linker (space separated)"),
498 lto: bool = (false, parse_bool,
499 "perform LLVM link-time optimizations"),
500 target_cpu: Option<String> = (None, parse_opt_string,
501 "select target processor (llc -mcpu=help for details)"),
502 target_feature: String = ("".to_string(), parse_string,
503 "target specific attributes (llc -mattr=help for details)"),
504 passes: Vec<String> = (Vec::new(), parse_list,
505 "a list of extra LLVM passes to run (space separated)"),
506 llvm_args: Vec<String> = (Vec::new(), parse_list,
507 "a list of arguments to pass to llvm (space separated)"),
508 save_temps: bool = (false, parse_bool,
509 "save all temporary output files during compilation"),
510 rpath: bool = (false, parse_bool,
511 "set rpath values in libs/exes"),
512 no_prepopulate_passes: bool = (false, parse_bool,
513 "don't pre-populate the pass manager with a list of passes"),
514 no_vectorize_loops: bool = (false, parse_bool,
515 "don't run the loop vectorization optimization passes"),
516 no_vectorize_slp: bool = (false, parse_bool,
517 "don't run LLVM's SLP vectorization pass"),
518 soft_float: bool = (false, parse_bool,
519 "generate software floating point library calls"),
520 prefer_dynamic: bool = (false, parse_bool,
521 "prefer dynamic linking to static linking"),
522 no_integrated_as: bool = (false, parse_bool,
523 "use an external assembler rather than LLVM's integrated one"),
524 no_redzone: Option<bool> = (None, parse_opt_bool,
525 "disable the use of the redzone"),
526 relocation_model: Option<String> = (None, parse_opt_string,
527 "choose the relocation model to use (llc -relocation-model for details)"),
528 code_model: Option<String> = (None, parse_opt_string,
529 "choose the code model to use (llc -code-model for details)"),
530 metadata: Vec<String> = (Vec::new(), parse_list,
531 "metadata to mangle symbol names with"),
532 extra_filename: String = ("".to_string(), parse_string,
533 "extra data to put in each output filename"),
534 codegen_units: uint = (1, parse_uint,
535 "divide crate into N units to optimize in parallel"),
536 remark: Passes = (SomePasses(Vec::new()), parse_passes,
537 "print remarks for these optimization passes (space separated, or \"all\")"),
538 no_stack_check: bool = (false, parse_bool,
539 "disable checks for stack exhaustion (a memory-safety hazard!)"),
540 debuginfo: Option<uint> = (None, parse_opt_uint,
541 "debug info emission level, 0 = no debug info, 1 = line tables only, \
542 2 = full debug info with variable and type information"),
543 opt_level: Option<uint> = (None, parse_opt_uint,
544 "Optimize with possible levels 0-3"),
547 pub fn build_codegen_options(matches: &getopts::Matches) -> CodegenOptions
549 let mut cg = basic_codegen_options();
550 for option in matches.opt_strs("C").into_iter() {
551 let mut iter = option.splitn(1, '=');
552 let key = iter.next().unwrap();
553 let value = iter.next();
554 let option_to_lookup = key.replace("-", "_");
555 let mut found = false;
556 for &(candidate, setter, opt_type_desc, _) in CG_OPTIONS.iter() {
557 if option_to_lookup != candidate { continue }
558 if !setter(&mut cg, value) {
559 match (value, opt_type_desc) {
560 (Some(..), None) => {
561 early_error(format!("codegen option `{}` takes no \
564 (None, Some(type_desc)) => {
565 early_error(format!("codegen option `{0}` requires \
566 {1} (-C {0}=<value>)",
569 (Some(value), Some(type_desc)) => {
570 early_error(format!("incorrect value `{}` for codegen \
571 option `{}` - {} was expected",
572 value, key, type_desc)[])
574 (None, None) => unreachable!()
581 early_error(format!("unknown codegen option: `{}`",
588 pub fn default_lib_output() -> CrateType {
592 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
593 use syntax::parse::token::intern_and_get_ident as intern;
595 let end = sess.target.target.target_endian[];
596 let arch = sess.target.target.arch[];
597 let wordsz = sess.target.target.target_word_size[];
598 let os = sess.target.target.target_os[];
600 let fam = match sess.target.target.options.is_like_windows {
601 true => InternedString::new("windows"),
602 false => InternedString::new("unix")
605 let mk = attr::mk_name_value_item_str;
606 return vec!(// Target bindings.
607 attr::mk_word_item(fam.clone()),
608 mk(InternedString::new("target_os"), intern(os)),
609 mk(InternedString::new("target_family"), fam),
610 mk(InternedString::new("target_arch"), intern(arch)),
611 mk(InternedString::new("target_endian"), intern(end)),
612 mk(InternedString::new("target_word_size"),
617 pub fn append_configuration(cfg: &mut ast::CrateConfig,
618 name: InternedString) {
619 if !cfg.iter().any(|mi| mi.name() == name) {
620 cfg.push(attr::mk_word_item(name))
624 pub fn build_configuration(sess: &Session) -> ast::CrateConfig {
625 // Combine the configuration requested by the session (command line) with
626 // some default and generated configuration items
627 let default_cfg = default_configuration(sess);
628 let mut user_cfg = sess.opts.cfg.clone();
629 // If the user wants a test runner, then add the test cfg
631 append_configuration(&mut user_cfg, InternedString::new("test"))
633 let mut v = user_cfg.into_iter().collect::<Vec<_>>();
634 v.push_all(default_cfg[]);
638 pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config {
639 let target = match Target::search(opts.target_triple[]) {
642 sp.handler().fatal((format!("Error loading target specification: {}", e))[]);
646 let (int_type, uint_type) = match target.target_word_size[] {
647 "32" => (ast::TyI32, ast::TyU32),
648 "64" => (ast::TyI64, ast::TyU64),
649 w => sp.handler().fatal((format!("target specification was invalid: unrecognized \
650 target-word-size {}", w))[])
656 uint_type: uint_type,
660 /// Returns the "short" subset of the stable rustc command line options.
661 pub fn short_optgroups() -> Vec<getopts::OptGroup> {
662 rustc_short_optgroups().into_iter()
663 .filter(|g|g.is_stable())
668 /// Returns all of the stable rustc command line options.
669 pub fn optgroups() -> Vec<getopts::OptGroup> {
670 rustc_optgroups().into_iter()
671 .filter(|g|g.is_stable())
676 #[derive(Copy, Clone, PartialEq, Eq, Show)]
677 pub enum OptionStability { Stable, Unstable }
679 #[derive(Clone, PartialEq, Eq)]
680 pub struct RustcOptGroup {
681 pub opt_group: getopts::OptGroup,
682 pub stability: OptionStability,
686 pub fn is_stable(&self) -> bool {
687 self.stability == OptionStability::Stable
690 fn stable(g: getopts::OptGroup) -> RustcOptGroup {
691 RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
694 fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
695 RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
699 // The `opt` local module holds wrappers around the `getopts` API that
700 // adds extra rustc-specific metadata to each option; such metadata
701 // is exposed by . The public
702 // functions below ending with `_u` are the functions that return
703 // *unstable* options, i.e. options that are only enabled when the
704 // user also passes the `-Z unstable-options` debugging flag.
706 // The `fn opt_u` etc below are written so that we can use them
707 // in the future; do not warn about them not being used right now.
711 use super::RustcOptGroup;
713 type R = RustcOptGroup;
714 type S<'a> = &'a str;
716 fn stable(g: getopts::OptGroup) -> R { RustcOptGroup::stable(g) }
717 fn unstable(g: getopts::OptGroup) -> R { RustcOptGroup::unstable(g) }
719 // FIXME (pnkfelix): We default to stable since the current set of
720 // options is defacto stable. However, it would be good to revise the
721 // code so that a stable option is the thing that takes extra effort
724 pub fn opt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optopt(a, b, c, d)) }
725 pub fn multi(a: S, b: S, c: S, d: S) -> R { stable(getopts::optmulti(a, b, c, d)) }
726 pub fn flag(a: S, b: S, c: S) -> R { stable(getopts::optflag(a, b, c)) }
727 pub fn flagopt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optflagopt(a, b, c, d)) }
729 pub fn opt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optopt(a, b, c, d)) }
730 pub fn multi_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optmulti(a, b, c, d)) }
731 pub fn flag_u(a: S, b: S, c: S) -> R { unstable(getopts::optflag(a, b, c)) }
732 pub fn flagopt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optflagopt(a, b, c, d)) }
735 /// Returns the "short" subset of the rustc command line options,
736 /// including metadata for each option, such as whether the option is
737 /// part of the stable long-term interface for rustc.
738 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
740 opt::flag("h", "help", "Display this message"),
741 opt::multi("", "cfg", "Configure the compilation environment", "SPEC"),
742 opt::multi("L", "", "Add a directory to the library search path", "PATH"),
743 opt::multi("l", "", "Link the generated crate(s) to the specified native
744 library NAME. The optional KIND can be one of,
745 static, dylib, or framework. If omitted, dylib is
746 assumed.", "[KIND=]NAME"),
747 opt::multi("", "crate-type", "Comma separated list of types of crates
748 for the compiler to emit",
749 "[bin|lib|rlib|dylib|staticlib]"),
750 opt::opt("", "crate-name", "Specify the name of the crate being built",
752 opt::multi("", "emit", "Comma separated list of types of output for \
753 the compiler to emit",
754 "[asm|llvm-bc|llvm-ir|obj|link|dep-info]"),
755 opt::multi("", "print", "Comma separated list of compiler information to \
757 "[crate-name|file-names|sysroot]"),
758 opt::flag("g", "", "Equivalent to -C debuginfo=2"),
759 opt::flag("O", "", "Equivalent to -C opt-level=2"),
760 opt::opt("o", "", "Write output to <filename>", "FILENAME"),
761 opt::opt("", "out-dir", "Write output to compiler-chosen filename \
763 opt::opt("", "explain", "Provide a detailed explanation of an error \
765 opt::flag("", "test", "Build a test harness"),
766 opt::opt("", "target", "Target triple cpu-manufacturer-kernel[-os] \
767 to compile for (see chapter 3.4 of \
768 http://www.sourceware.org/autobook/
771 opt::multi("W", "warn", "Set lint warnings", "OPT"),
772 opt::multi("A", "allow", "Set lint allowed", "OPT"),
773 opt::multi("D", "deny", "Set lint denied", "OPT"),
774 opt::multi("F", "forbid", "Set lint forbidden", "OPT"),
775 opt::multi("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
776 opt::flag("V", "version", "Print version info and exit"),
777 opt::flag("v", "verbose", "Use verbose output"),
781 /// Returns all rustc command line options, including metadata for
782 /// each option, such as whether the option is part of the stable
783 /// long-term interface for rustc.
784 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
785 let mut opts = rustc_short_optgroups();
787 opt::multi("", "extern", "Specify where an external rust library is \
790 opt::opt("", "opt-level", "Optimize with possible levels 0-3", "LEVEL"),
791 opt::opt("", "sysroot", "Override the system root", "PATH"),
792 opt::multi("Z", "", "Set internal debugging options", "FLAG"),
793 opt::opt("", "color", "Configure coloring of output:
794 auto = colorize, if output goes to a tty (default);
795 always = always colorize output;
796 never = never colorize output", "auto|always|never"),
799 opt::flag("", "print-crate-name", "Output the crate name and exit"),
800 opt::flag("", "print-file-name", "Output the file(s) that would be \
801 written if compilation \
802 continued and exit"),
803 opt::opt("", "debuginfo", "Emit DWARF debug info to the objects created:
805 1 = line-tables only (for stacktraces and breakpoints),
806 2 = full debug info with variable and type information \
807 (same as -g)", "LEVEL"),
808 opt::flag("", "no-trans", "Run all passes except translation; no output"),
809 opt::flag("", "no-analysis", "Parse and expand the source, but run no \
810 analysis and produce no output"),
811 opt::flag("", "parse-only", "Parse only; do not compile, assemble, \
813 opt::flagopt("", "pretty",
814 "Pretty-print the input instead of compiling;
815 valid types are: `normal` (un-annotated source),
816 `expanded` (crates expanded),
817 `typed` (crates expanded, with type annotations), or
818 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
820 opt::flagopt_u("", "xpretty",
821 "Pretty-print the input instead of compiling, unstable variants;
822 valid types are any of the types for `--pretty`, as well as:
823 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node), or
824 `everybody_loops` (all function bodies replaced with `loop {}`).",
826 opt::flagopt("", "dep-info",
827 "Output dependency info to <filename> after compiling, \
828 in a format suitable for use by Makefiles", "FILENAME"),
833 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
834 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
835 cfgspecs.into_iter().map(|s| {
836 parse::parse_meta_from_source_str("cfgspec".to_string(),
839 &parse::new_parse_sess())
840 }).collect::<ast::CrateConfig>()
843 pub fn build_session_options(matches: &getopts::Matches) -> Options {
845 let unparsed_crate_types = matches.opt_strs("crate-type");
846 let crate_types = parse_crate_types_from_list(unparsed_crate_types)
847 .unwrap_or_else(|e| early_error(e[]));
849 let mut lint_opts = vec!();
850 let mut describe_lints = false;
852 for &level in [lint::Allow, lint::Warn, lint::Deny, lint::Forbid].iter() {
853 for lint_name in matches.opt_strs(level.as_str()).into_iter() {
854 if lint_name == "help" {
855 describe_lints = true;
857 lint_opts.push((lint_name.replace("-", "_"), level));
862 let mut debugging_opts = 0;
863 let debug_flags = matches.opt_strs("Z");
864 let debug_map = debugging_opts_map();
865 for debug_flag in debug_flags.iter() {
866 let mut this_bit = 0;
867 for &(name, _, bit) in debug_map.iter() {
868 if name == *debug_flag {
874 early_error(format!("unknown debug flag: {}",
877 debugging_opts |= this_bit;
880 let parse_only = if matches.opt_present("parse-only") {
881 // FIXME(acrichto) remove this eventually
882 early_warn("--parse-only is deprecated in favor of -Z parse-only");
885 debugging_opts & PARSE_ONLY != 0
887 let no_trans = if matches.opt_present("no-trans") {
888 // FIXME(acrichto) remove this eventually
889 early_warn("--no-trans is deprecated in favor of -Z no-trans");
892 debugging_opts & NO_TRANS != 0
894 let no_analysis = if matches.opt_present("no-analysis") {
895 // FIXME(acrichto) remove this eventually
896 early_warn("--no-analysis is deprecated in favor of -Z no-analysis");
899 debugging_opts & NO_ANALYSIS != 0
902 if debugging_opts & DEBUG_LLVM != 0 {
903 unsafe { llvm::LLVMSetDebug(1); }
906 let mut output_types = Vec::new();
907 if !parse_only && !no_trans {
908 let unparsed_output_types = matches.opt_strs("emit");
909 for unparsed_output_type in unparsed_output_types.iter() {
910 for part in unparsed_output_type.split(',') {
911 let output_type = match part.as_slice() {
912 "asm" => OutputTypeAssembly,
913 "llvm-ir" => OutputTypeLlvmAssembly,
914 "llvm-bc" => OutputTypeBitcode,
915 "obj" => OutputTypeObject,
916 "link" => OutputTypeExe,
917 "dep-info" => OutputTypeDepInfo,
919 early_error(format!("unknown emission type: `{}`",
923 output_types.push(output_type)
928 output_types.dedup();
929 if output_types.len() == 0 {
930 output_types.push(OutputTypeExe);
933 let cg = build_codegen_options(matches);
935 let sysroot_opt = matches.opt_str("sysroot").map(|m| Path::new(m));
936 let target = matches.opt_str("target").unwrap_or(
937 host_triple().to_string());
939 if matches.opt_present("O") {
940 if matches.opt_present("opt-level") {
941 early_error("-O and --opt-level both provided");
943 if cg.opt_level.is_some() {
944 early_error("-O and -C opt-level both provided");
947 } else if matches.opt_present("opt-level") {
948 // FIXME(acrichto) remove this eventually
949 early_warn("--opt-level=N is deprecated in favor of -C opt-level=N");
950 match matches.opt_str("opt-level").as_ref().map(|s| s.as_slice()) {
954 Some("2") => Default,
955 Some("3") => Aggressive,
957 early_error(format!("optimization level needs to be \
958 between 0-3 (instead was `{}`)",
968 Some(3) => Aggressive,
970 early_error(format!("optimization level needs to be \
971 between 0-3 (instead was `{}`)",
977 let gc = debugging_opts & GC != 0;
978 let debuginfo = if matches.opt_present("g") {
979 if matches.opt_present("debuginfo") {
980 early_error("-g and --debuginfo both provided");
982 if cg.debuginfo.is_some() {
983 early_error("-g and -C debuginfo both provided");
986 } else if matches.opt_present("debuginfo") {
987 // FIXME(acrichto) remove this eventually
988 early_warn("--debuginfo=N is deprecated in favor of -C debuginfo=N");
989 match matches.opt_str("debuginfo").as_ref().map(|s| s.as_slice()) {
990 Some("0") => NoDebugInfo,
991 Some("1") => LimitedDebugInfo,
993 Some("2") => FullDebugInfo,
995 early_error(format!("debug info level needs to be between \
996 0-2 (instead was `{}`)",
1001 match cg.debuginfo {
1002 None | Some(0) => NoDebugInfo,
1003 Some(1) => LimitedDebugInfo,
1004 Some(2) => FullDebugInfo,
1006 early_error(format!("debug info level needs to be between \
1007 0-2 (instead was `{}`)",
1013 let mut search_paths = SearchPaths::new();
1014 for s in matches.opt_strs("L").iter() {
1015 search_paths.add_path(s[]);
1018 let libs = matches.opt_strs("l").into_iter().map(|s| {
1019 let mut parts = s.splitn(1, '=');
1020 let kind = parts.next().unwrap();
1021 if let Some(name) = parts.next() {
1022 let kind = match kind {
1023 "dylib" => cstore::NativeUnknown,
1024 "framework" => cstore::NativeFramework,
1025 "static" => cstore::NativeStatic,
1027 early_error(format!("unknown library kind `{}`, expected \
1028 one of dylib, framework, or static",
1032 return (name.to_string(), kind)
1035 // FIXME(acrichto) remove this once crates have stopped using it, this
1036 // is deprecated behavior now.
1037 let mut parts = s.rsplitn(1, ':');
1038 let kind = parts.next().unwrap();
1039 let (name, kind) = match (parts.next(), kind) {
1041 (Some(name), "dylib") => (name, cstore::NativeUnknown),
1042 (Some(name), "framework") => (name, cstore::NativeFramework),
1043 (Some(name), "static") => (name, cstore::NativeStatic),
1045 early_error(format!("unknown library kind `{}`, expected \
1046 one of dylib, framework, or static",
1050 (name.to_string(), kind)
1053 let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
1054 let test = matches.opt_present("test");
1055 let write_dependency_info = if matches.opt_present("dep-info") {
1056 // FIXME(acrichto) remove this eventually
1057 early_warn("--dep-info has been deprecated in favor of --emit");
1058 (true, matches.opt_str("dep-info").map(|p| Path::new(p)))
1060 (output_types.contains(&OutputTypeDepInfo), None)
1063 let mut prints = matches.opt_strs("print").into_iter().map(|s| {
1064 match s.as_slice() {
1065 "crate-name" => PrintRequest::CrateName,
1066 "file-names" => PrintRequest::FileNames,
1067 "sysroot" => PrintRequest::Sysroot,
1069 early_error(format!("unknown print request `{}`", req).as_slice())
1072 }).collect::<Vec<_>>();
1073 if matches.opt_present("print-crate-name") {
1074 // FIXME(acrichto) remove this eventually
1075 early_warn("--print-crate-name has been deprecated in favor of \
1076 --print crate-name");
1077 prints.push(PrintRequest::CrateName);
1079 if matches.opt_present("print-file-name") {
1080 // FIXME(acrichto) remove this eventually
1081 early_warn("--print-file-name has been deprecated in favor of \
1082 --print file-names");
1083 prints.push(PrintRequest::FileNames);
1086 if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
1087 early_warn("-C remark will not show source locations without \
1091 let color = match matches.opt_str("color").as_ref().map(|s| s[]) {
1092 Some("auto") => Auto,
1093 Some("always") => Always,
1094 Some("never") => Never,
1099 early_error(format!("argument for --color must be auto, always \
1100 or never (instead was `{}`)",
1105 let mut externs = HashMap::new();
1106 for arg in matches.opt_strs("extern").iter() {
1107 let mut parts = arg.splitn(1, '=');
1108 let name = match parts.next() {
1110 None => early_error("--extern value must not be empty"),
1112 let location = match parts.next() {
1114 None => early_error("--extern value must be of the format `foo=bar`"),
1117 match externs.entry(name.to_string()) {
1118 Vacant(entry) => { entry.set(vec![location.to_string()]); },
1119 Occupied(mut entry) => { entry.get_mut().push(location.to_string()); },
1123 let crate_name = matches.opt_str("crate-name");
1126 crate_types: crate_types,
1128 optimize: opt_level,
1129 debuginfo: debuginfo,
1130 lint_opts: lint_opts,
1131 describe_lints: describe_lints,
1132 output_types: output_types,
1133 search_paths: search_paths,
1134 maybe_sysroot: sysroot_opt,
1135 target_triple: target,
1138 parse_only: parse_only,
1140 no_analysis: no_analysis,
1141 debugging_opts: debugging_opts,
1142 write_dependency_info: write_dependency_info,
1147 crate_name: crate_name,
1153 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
1155 let mut crate_types: Vec<CrateType> = Vec::new();
1156 for unparsed_crate_type in list_list.iter() {
1157 for part in unparsed_crate_type.split(',') {
1158 let new_part = match part {
1159 "lib" => default_lib_output(),
1160 "rlib" => CrateTypeRlib,
1161 "staticlib" => CrateTypeStaticlib,
1162 "dylib" => CrateTypeDylib,
1163 "bin" => CrateTypeExecutable,
1165 return Err(format!("unknown crate type: `{}`",
1169 crate_types.push(new_part)
1173 return Ok(crate_types);
1176 impl fmt::Show for CrateType {
1177 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1179 CrateTypeExecutable => "bin".fmt(f),
1180 CrateTypeDylib => "dylib".fmt(f),
1181 CrateTypeRlib => "rlib".fmt(f),
1182 CrateTypeStaticlib => "staticlib".fmt(f)
1190 use session::config::{build_configuration, optgroups, build_session_options};
1191 use session::build_session;
1193 use getopts::getopts;
1195 use syntax::attr::AttrMetaMethods;
1196 use syntax::diagnostics;
1198 // When the user supplies --test we should implicitly supply --cfg test
1200 fn test_switch_implies_cfg_test() {
1202 &match getopts(&["--test".to_string()], optgroups()[]) {
1204 Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
1206 let registry = diagnostics::registry::Registry::new(&[]);
1207 let sessopts = build_session_options(matches);
1208 let sess = build_session(sessopts, None, registry);
1209 let cfg = build_configuration(&sess);
1210 assert!((attr::contains_name(cfg[], "test")));
1213 // When the user supplies --test and --cfg test, don't implicitly add
1214 // another --cfg test
1216 fn test_switch_implies_cfg_test_unless_cfg_test() {
1218 &match getopts(&["--test".to_string(), "--cfg=test".to_string()],
1222 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
1225 let registry = diagnostics::registry::Registry::new(&[]);
1226 let sessopts = build_session_options(matches);
1227 let sess = build_session(sessopts, None, registry);
1228 let cfg = build_configuration(&sess);
1229 let mut test_items = cfg.iter().filter(|m| m.name() == "test");
1230 assert!(test_items.next().is_some());
1231 assert!(test_items.next().is_none());
1235 fn test_can_print_warnings() {
1237 let matches = getopts(&[
1238 "-Awarnings".to_string()
1239 ], optgroups()[]).unwrap();
1240 let registry = diagnostics::registry::Registry::new(&[]);
1241 let sessopts = build_session_options(&matches);
1242 let sess = build_session(sessopts, None, registry);
1243 assert!(!sess.can_print_warnings);
1247 let matches = getopts(&[
1248 "-Awarnings".to_string(),
1249 "-Dwarnings".to_string()
1250 ], optgroups()[]).unwrap();
1251 let registry = diagnostics::registry::Registry::new(&[]);
1252 let sessopts = build_session_options(&matches);
1253 let sess = build_session(sessopts, None, registry);
1254 assert!(sess.can_print_warnings);
1258 let matches = getopts(&[
1259 "-Adead_code".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);