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
;
35 use syntax
::feature_gate
::UnstableFeatures
;
38 use std
::collections
::HashMap
;
41 use std
::path
::PathBuf
;
48 pub uint_type
: UintTy
,
51 #[derive(Clone, Copy, PartialEq)]
59 #[derive(Clone, Copy, PartialEq)]
60 pub enum DebugInfoLevel
{
66 #[derive(Clone, Copy, PartialEq, PartialOrd, Ord, Eq)]
70 OutputTypeLlvmAssembly
,
78 // The crate config requested for the session, which may be combined
79 // with additional crate configurations during the compile process
80 pub crate_types
: Vec
<CrateType
>,
83 pub optimize
: OptLevel
,
84 pub debug_assertions
: bool
,
85 pub debuginfo
: DebugInfoLevel
,
86 pub lint_opts
: Vec
<(String
, lint
::Level
)>,
87 pub lint_cap
: Option
<lint
::Level
>,
88 pub describe_lints
: bool
,
89 pub output_types
: Vec
<OutputType
>,
90 // This was mutable for rustpkg, which updates search paths based on the
91 // parsed code. It remains mutable in case its replacements wants to use
93 pub search_paths
: SearchPaths
,
94 pub libs
: Vec
<(String
, cstore
::NativeLibraryKind
)>,
95 pub maybe_sysroot
: Option
<PathBuf
>,
96 pub target_triple
: String
,
97 // User-specified cfg meta items. The compiler itself will add additional
98 // items to the crate config, and during parsing the entire crate config
99 // will be added to the crate AST node. This should not be used for
100 // anything except building the full crate config prior to parsing.
101 pub cfg
: ast
::CrateConfig
,
103 pub parse_only
: bool
,
105 pub treat_err_as_bug
: bool
,
106 pub no_analysis
: bool
,
107 pub debugging_opts
: DebuggingOptions
,
108 /// Whether to write dependency files. It's (enabled, optional filename).
109 pub write_dependency_info
: (bool
, Option
<PathBuf
>),
110 pub prints
: Vec
<PrintRequest
>,
111 pub cg
: CodegenOptions
,
112 pub color
: ColorConfig
,
113 pub show_span
: Option
<String
>,
114 pub externs
: HashMap
<String
, Vec
<String
>>,
115 pub crate_name
: Option
<String
>,
116 /// An optional name to use as the crate for std during std injection,
117 /// written `extern crate std = "name"`. Default to "std". Used by
118 /// out-of-tree drivers.
119 pub alt_std_name
: Option
<String
>,
120 /// Indicates how the compiler should treat unstable features
121 pub unstable_features
: UnstableFeatures
124 #[derive(Clone, PartialEq, Eq)]
125 pub enum PrintRequest
{
132 /// Load source from file
134 /// The string is the source
139 pub fn filestem(&self) -> String
{
141 Input
::File(ref ifile
) => ifile
.file_stem().unwrap()
142 .to_str().unwrap().to_string(),
143 Input
::Str(_
) => "rust_out".to_string(),
149 pub struct OutputFilenames
{
150 pub out_directory
: PathBuf
,
151 pub out_filestem
: String
,
152 pub single_output_file
: Option
<PathBuf
>,
156 impl OutputFilenames
{
157 pub fn path(&self, flavor
: OutputType
) -> PathBuf
{
158 match self.single_output_file
{
159 Some(ref path
) => return path
.clone(),
162 self.temp_path(flavor
)
165 pub fn temp_path(&self, flavor
: OutputType
) -> PathBuf
{
166 let base
= self.out_directory
.join(&self.filestem());
168 OutputTypeBitcode
=> base
.with_extension("bc"),
169 OutputTypeAssembly
=> base
.with_extension("s"),
170 OutputTypeLlvmAssembly
=> base
.with_extension("ll"),
171 OutputTypeObject
=> base
.with_extension("o"),
172 OutputTypeDepInfo
=> base
.with_extension("d"),
173 OutputTypeExe
=> base
,
177 pub fn with_extension(&self, extension
: &str) -> PathBuf
{
178 self.out_directory
.join(&self.filestem()).with_extension(extension
)
181 pub fn filestem(&self) -> String
{
182 format
!("{}{}", self.out_filestem
, self.extra
)
186 pub fn host_triple() -> &'
static str {
187 // Get the host triple out of the build environment. This ensures that our
188 // idea of the host triple is the same as for the set of libraries we've
189 // actually built. We can't just take LLVM's host triple because they
190 // normalize all ix86 architectures to i386.
192 // Instead of grabbing the host triple (for the current host), we grab (at
193 // compile time) the target triple that this rustc is built with and
194 // calling that (at runtime) the host triple.
195 (option_env
!("CFG_COMPILER_HOST_TRIPLE")).
196 expect("CFG_COMPILER_HOST_TRIPLE")
199 /// Some reasonable defaults
200 pub fn basic_options() -> Options
{
202 crate_types
: Vec
::new(),
205 debuginfo
: NoDebugInfo
,
206 lint_opts
: Vec
::new(),
208 describe_lints
: false,
209 output_types
: Vec
::new(),
210 search_paths
: SearchPaths
::new(),
212 target_triple
: host_triple().to_string(),
217 treat_err_as_bug
: false,
219 debugging_opts
: basic_debugging_options(),
220 write_dependency_info
: (false, None
),
222 cg
: basic_codegen_options(),
225 externs
: HashMap
::new(),
229 unstable_features
: UnstableFeatures
::Disallow
,
230 debug_assertions
: true,
234 // The type of entry function, so
235 // users can have their own entry
236 // functions that don't start a
238 #[derive(Copy, Clone, PartialEq)]
239 pub enum EntryFnType
{
245 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
255 SomePasses(Vec
<String
>),
260 pub fn is_empty(&self) -> bool
{
262 SomePasses(ref v
) => v
.is_empty(),
268 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
269 /// at once. The goal of this macro is to define an interface that can be
270 /// programmatically used by the option parser in order to initialize the struct
271 /// without hardcoding field names all over the place.
273 /// The goal is to invoke this macro once with the correct fields, and then this
274 /// macro generates all necessary code. The main gotcha of this macro is the
275 /// cgsetters module which is a bunch of generated code to parse an option into
276 /// its respective field in the struct. There are a few hand-written parsers for
277 /// parsing specific types of values in this module.
278 macro_rules
! options
{
279 ($struct_name
:ident
, $setter_name
:ident
, $defaultfn
:ident
,
280 $buildfn
:ident
, $prefix
:expr
, $outputname
:expr
,
281 $stat
:ident
, $mod_desc
:ident
, $mod_set
:ident
,
282 $
($opt
:ident
: $t
:ty
= ($init
:expr
, $parse
:ident
, $desc
:expr
)),* ,) =>
285 pub struct $struct_name { $(pub $opt: $t),* }
287 pub fn $
defaultfn() -> $struct_name
{
288 $struct_name { $($opt: $init),* }
291 pub fn $
buildfn(matches
: &getopts
::Matches
) -> $struct_name
293 let mut op
= $
defaultfn();
294 for option
in matches
.opt_strs($prefix
) {
295 let mut iter
= option
.splitn(2, '
='
);
296 let key
= iter
.next().unwrap();
297 let value
= iter
.next();
298 let option_to_lookup
= key
.replace("-", "_");
299 let mut found
= false;
300 for &(candidate
, setter
, opt_type_desc
, _
) in $stat
{
301 if option_to_lookup
!= candidate { continue }
302 if !setter(&mut op
, value
) {
303 match (value
, opt_type_desc
) {
304 (Some(..), None
) => {
305 early_error(&format
!("{} option `{}` takes no \
306 value", $outputname
, key
))
308 (None
, Some(type_desc
)) => {
309 early_error(&format
!("{0} option `{1}` requires \
310 {2} ({3} {1}=<value>)",
314 (Some(value
), Some(type_desc
)) => {
315 early_error(&format
!("incorrect value `{}` for {} \
316 option `{}` - {} was expected",
320 (None
, None
) => unreachable
!()
327 early_error(&format
!("unknown {} option: `{}`",
334 pub type $setter_name
= fn(&mut $struct_name
, v
: Option
<&str>) -> bool
;
335 pub const $stat
: &'
static [(&'
static str, $setter_name
,
336 Option
<&'
static str>, &'
static str)] =
337 &[ $
( (stringify
!($opt
), $mod_set
::$opt
, $mod_desc
::$parse
, $desc
) ),* ];
339 #[allow(non_upper_case_globals, dead_code)]
341 pub const parse_bool
: Option
<&'
static str> = None
;
342 pub const parse_opt_bool
: Option
<&'
static str> =
343 Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
344 pub const parse_string
: Option
<&'
static str> = Some("a string");
345 pub const parse_opt_string
: Option
<&'
static str> = Some("a string");
346 pub const parse_list
: Option
<&'
static str> = Some("a space-separated list of strings");
347 pub const parse_opt_list
: Option
<&'
static str> = Some("a space-separated list of strings");
348 pub const parse_uint
: Option
<&'
static str> = Some("a number");
349 pub const parse_passes
: Option
<&'
static str> =
350 Some("a space-separated list of passes, or `all`");
351 pub const parse_opt_uint
: Option
<&'
static str> =
357 use super::{$struct_name, Passes, SomePasses, AllPasses}
;
360 pub fn $
opt(cg
: &mut $struct_name
, v
: Option
<&str>) -> bool
{
361 $
parse(&mut cg
.$opt
, v
)
365 fn parse_bool(slot
: &mut bool
, v
: Option
<&str>) -> bool
{
368 None
=> { *slot = true; true }
372 fn parse_opt_bool(slot
: &mut Option
<bool
>, v
: Option
<&str>) -> bool
{
376 "n" | "no" | "off" => {
379 "y" | "yes" | "on" => {
382 _
=> { return false; }
387 None
=> { *slot = Some(true); true }
391 fn parse_opt_string(slot
: &mut Option
<String
>, v
: Option
<&str>) -> bool
{
393 Some(s
) => { *slot = Some(s.to_string()); true }
,
398 fn parse_string(slot
: &mut String
, v
: Option
<&str>) -> bool
{
400 Some(s
) => { *slot = s.to_string(); true }
,
405 fn parse_list(slot
: &mut Vec
<String
>, v
: Option
<&str>)
409 for s
in s
.split_whitespace() {
410 slot
.push(s
.to_string());
418 fn parse_opt_list(slot
: &mut Option
<Vec
<String
>>, v
: Option
<&str>)
422 let v
= s
.split_whitespace().map(|s
| s
.to_string()).collect();
430 fn parse_uint(slot
: &mut usize, v
: Option
<&str>) -> bool
{
431 match v
.and_then(|s
| s
.parse().ok()) {
432 Some(i
) => { *slot = i; true }
,
437 fn parse_opt_uint(slot
: &mut Option
<usize>, v
: Option
<&str>) -> bool
{
439 Some(s
) => { *slot = s.parse().ok(); slot.is_some() }
440 None
=> { *slot = None; true }
444 fn parse_passes(slot
: &mut Passes
, v
: Option
<&str>) -> bool
{
451 let mut passes
= vec
!();
452 if parse_list(&mut passes
, v
) {
453 *slot
= SomePasses(passes
);
464 options
! {CodegenOptions
, CodegenSetter
, basic_codegen_options
,
465 build_codegen_options
, "C", "codegen",
466 CG_OPTIONS
, cg_type_desc
, cgsetters
,
467 ar
: Option
<String
> = (None
, parse_opt_string
,
468 "tool to assemble archives with"),
469 linker
: Option
<String
> = (None
, parse_opt_string
,
470 "system linker to link outputs with"),
471 link_args
: Option
<Vec
<String
>> = (None
, parse_opt_list
,
472 "extra arguments to pass to the linker (space separated)"),
473 lto
: bool
= (false, parse_bool
,
474 "perform LLVM link-time optimizations"),
475 target_cpu
: Option
<String
> = (None
, parse_opt_string
,
476 "select target processor (llc -mcpu=help for details)"),
477 target_feature
: String
= ("".to_string(), parse_string
,
478 "target specific attributes (llc -mattr=help for details)"),
479 passes
: Vec
<String
> = (Vec
::new(), parse_list
,
480 "a list of extra LLVM passes to run (space separated)"),
481 llvm_args
: Vec
<String
> = (Vec
::new(), parse_list
,
482 "a list of arguments to pass to llvm (space separated)"),
483 save_temps
: bool
= (false, parse_bool
,
484 "save all temporary output files during compilation"),
485 rpath
: bool
= (false, parse_bool
,
486 "set rpath values in libs/exes"),
487 no_prepopulate_passes
: bool
= (false, parse_bool
,
488 "don't pre-populate the pass manager with a list of passes"),
489 no_vectorize_loops
: bool
= (false, parse_bool
,
490 "don't run the loop vectorization optimization passes"),
491 no_vectorize_slp
: bool
= (false, parse_bool
,
492 "don't run LLVM's SLP vectorization pass"),
493 soft_float
: bool
= (false, parse_bool
,
494 "generate software floating point library calls"),
495 prefer_dynamic
: bool
= (false, parse_bool
,
496 "prefer dynamic linking to static linking"),
497 no_integrated_as
: bool
= (false, parse_bool
,
498 "use an external assembler rather than LLVM's integrated one"),
499 no_redzone
: Option
<bool
> = (None
, parse_opt_bool
,
500 "disable the use of the redzone"),
501 relocation_model
: Option
<String
> = (None
, parse_opt_string
,
502 "choose the relocation model to use (llc -relocation-model for details)"),
503 code_model
: Option
<String
> = (None
, parse_opt_string
,
504 "choose the code model to use (llc -code-model for details)"),
505 metadata
: Vec
<String
> = (Vec
::new(), parse_list
,
506 "metadata to mangle symbol names with"),
507 extra_filename
: String
= ("".to_string(), parse_string
,
508 "extra data to put in each output filename"),
509 codegen_units
: usize = (1, parse_uint
,
510 "divide crate into N units to optimize in parallel"),
511 remark
: Passes
= (SomePasses(Vec
::new()), parse_passes
,
512 "print remarks for these optimization passes (space separated, or \"all\")"),
513 no_stack_check
: bool
= (false, parse_bool
,
514 "disable checks for stack exhaustion (a memory-safety hazard!)"),
515 debuginfo
: Option
<usize> = (None
, parse_opt_uint
,
516 "debug info emission level, 0 = no debug info, 1 = line tables only, \
517 2 = full debug info with variable and type information"),
518 opt_level
: Option
<usize> = (None
, parse_opt_uint
,
519 "Optimize with possible levels 0-3"),
520 debug_assertions
: Option
<bool
> = (None
, parse_opt_bool
,
521 "explicitly enable the cfg(debug_assertions) directive"),
525 options
! {DebuggingOptions
, DebuggingSetter
, basic_debugging_options
,
526 build_debugging_options
, "Z", "debugging",
527 DB_OPTIONS
, db_type_desc
, dbsetters
,
528 verbose
: bool
= (false, parse_bool
,
529 "in general, enable more debug printouts"),
530 time_passes
: bool
= (false, parse_bool
,
531 "measure time of each rustc pass"),
532 count_llvm_insns
: bool
= (false, parse_bool
,
533 "count where LLVM instrs originate"),
534 time_llvm_passes
: bool
= (false, parse_bool
,
535 "measure time of each LLVM pass"),
536 trans_stats
: bool
= (false, parse_bool
,
537 "gather trans statistics"),
538 asm_comments
: bool
= (false, parse_bool
,
539 "generate comments into the assembly (may change behavior)"),
540 no_verify
: bool
= (false, parse_bool
,
541 "skip LLVM verification"),
542 borrowck_stats
: bool
= (false, parse_bool
,
543 "gather borrowck statistics"),
544 no_landing_pads
: bool
= (false, parse_bool
,
545 "omit landing pads for unwinding"),
546 debug_llvm
: bool
= (false, parse_bool
,
547 "enable debug output from LLVM"),
548 count_type_sizes
: bool
= (false, parse_bool
,
549 "count the sizes of aggregate types"),
550 meta_stats
: bool
= (false, parse_bool
,
551 "gather metadata statistics"),
552 print_link_args
: bool
= (false, parse_bool
,
553 "Print the arguments passed to the linker"),
554 gc
: bool
= (false, parse_bool
,
555 "Garbage collect shared data (experimental)"),
556 print_llvm_passes
: bool
= (false, parse_bool
,
557 "Prints the llvm optimization passes being run"),
558 ast_json
: bool
= (false, parse_bool
,
559 "Print the AST as JSON and halt"),
560 ast_json_noexpand
: bool
= (false, parse_bool
,
561 "Print the pre-expansion AST as JSON and halt"),
562 ls
: bool
= (false, parse_bool
,
563 "List the symbols defined by a library crate"),
564 save_analysis
: bool
= (false, parse_bool
,
565 "Write syntax and type analysis information in addition to normal output"),
566 print_move_fragments
: bool
= (false, parse_bool
,
567 "Print out move-fragment data for every fn"),
568 flowgraph_print_loans
: bool
= (false, parse_bool
,
569 "Include loan analysis data in --pretty flowgraph output"),
570 flowgraph_print_moves
: bool
= (false, parse_bool
,
571 "Include move analysis data in --pretty flowgraph output"),
572 flowgraph_print_assigns
: bool
= (false, parse_bool
,
573 "Include assignment analysis data in --pretty flowgraph output"),
574 flowgraph_print_all
: bool
= (false, parse_bool
,
575 "Include all dataflow analysis data in --pretty flowgraph output"),
576 print_region_graph
: bool
= (false, parse_bool
,
577 "Prints region inference graph. \
578 Use with RUST_REGION_GRAPH=help for more info"),
579 parse_only
: bool
= (false, parse_bool
,
580 "Parse only; do not compile, assemble, or link"),
581 no_trans
: bool
= (false, parse_bool
,
582 "Run all passes except translation; no output"),
583 treat_err_as_bug
: bool
= (false, parse_bool
,
584 "Treat all errors that occur as bugs"),
585 no_analysis
: bool
= (false, parse_bool
,
586 "Parse and expand the source, but run no analysis"),
587 extra_plugins
: Vec
<String
> = (Vec
::new(), parse_list
,
588 "load extra plugins"),
589 unstable_options
: bool
= (false, parse_bool
,
590 "Adds unstable command line options to rustc interface"),
591 print_enum_sizes
: bool
= (false, parse_bool
,
592 "Print the size of enums and their variants"),
593 force_overflow_checks
: Option
<bool
> = (None
, parse_opt_bool
,
594 "Force overflow checks on or off"),
595 force_dropflag_checks
: Option
<bool
> = (None
, parse_opt_bool
,
596 "Force drop flag checks on or off"),
597 trace_macros
: bool
= (false, parse_bool
,
598 "For every macro invocation, print its name and arguments"),
599 enable_nonzeroing_move_hints
: bool
= (false, parse_bool
,
600 "Force nonzeroing move optimization on"),
603 pub fn default_lib_output() -> CrateType
{
607 pub fn default_configuration(sess
: &Session
) -> ast
::CrateConfig
{
608 use syntax
::parse
::token
::intern_and_get_ident
as intern
;
610 let end
= &sess
.target
.target
.target_endian
;
611 let arch
= &sess
.target
.target
.arch
;
612 let wordsz
= &sess
.target
.target
.target_pointer_width
;
613 let os
= &sess
.target
.target
.target_os
;
614 let env
= &sess
.target
.target
.target_env
;
616 let fam
= match sess
.target
.target
.options
.is_like_windows
{
617 true => InternedString
::new("windows"),
618 false => InternedString
::new("unix")
621 let mk
= attr
::mk_name_value_item_str
;
622 let mut ret
= vec
![ // Target bindings.
623 attr
::mk_word_item(fam
.clone()),
624 mk(InternedString
::new("target_os"), intern(os
)),
625 mk(InternedString
::new("target_family"), fam
),
626 mk(InternedString
::new("target_arch"), intern(arch
)),
627 mk(InternedString
::new("target_endian"), intern(end
)),
628 mk(InternedString
::new("target_pointer_width"), intern(wordsz
)),
629 mk(InternedString
::new("target_env"), intern(env
)),
631 if sess
.opts
.debug_assertions
{
632 ret
.push(attr
::mk_word_item(InternedString
::new("debug_assertions")));
637 pub fn append_configuration(cfg
: &mut ast
::CrateConfig
,
638 name
: InternedString
) {
639 if !cfg
.iter().any(|mi
| mi
.name() == name
) {
640 cfg
.push(attr
::mk_word_item(name
))
644 pub fn build_configuration(sess
: &Session
) -> ast
::CrateConfig
{
645 // Combine the configuration requested by the session (command line) with
646 // some default and generated configuration items
647 let default_cfg
= default_configuration(sess
);
648 let mut user_cfg
= sess
.opts
.cfg
.clone();
649 // If the user wants a test runner, then add the test cfg
651 append_configuration(&mut user_cfg
, InternedString
::new("test"))
653 let mut v
= user_cfg
.into_iter().collect
::<Vec
<_
>>();
654 v
.push_all(&default_cfg
[..]);
658 pub fn build_target_config(opts
: &Options
, sp
: &SpanHandler
) -> Config
{
659 let target
= match Target
::search(&opts
.target_triple
) {
662 sp
.handler().fatal(&format
!("Error loading target specification: {}", e
));
666 let (int_type
, uint_type
) = match &target
.target_pointer_width
[..] {
667 "32" => (ast
::TyI32
, ast
::TyU32
),
668 "64" => (ast
::TyI64
, ast
::TyU64
),
669 w
=> sp
.handler().fatal(&format
!("target specification was invalid: unrecognized \
670 target-pointer-width {}", w
))
676 uint_type
: uint_type
,
680 /// Returns the "short" subset of the stable rustc command line options.
681 pub fn short_optgroups() -> Vec
<getopts
::OptGroup
> {
682 rustc_short_optgroups().into_iter()
683 .filter(|g
|g
.is_stable())
688 /// Returns all of the stable rustc command line options.
689 pub fn optgroups() -> Vec
<getopts
::OptGroup
> {
690 rustc_optgroups().into_iter()
691 .filter(|g
|g
.is_stable())
696 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
697 pub enum OptionStability { Stable, Unstable }
699 #[derive(Clone, PartialEq, Eq)]
700 pub struct RustcOptGroup
{
701 pub opt_group
: getopts
::OptGroup
,
702 pub stability
: OptionStability
,
706 pub fn is_stable(&self) -> bool
{
707 self.stability
== OptionStability
::Stable
710 fn stable(g
: getopts
::OptGroup
) -> RustcOptGroup
{
711 RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
714 fn unstable(g
: getopts
::OptGroup
) -> RustcOptGroup
{
715 RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
719 // The `opt` local module holds wrappers around the `getopts` API that
720 // adds extra rustc-specific metadata to each option; such metadata
721 // is exposed by . The public
722 // functions below ending with `_u` are the functions that return
723 // *unstable* options, i.e. options that are only enabled when the
724 // user also passes the `-Z unstable-options` debugging flag.
726 // The `fn opt_u` etc below are written so that we can use them
727 // in the future; do not warn about them not being used right now.
731 use super::RustcOptGroup
;
733 pub type R
= RustcOptGroup
;
734 pub type S
<'a
> = &'a
str;
736 fn stable(g
: getopts
::OptGroup
) -> R { RustcOptGroup::stable(g) }
737 fn unstable(g
: getopts
::OptGroup
) -> R { RustcOptGroup::unstable(g) }
739 // FIXME (pnkfelix): We default to stable since the current set of
740 // options is defacto stable. However, it would be good to revise the
741 // code so that a stable option is the thing that takes extra effort
744 pub fn opt(a
: S
, b
: S
, c
: S
, d
: S
) -> R { stable(getopts::optopt(a, b, c, d)) }
745 pub fn multi(a
: S
, b
: S
, c
: S
, d
: S
) -> R { stable(getopts::optmulti(a, b, c, d)) }
746 pub fn flag(a
: S
, b
: S
, c
: S
) -> R { stable(getopts::optflag(a, b, c)) }
747 pub fn flagopt(a
: S
, b
: S
, c
: S
, d
: S
) -> R { stable(getopts::optflagopt(a, b, c, d)) }
748 pub fn flagmulti(a
: S
, b
: S
, c
: S
) -> R { stable(getopts::optflagmulti(a, b, c)) }
751 pub fn opt_u(a
: S
, b
: S
, c
: S
, d
: S
) -> R { unstable(getopts::optopt(a, b, c, d)) }
752 pub fn multi_u(a
: S
, b
: S
, c
: S
, d
: S
) -> R { unstable(getopts::optmulti(a, b, c, d)) }
753 pub fn flag_u(a
: S
, b
: S
, c
: S
) -> R { unstable(getopts::optflag(a, b, c)) }
754 pub fn flagopt_u(a
: S
, b
: S
, c
: S
, d
: S
) -> R { unstable(getopts::optflagopt(a, b, c, d)) }
755 pub fn flagmulti_u(a
: S
, b
: S
, c
: S
) -> R { unstable(getopts::optflagmulti(a, b, c)) }
758 /// Returns the "short" subset of the rustc command line options,
759 /// including metadata for each option, such as whether the option is
760 /// part of the stable long-term interface for rustc.
761 pub fn rustc_short_optgroups() -> Vec
<RustcOptGroup
> {
763 opt
::flag("h", "help", "Display this message"),
764 opt
::multi("", "cfg", "Configure the compilation environment", "SPEC"),
765 opt
::multi("L", "", "Add a directory to the library search path",
767 opt
::multi("l", "", "Link the generated crate(s) to the specified native
768 library NAME. The optional KIND can be one of,
769 static, dylib, or framework. If omitted, dylib is
770 assumed.", "[KIND=]NAME"),
771 opt
::multi("", "crate-type", "Comma separated list of types of crates
772 for the compiler to emit",
773 "[bin|lib|rlib|dylib|staticlib]"),
774 opt
::opt("", "crate-name", "Specify the name of the crate being built",
776 opt
::multi("", "emit", "Comma separated list of types of output for \
777 the compiler to emit",
778 "[asm|llvm-bc|llvm-ir|obj|link|dep-info]"),
779 opt
::multi("", "print", "Comma separated list of compiler information to \
781 "[crate-name|file-names|sysroot]"),
782 opt
::flagmulti("g", "", "Equivalent to -C debuginfo=2"),
783 opt
::flagmulti("O", "", "Equivalent to -C opt-level=2"),
784 opt
::opt("o", "", "Write output to <filename>", "FILENAME"),
785 opt
::opt("", "out-dir", "Write output to compiler-chosen filename \
787 opt
::opt("", "explain", "Provide a detailed explanation of an error \
789 opt
::flag("", "test", "Build a test harness"),
790 opt
::opt("", "target", "Target triple cpu-manufacturer-kernel[-os] \
791 to compile for (see chapter 3.4 of \
792 http://www.sourceware.org/autobook/
795 opt
::multi("W", "warn", "Set lint warnings", "OPT"),
796 opt
::multi("A", "allow", "Set lint allowed", "OPT"),
797 opt
::multi("D", "deny", "Set lint denied", "OPT"),
798 opt
::multi("F", "forbid", "Set lint forbidden", "OPT"),
799 opt
::multi("", "cap-lints", "Set the most restrictive lint level. \
800 More restrictive lints are capped at this \
802 opt
::multi("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
803 opt
::flag("V", "version", "Print version info and exit"),
804 opt
::flag("v", "verbose", "Use verbose output"),
808 /// Returns all rustc command line options, including metadata for
809 /// each option, such as whether the option is part of the stable
810 /// long-term interface for rustc.
811 pub fn rustc_optgroups() -> Vec
<RustcOptGroup
> {
812 let mut opts
= rustc_short_optgroups();
814 opt
::multi("", "extern", "Specify where an external rust library is \
817 opt
::opt("", "sysroot", "Override the system root", "PATH"),
818 opt
::multi("Z", "", "Set internal debugging options", "FLAG"),
819 opt
::opt("", "color", "Configure coloring of output:
820 auto = colorize, if output goes to a tty (default);
821 always = always colorize output;
822 never = never colorize output", "auto|always|never"),
824 opt
::flagopt_u("", "pretty",
825 "Pretty-print the input instead of compiling;
826 valid types are: `normal` (un-annotated source),
827 `expanded` (crates expanded),
828 `typed` (crates expanded, with type annotations), or
829 `expanded,identified` (fully parenthesized, AST nodes with IDs).",
831 opt
::flagopt_u("", "unpretty",
832 "Present the input source, unstable (and less-pretty) variants;
833 valid types are any of the types for `--pretty`, as well as:
834 `flowgraph=<nodeid>` (graphviz formatted flowgraph for node), or
835 `everybody_loops` (all function bodies replaced with `loop {}`).",
837 opt
::opt_u("", "show-span", "Show spans for compiler debugging", "expr|pat|ty"),
842 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
843 pub fn parse_cfgspecs(cfgspecs
: Vec
<String
> ) -> ast
::CrateConfig
{
844 cfgspecs
.into_iter().map(|s
| {
845 parse
::parse_meta_from_source_str("cfgspec".to_string(),
848 &parse
::ParseSess
::new())
849 }).collect
::<ast
::CrateConfig
>()
852 pub fn build_session_options(matches
: &getopts
::Matches
) -> Options
{
853 let unparsed_crate_types
= matches
.opt_strs("crate-type");
854 let crate_types
= parse_crate_types_from_list(unparsed_crate_types
)
855 .unwrap_or_else(|e
| early_error(&e
[..]));
857 let mut lint_opts
= vec
!();
858 let mut describe_lints
= false;
860 for &level
in &[lint
::Allow
, lint
::Warn
, lint
::Deny
, lint
::Forbid
] {
861 for lint_name
in matches
.opt_strs(level
.as_str()) {
862 if lint_name
== "help" {
863 describe_lints
= true;
865 lint_opts
.push((lint_name
.replace("-", "_"), level
));
870 let lint_cap
= matches
.opt_str("cap-lints").map(|cap
| {
871 lint
::Level
::from_str(&cap
).unwrap_or_else(|| {
872 early_error(&format
!("unknown lint level: `{}`", cap
))
876 let debugging_opts
= build_debugging_options(matches
);
878 let parse_only
= debugging_opts
.parse_only
;
879 let no_trans
= debugging_opts
.no_trans
;
880 let treat_err_as_bug
= debugging_opts
.treat_err_as_bug
;
881 let no_analysis
= debugging_opts
.no_analysis
;
883 if debugging_opts
.debug_llvm
{
884 unsafe { llvm::LLVMSetDebug(1); }
887 let mut output_types
= Vec
::new();
888 if !debugging_opts
.parse_only
&& !no_trans
{
889 let unparsed_output_types
= matches
.opt_strs("emit");
890 for unparsed_output_type
in &unparsed_output_types
{
891 for part
in unparsed_output_type
.split('
,'
) {
892 let output_type
= match part
{
893 "asm" => OutputTypeAssembly
,
894 "llvm-ir" => OutputTypeLlvmAssembly
,
895 "llvm-bc" => OutputTypeBitcode
,
896 "obj" => OutputTypeObject
,
897 "link" => OutputTypeExe
,
898 "dep-info" => OutputTypeDepInfo
,
900 early_error(&format
!("unknown emission type: `{}`",
904 output_types
.push(output_type
)
909 output_types
.dedup();
910 if output_types
.is_empty() {
911 output_types
.push(OutputTypeExe
);
914 let cg
= build_codegen_options(matches
);
916 let sysroot_opt
= matches
.opt_str("sysroot").map(|m
| PathBuf
::from(&m
));
917 let target
= matches
.opt_str("target").unwrap_or(
918 host_triple().to_string());
920 if matches
.opt_present("O") {
921 if cg
.opt_level
.is_some() {
922 early_error("-O and -C opt-level both provided");
931 Some(3) => Aggressive
,
933 early_error(&format
!("optimization level needs to be \
934 between 0-3 (instead was `{}`)",
940 let debug_assertions
= cg
.debug_assertions
.unwrap_or(opt_level
== No
);
941 let gc
= debugging_opts
.gc
;
942 let debuginfo
= if matches
.opt_present("g") {
943 if cg
.debuginfo
.is_some() {
944 early_error("-g and -C debuginfo both provided");
949 None
| Some(0) => NoDebugInfo
,
950 Some(1) => LimitedDebugInfo
,
951 Some(2) => FullDebugInfo
,
953 early_error(&format
!("debug info level needs to be between \
954 0-2 (instead was `{}`)",
960 let mut search_paths
= SearchPaths
::new();
961 for s
in &matches
.opt_strs("L") {
962 search_paths
.add_path(&s
[..]);
965 let libs
= matches
.opt_strs("l").into_iter().map(|s
| {
966 let mut parts
= s
.splitn(2, '
='
);
967 let kind
= parts
.next().unwrap();
968 let (name
, kind
) = match (parts
.next(), kind
) {
970 (Some(name
), "dylib") => (name
, cstore
::NativeUnknown
),
971 (Some(name
), "framework") => (name
, cstore
::NativeFramework
),
972 (Some(name
), "static") => (name
, cstore
::NativeStatic
),
974 early_error(&format
!("unknown library kind `{}`, expected \
975 one of dylib, framework, or static",
979 (name
.to_string(), kind
)
982 let cfg
= parse_cfgspecs(matches
.opt_strs("cfg"));
983 let test
= matches
.opt_present("test");
984 let write_dependency_info
= (output_types
.contains(&OutputTypeDepInfo
), None
);
986 let prints
= matches
.opt_strs("print").into_iter().map(|s
| {
988 "crate-name" => PrintRequest
::CrateName
,
989 "file-names" => PrintRequest
::FileNames
,
990 "sysroot" => PrintRequest
::Sysroot
,
992 early_error(&format
!("unknown print request `{}`", req
))
995 }).collect
::<Vec
<_
>>();
997 if !cg
.remark
.is_empty() && debuginfo
== NoDebugInfo
{
998 early_warn("-C remark will not show source locations without \
1002 let color
= match matches
.opt_str("color").as_ref().map(|s
| &s
[..]) {
1003 Some("auto") => Auto
,
1004 Some("always") => Always
,
1005 Some("never") => Never
,
1010 early_error(&format
!("argument for --color must be auto, always \
1011 or never (instead was `{}`)",
1016 let mut externs
= HashMap
::new();
1017 for arg
in &matches
.opt_strs("extern") {
1018 let mut parts
= arg
.splitn(2, '
='
);
1019 let name
= match parts
.next() {
1021 None
=> early_error("--extern value must not be empty"),
1023 let location
= match parts
.next() {
1025 None
=> early_error("--extern value must be of the format `foo=bar`"),
1028 externs
.entry(name
.to_string()).or_insert(vec
![]).push(location
.to_string());
1031 let crate_name
= matches
.opt_str("crate-name");
1034 crate_types
: crate_types
,
1036 optimize
: opt_level
,
1037 debuginfo
: debuginfo
,
1038 lint_opts
: lint_opts
,
1040 describe_lints
: describe_lints
,
1041 output_types
: output_types
,
1042 search_paths
: search_paths
,
1043 maybe_sysroot
: sysroot_opt
,
1044 target_triple
: target
,
1047 parse_only
: parse_only
,
1049 treat_err_as_bug
: treat_err_as_bug
,
1050 no_analysis
: no_analysis
,
1051 debugging_opts
: debugging_opts
,
1052 write_dependency_info
: write_dependency_info
,
1058 crate_name
: crate_name
,
1061 unstable_features
: get_unstable_features_setting(),
1062 debug_assertions
: debug_assertions
,
1066 pub fn get_unstable_features_setting() -> UnstableFeatures
{
1067 // Whether this is a feature-staged build, i.e. on the beta or stable channel
1068 let disable_unstable_features
= option_env
!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
1069 // The secret key needed to get through the rustc build itself by
1070 // subverting the unstable features lints
1071 let bootstrap_secret_key
= option_env
!("CFG_BOOTSTRAP_KEY");
1072 // The matching key to the above, only known by the build system
1073 let bootstrap_provided_key
= env
::var("RUSTC_BOOTSTRAP_KEY").ok();
1074 match (disable_unstable_features
, bootstrap_secret_key
, bootstrap_provided_key
) {
1075 (_
, Some(ref s
), Some(ref p
)) if s
== p
=> UnstableFeatures
::Cheat
,
1076 (true, _
, _
) => UnstableFeatures
::Disallow
,
1077 (false, _
, _
) => UnstableFeatures
::Allow
1081 pub fn parse_crate_types_from_list(list_list
: Vec
<String
>) -> Result
<Vec
<CrateType
>, String
> {
1083 let mut crate_types
: Vec
<CrateType
> = Vec
::new();
1084 for unparsed_crate_type
in &list_list
{
1085 for part
in unparsed_crate_type
.split('
,'
) {
1086 let new_part
= match part
{
1087 "lib" => default_lib_output(),
1088 "rlib" => CrateTypeRlib
,
1089 "staticlib" => CrateTypeStaticlib
,
1090 "dylib" => CrateTypeDylib
,
1091 "bin" => CrateTypeExecutable
,
1093 return Err(format
!("unknown crate type: `{}`",
1097 if !crate_types
.contains(&new_part
) {
1098 crate_types
.push(new_part
)
1103 return Ok(crate_types
);
1106 impl fmt
::Display
for CrateType
{
1107 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1109 CrateTypeExecutable
=> "bin".fmt(f
),
1110 CrateTypeDylib
=> "dylib".fmt(f
),
1111 CrateTypeRlib
=> "rlib".fmt(f
),
1112 CrateTypeStaticlib
=> "staticlib".fmt(f
)
1120 use session
::config
::{build_configuration, optgroups, build_session_options}
;
1121 use session
::build_session
;
1123 use getopts
::getopts
;
1125 use syntax
::attr
::AttrMetaMethods
;
1126 use syntax
::diagnostics
;
1128 // When the user supplies --test we should implicitly supply --cfg test
1130 fn test_switch_implies_cfg_test() {
1132 &match getopts(&["--test".to_string()], &optgroups()) {
1134 Err(f
) => panic
!("test_switch_implies_cfg_test: {}", f
)
1136 let registry
= diagnostics
::registry
::Registry
::new(&[]);
1137 let sessopts
= build_session_options(matches
);
1138 let sess
= build_session(sessopts
, None
, registry
);
1139 let cfg
= build_configuration(&sess
);
1140 assert
!((attr
::contains_name(&cfg
[..], "test")));
1143 // When the user supplies --test and --cfg test, don't implicitly add
1144 // another --cfg test
1146 fn test_switch_implies_cfg_test_unless_cfg_test() {
1148 &match getopts(&["--test".to_string(), "--cfg=test".to_string()],
1152 panic
!("test_switch_implies_cfg_test_unless_cfg_test: {}", f
)
1155 let registry
= diagnostics
::registry
::Registry
::new(&[]);
1156 let sessopts
= build_session_options(matches
);
1157 let sess
= build_session(sessopts
, None
, registry
);
1158 let cfg
= build_configuration(&sess
);
1159 let mut test_items
= cfg
.iter().filter(|m
| m
.name() == "test");
1160 assert
!(test_items
.next().is_some());
1161 assert
!(test_items
.next().is_none());
1165 fn test_can_print_warnings() {
1167 let matches
= getopts(&[
1168 "-Awarnings".to_string()
1169 ], &optgroups()).unwrap();
1170 let registry
= diagnostics
::registry
::Registry
::new(&[]);
1171 let sessopts
= build_session_options(&matches
);
1172 let sess
= build_session(sessopts
, None
, registry
);
1173 assert
!(!sess
.can_print_warnings
);
1177 let matches
= getopts(&[
1178 "-Awarnings".to_string(),
1179 "-Dwarnings".to_string()
1180 ], &optgroups()).unwrap();
1181 let registry
= diagnostics
::registry
::Registry
::new(&[]);
1182 let sessopts
= build_session_options(&matches
);
1183 let sess
= build_session(sessopts
, None
, registry
);
1184 assert
!(sess
.can_print_warnings
);
1188 let matches
= getopts(&[
1189 "-Adead_code".to_string()
1190 ], &optgroups()).unwrap();
1191 let registry
= diagnostics
::registry
::Registry
::new(&[]);
1192 let sessopts
= build_session_options(&matches
);
1193 let sess
= build_session(sessopts
, None
, registry
);
1194 assert
!(sess
.can_print_warnings
);