]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/config.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[rust.git] / src / librustc / session / config.rs
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.
4 //
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.
10
11 //! Contains infrastructure for configuring the compiler, including parsing
12 //! command line options.
13
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::*;
20
21 use session::{early_error, early_warn, Session};
22 use session::search_paths::SearchPaths;
23
24 use rustc_back::target::Target;
25 use lint;
26 use metadata::cstore;
27
28 use syntax::ast;
29 use syntax::ast::{IntTy, UintTy};
30 use syntax::attr;
31 use syntax::attr::AttrMetaMethods;
32 use syntax::diagnostic::{ColorConfig, Auto, Always, Never, SpanHandler};
33 use syntax::parse;
34 use syntax::parse::token::InternedString;
35
36 use getopts;
37 use std::collections::HashMap;
38 use std::collections::hash_map::Entry::{Occupied, Vacant};
39 use std::env;
40 use std::fmt;
41
42 use llvm;
43
44 pub struct Config {
45     pub target: Target,
46     pub int_type: IntTy,
47     pub uint_type: UintTy,
48 }
49
50 #[derive(Clone, Copy, PartialEq)]
51 pub enum OptLevel {
52     No, // -O0
53     Less, // -O1
54     Default, // -O2
55     Aggressive // -O3
56 }
57
58 #[derive(Clone, Copy, PartialEq)]
59 pub enum DebugInfoLevel {
60     NoDebugInfo,
61     LimitedDebugInfo,
62     FullDebugInfo,
63 }
64
65 #[derive(Clone, Copy, PartialEq, PartialOrd, Ord, Eq)]
66 pub enum OutputType {
67     OutputTypeBitcode,
68     OutputTypeAssembly,
69     OutputTypeLlvmAssembly,
70     OutputTypeObject,
71     OutputTypeExe,
72     OutputTypeDepInfo,
73 }
74
75 #[derive(Clone)]
76 pub struct Options {
77     // The crate config requested for the session, which may be combined
78     // with additional crate configurations during the compile process
79     pub crate_types: Vec<CrateType>,
80
81     pub gc: bool,
82     pub optimize: OptLevel,
83     pub debuginfo: DebugInfoLevel,
84     pub lint_opts: Vec<(String, lint::Level)>,
85     pub describe_lints: bool,
86     pub output_types: Vec<OutputType>,
87     // This was mutable for rustpkg, which updates search paths based on the
88     // parsed code. It remains mutable in case its replacements wants to use
89     // this.
90     pub search_paths: SearchPaths,
91     pub libs: Vec<(String, cstore::NativeLibraryKind)>,
92     pub maybe_sysroot: Option<Path>,
93     pub target_triple: String,
94     // User-specified cfg meta items. The compiler itself will add additional
95     // items to the crate config, and during parsing the entire crate config
96     // will be added to the crate AST node.  This should not be used for
97     // anything except building the full crate config prior to parsing.
98     pub cfg: ast::CrateConfig,
99     pub test: bool,
100     pub parse_only: bool,
101     pub no_trans: bool,
102     pub no_analysis: bool,
103     pub debugging_opts: DebuggingOptions,
104     /// Whether to write dependency files. It's (enabled, optional filename).
105     pub write_dependency_info: (bool, Option<Path>),
106     pub prints: Vec<PrintRequest>,
107     pub cg: CodegenOptions,
108     pub color: ColorConfig,
109     pub show_span: Option<String>,
110     pub externs: HashMap<String, Vec<String>>,
111     pub crate_name: Option<String>,
112     /// An optional name to use as the crate for std during std injection,
113     /// written `extern crate std = "name"`. Default to "std". Used by
114     /// out-of-tree drivers.
115     pub alt_std_name: Option<String>,
116     /// Indicates how the compiler should treat unstable features
117     pub unstable_features: UnstableFeatures
118 }
119
120 #[derive(Clone, Copy)]
121 pub enum UnstableFeatures {
122     /// Hard errors for unstable features are active, as on
123     /// beta/stable channels.
124     Disallow,
125     /// Use the default lint levels
126     Default,
127     /// Errors are bypassed for bootstrapping. This is required any time
128     /// during the build that feature-related lints are set to warn or above
129     /// because the build turns on warnings-as-errors and uses lots of unstable
130     /// features. As a result, this this is always required for building Rust
131     /// itself.
132     Cheat
133 }
134
135 #[derive(Clone, PartialEq, Eq)]
136 pub enum PrintRequest {
137     FileNames,
138     Sysroot,
139     CrateName,
140 }
141
142 pub enum Input {
143     /// Load source from file
144     File(Path),
145     /// The string is the source
146     Str(String)
147 }
148
149 impl Input {
150     pub fn filestem(&self) -> String {
151         match *self {
152             Input::File(ref ifile) => ifile.filestem_str().unwrap().to_string(),
153             Input::Str(_) => "rust_out".to_string(),
154         }
155     }
156 }
157
158 #[derive(Clone)]
159 pub struct OutputFilenames {
160     pub out_directory: Path,
161     pub out_filestem: String,
162     pub single_output_file: Option<Path>,
163     pub extra: String,
164 }
165
166 impl OutputFilenames {
167     pub fn path(&self, flavor: OutputType) -> Path {
168         match self.single_output_file {
169             Some(ref path) => return path.clone(),
170             None => {}
171         }
172         self.temp_path(flavor)
173     }
174
175     pub fn temp_path(&self, flavor: OutputType) -> Path {
176         let base = self.out_directory.join(self.filestem());
177         match flavor {
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,
184         }
185     }
186
187     pub fn with_extension(&self, extension: &str) -> Path {
188         self.out_directory.join(self.filestem()).with_extension(extension)
189     }
190
191     pub fn filestem(&self) -> String {
192         format!("{}{}", self.out_filestem, self.extra)
193     }
194 }
195
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.
201     //
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")
207 }
208
209 /// Some reasonable defaults
210 pub fn basic_options() -> Options {
211     Options {
212         crate_types: Vec::new(),
213         gc: false,
214         optimize: No,
215         debuginfo: NoDebugInfo,
216         lint_opts: Vec::new(),
217         describe_lints: false,
218         output_types: Vec::new(),
219         search_paths: SearchPaths::new(),
220         maybe_sysroot: None,
221         target_triple: host_triple().to_string(),
222         cfg: Vec::new(),
223         test: false,
224         parse_only: false,
225         no_trans: false,
226         no_analysis: false,
227         debugging_opts: basic_debugging_options(),
228         write_dependency_info: (false, None),
229         prints: Vec::new(),
230         cg: basic_codegen_options(),
231         color: Auto,
232         show_span: None,
233         externs: HashMap::new(),
234         crate_name: None,
235         alt_std_name: None,
236         libs: Vec::new(),
237         unstable_features: UnstableFeatures::Disallow
238     }
239 }
240
241 // The type of entry function, so
242 // users can have their own entry
243 // functions that don't start a
244 // scheduler
245 #[derive(Copy, PartialEq)]
246 pub enum EntryFnType {
247     EntryMain,
248     EntryStart,
249     EntryNone,
250 }
251
252 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
253 pub enum CrateType {
254     CrateTypeExecutable,
255     CrateTypeDylib,
256     CrateTypeRlib,
257     CrateTypeStaticlib,
258 }
259
260
261 #[derive(Clone)]
262 pub enum Passes {
263     SomePasses(Vec<String>),
264     AllPasses,
265 }
266
267 impl Passes {
268     pub fn is_empty(&self) -> bool {
269         match *self {
270             SomePasses(ref v) => v.is_empty(),
271             AllPasses => false,
272         }
273     }
274 }
275
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.
280 ///
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)),* ,) =>
291 (
292     #[derive(Clone)]
293     pub struct $struct_name { $(pub $opt: $t),* }
294
295     pub fn $defaultfn() -> $struct_name {
296         $struct_name { $($opt: $init),* }
297     }
298
299     pub fn $buildfn(matches: &getopts::Matches) -> $struct_name
300     {
301         let mut op = $defaultfn();
302         for option in matches.opt_strs($prefix) {
303             let mut iter = option.splitn(1, '=');
304             let key = iter.next().unwrap();
305             let value = iter.next();
306             let option_to_lookup = key.replace("-", "_");
307             let mut found = false;
308             for &(candidate, setter, opt_type_desc, _) in $stat {
309                 if option_to_lookup != candidate { continue }
310                 if !setter(&mut op, value) {
311                     match (value, opt_type_desc) {
312                         (Some(..), None) => {
313                             early_error(&format!("{} option `{}` takes no \
314                                                  value", $outputname, key)[])
315                         }
316                         (None, Some(type_desc)) => {
317                             early_error(&format!("{0} option `{1}` requires \
318                                                  {2} ({3} {1}=<value>)",
319                                                 $outputname, key,
320                                                 type_desc, $prefix)[])
321                         }
322                         (Some(value), Some(type_desc)) => {
323                             early_error(&format!("incorrect value `{}` for {} \
324                                                  option `{}` - {} was expected",
325                                                  value, $outputname,
326                                                  key, type_desc)[])
327                         }
328                         (None, None) => unreachable!()
329                     }
330                 }
331                 found = true;
332                 break;
333             }
334             if !found {
335                 early_error(&format!("unknown {} option: `{}`",
336                                     $outputname, key)[]);
337             }
338         }
339         return op;
340     }
341
342     pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
343     pub const $stat: &'static [(&'static str, $setter_name,
344                                      Option<&'static str>, &'static str)] =
345         &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
346
347     #[allow(non_upper_case_globals, dead_code)]
348     mod $mod_desc {
349         pub const parse_bool: Option<&'static str> = None;
350         pub const parse_opt_bool: Option<&'static str> = None;
351         pub const parse_string: Option<&'static str> = Some("a string");
352         pub const parse_opt_string: Option<&'static str> = Some("a string");
353         pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
354         pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
355         pub const parse_uint: Option<&'static str> = Some("a number");
356         pub const parse_passes: Option<&'static str> =
357             Some("a space-separated list of passes, or `all`");
358         pub const parse_opt_uint: Option<&'static str> =
359             Some("a number");
360     }
361
362     #[allow(dead_code)]
363     mod $mod_set {
364         use super::{$struct_name, Passes, SomePasses, AllPasses};
365
366         $(
367             pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
368                 $parse(&mut cg.$opt, v)
369             }
370         )*
371
372         fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
373             match v {
374                 Some(..) => false,
375                 None => { *slot = true; true }
376             }
377         }
378
379         fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
380             match v {
381                 Some(..) => false,
382                 None => { *slot = Some(true); true }
383             }
384         }
385
386         fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
387             match v {
388                 Some(s) => { *slot = Some(s.to_string()); true },
389                 None => false,
390             }
391         }
392
393         fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
394             match v {
395                 Some(s) => { *slot = s.to_string(); true },
396                 None => false,
397             }
398         }
399
400         fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
401                       -> bool {
402             match v {
403                 Some(s) => {
404                     for s in s.words() {
405                         slot.push(s.to_string());
406                     }
407                     true
408                 },
409                 None => false,
410             }
411         }
412
413         fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
414                       -> bool {
415             match v {
416                 Some(s) => {
417                     let v = s.words().map(|s| s.to_string()).collect();
418                     *slot = Some(v);
419                     true
420                 },
421                 None => false,
422             }
423         }
424
425         fn parse_uint(slot: &mut uint, v: Option<&str>) -> bool {
426             match v.and_then(|s| s.parse().ok()) {
427                 Some(i) => { *slot = i; true },
428                 None => false
429             }
430         }
431
432         fn parse_opt_uint(slot: &mut Option<uint>, v: Option<&str>) -> bool {
433             match v {
434                 Some(s) => { *slot = s.parse().ok(); slot.is_some() }
435                 None => { *slot = None; true }
436             }
437         }
438
439         fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
440             match v {
441                 Some("all") => {
442                     *slot = AllPasses;
443                     true
444                 }
445                 v => {
446                     let mut passes = vec!();
447                     if parse_list(&mut passes, v) {
448                         *slot = SomePasses(passes);
449                         true
450                     } else {
451                         false
452                     }
453                 }
454             }
455         }
456     }
457 ) }
458
459 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
460          build_codegen_options, "C", "codegen",
461          CG_OPTIONS, cg_type_desc, cgsetters,
462     ar: Option<String> = (None, parse_opt_string,
463         "tool to assemble archives with"),
464     linker: Option<String> = (None, parse_opt_string,
465         "system linker to link outputs with"),
466     link_args: Option<Vec<String>> = (None, parse_opt_list,
467         "extra arguments to pass to the linker (space separated)"),
468     lto: bool = (false, parse_bool,
469         "perform LLVM link-time optimizations"),
470     target_cpu: Option<String> = (None, parse_opt_string,
471         "select target processor (llc -mcpu=help for details)"),
472     target_feature: String = ("".to_string(), parse_string,
473         "target specific attributes (llc -mattr=help for details)"),
474     passes: Vec<String> = (Vec::new(), parse_list,
475         "a list of extra LLVM passes to run (space separated)"),
476     llvm_args: Vec<String> = (Vec::new(), parse_list,
477         "a list of arguments to pass to llvm (space separated)"),
478     save_temps: bool = (false, parse_bool,
479         "save all temporary output files during compilation"),
480     rpath: bool = (false, parse_bool,
481         "set rpath values in libs/exes"),
482     no_prepopulate_passes: bool = (false, parse_bool,
483         "don't pre-populate the pass manager with a list of passes"),
484     no_vectorize_loops: bool = (false, parse_bool,
485         "don't run the loop vectorization optimization passes"),
486     no_vectorize_slp: bool = (false, parse_bool,
487         "don't run LLVM's SLP vectorization pass"),
488     soft_float: bool = (false, parse_bool,
489         "generate software floating point library calls"),
490     prefer_dynamic: bool = (false, parse_bool,
491         "prefer dynamic linking to static linking"),
492     no_integrated_as: bool = (false, parse_bool,
493         "use an external assembler rather than LLVM's integrated one"),
494     no_redzone: Option<bool> = (None, parse_opt_bool,
495         "disable the use of the redzone"),
496     relocation_model: Option<String> = (None, parse_opt_string,
497          "choose the relocation model to use (llc -relocation-model for details)"),
498     code_model: Option<String> = (None, parse_opt_string,
499          "choose the code model to use (llc -code-model for details)"),
500     metadata: Vec<String> = (Vec::new(), parse_list,
501          "metadata to mangle symbol names with"),
502     extra_filename: String = ("".to_string(), parse_string,
503          "extra data to put in each output filename"),
504     codegen_units: uint = (1, parse_uint,
505         "divide crate into N units to optimize in parallel"),
506     remark: Passes = (SomePasses(Vec::new()), parse_passes,
507         "print remarks for these optimization passes (space separated, or \"all\")"),
508     no_stack_check: bool = (false, parse_bool,
509         "disable checks for stack exhaustion (a memory-safety hazard!)"),
510     debuginfo: Option<uint> = (None, parse_opt_uint,
511         "debug info emission level, 0 = no debug info, 1 = line tables only, \
512          2 = full debug info with variable and type information"),
513     opt_level: Option<uint> = (None, parse_opt_uint,
514         "Optimize with possible levels 0-3"),
515 }
516
517
518 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
519          build_debugging_options, "Z", "debugging",
520          DB_OPTIONS, db_type_desc, dbsetters,
521     verbose: bool = (false, parse_bool,
522         "in general, enable more debug printouts"),
523     time_passes: bool = (false, parse_bool,
524         "measure time of each rustc pass"),
525     count_llvm_insns: bool = (false, parse_bool,
526         "count where LLVM instrs originate"),
527     time_llvm_passes: bool = (false, parse_bool,
528         "measure time of each LLVM pass"),
529     trans_stats: bool = (false, parse_bool,
530         "gather trans statistics"),
531     asm_comments: bool = (false, parse_bool,
532         "generate comments into the assembly (may change behavior)"),
533     no_verify: bool = (false, parse_bool,
534         "skip LLVM verification"),
535     borrowck_stats: bool = (false, parse_bool,
536         "gather borrowck statistics"),
537     no_landing_pads: bool = (false, parse_bool,
538         "omit landing pads for unwinding"),
539     debug_llvm: bool = (false, parse_bool,
540         "enable debug output from LLVM"),
541     count_type_sizes: bool = (false, parse_bool,
542         "count the sizes of aggregate types"),
543     meta_stats: bool = (false, parse_bool,
544         "gather metadata statistics"),
545     print_link_args: bool = (false, parse_bool,
546         "Print the arguments passed to the linker"),
547     gc: bool = (false, parse_bool,
548         "Garbage collect shared data (experimental)"),
549     print_llvm_passes: bool = (false, parse_bool,
550         "Prints the llvm optimization passes being run"),
551     ast_json: bool = (false, parse_bool,
552         "Print the AST as JSON and halt"),
553     ast_json_noexpand: bool = (false, parse_bool,
554         "Print the pre-expansion AST as JSON and halt"),
555     ls: bool = (false, parse_bool,
556         "List the symbols defined by a library crate"),
557     save_analysis: bool = (false, parse_bool,
558         "Write syntax and type analysis information in addition to normal output"),
559     print_move_fragments: bool = (false, parse_bool,
560         "Print out move-fragment data for every fn"),
561     flowgraph_print_loans: bool = (false, parse_bool,
562         "Include loan analysis data in --pretty flowgraph output"),
563     flowgraph_print_moves: bool = (false, parse_bool,
564         "Include move analysis data in --pretty flowgraph output"),
565     flowgraph_print_assigns: bool = (false, parse_bool,
566         "Include assignment analysis data in --pretty flowgraph output"),
567     flowgraph_print_all: bool = (false, parse_bool,
568         "Include all dataflow analysis data in --pretty flowgraph output"),
569     print_region_graph: bool = (false, parse_bool,
570          "Prints region inference graph. \
571           Use with RUST_REGION_GRAPH=help for more info"),
572     parse_only: bool = (false, parse_bool,
573           "Parse only; do not compile, assemble, or link"),
574     no_trans: bool = (false, parse_bool,
575           "Run all passes except translation; no output"),
576     no_analysis: bool = (false, parse_bool,
577           "Parse and expand the source, but run no analysis"),
578     extra_plugins: Vec<String> = (Vec::new(), parse_list,
579         "load extra plugins"),
580     unstable_options: bool = (false, parse_bool,
581           "Adds unstable command line options to rustc interface"),
582     print_enum_sizes: bool = (false, parse_bool,
583           "Print the size of enums and their variants"),
584 }
585
586 pub fn default_lib_output() -> CrateType {
587     CrateTypeRlib
588 }
589
590 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
591     use syntax::parse::token::intern_and_get_ident as intern;
592
593     let end = &sess.target.target.target_endian[];
594     let arch = &sess.target.target.arch[];
595     let wordsz = &sess.target.target.target_pointer_width[];
596     let os = &sess.target.target.target_os[];
597
598     let fam = match sess.target.target.options.is_like_windows {
599         true  => InternedString::new("windows"),
600         false => InternedString::new("unix")
601     };
602
603     let mk = attr::mk_name_value_item_str;
604     return vec!(// Target bindings.
605          attr::mk_word_item(fam.clone()),
606          mk(InternedString::new("target_os"), intern(os)),
607          mk(InternedString::new("target_family"), fam),
608          mk(InternedString::new("target_arch"), intern(arch)),
609          mk(InternedString::new("target_endian"), intern(end)),
610          mk(InternedString::new("target_pointer_width"),
611             intern(wordsz))
612     );
613 }
614
615 pub fn append_configuration(cfg: &mut ast::CrateConfig,
616                             name: InternedString) {
617     if !cfg.iter().any(|mi| mi.name() == name) {
618         cfg.push(attr::mk_word_item(name))
619     }
620 }
621
622 pub fn build_configuration(sess: &Session) -> ast::CrateConfig {
623     // Combine the configuration requested by the session (command line) with
624     // some default and generated configuration items
625     let default_cfg = default_configuration(sess);
626     let mut user_cfg = sess.opts.cfg.clone();
627     // If the user wants a test runner, then add the test cfg
628     if sess.opts.test {
629         append_configuration(&mut user_cfg, InternedString::new("test"))
630     }
631     let mut v = user_cfg.into_iter().collect::<Vec<_>>();
632     v.push_all(&default_cfg[..]);
633     v
634 }
635
636 pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config {
637     let target = match Target::search(&opts.target_triple[]) {
638         Ok(t) => t,
639         Err(e) => {
640             sp.handler().fatal(&format!("Error loading target specification: {}", e));
641     }
642     };
643
644     let (int_type, uint_type) = match &target.target_pointer_width[] {
645         "32" => (ast::TyI32, ast::TyU32),
646         "64" => (ast::TyI64, ast::TyU64),
647         w    => sp.handler().fatal(&format!("target specification was invalid: unrecognized \
648                                              target-pointer-width {}", w)[])
649     };
650
651     Config {
652         target: target,
653         int_type: int_type,
654         uint_type: uint_type,
655     }
656 }
657
658 /// Returns the "short" subset of the stable rustc command line options.
659 pub fn short_optgroups() -> Vec<getopts::OptGroup> {
660     rustc_short_optgroups().into_iter()
661         .filter(|g|g.is_stable())
662         .map(|g|g.opt_group)
663         .collect()
664 }
665
666 /// Returns all of the stable rustc command line options.
667 pub fn optgroups() -> Vec<getopts::OptGroup> {
668     rustc_optgroups().into_iter()
669         .filter(|g|g.is_stable())
670         .map(|g|g.opt_group)
671         .collect()
672 }
673
674 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
675 pub enum OptionStability { Stable, Unstable }
676
677 #[derive(Clone, PartialEq, Eq)]
678 pub struct RustcOptGroup {
679     pub opt_group: getopts::OptGroup,
680     pub stability: OptionStability,
681 }
682
683 impl RustcOptGroup {
684     pub fn is_stable(&self) -> bool {
685         self.stability == OptionStability::Stable
686     }
687
688     fn stable(g: getopts::OptGroup) -> RustcOptGroup {
689         RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
690     }
691
692     fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
693         RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
694     }
695 }
696
697 // The `opt` local module holds wrappers around the `getopts` API that
698 // adds extra rustc-specific metadata to each option; such metadata
699 // is exposed by .  The public
700 // functions below ending with `_u` are the functions that return
701 // *unstable* options, i.e. options that are only enabled when the
702 // user also passes the `-Z unstable-options` debugging flag.
703 mod opt {
704     // The `fn opt_u` etc below are written so that we can use them
705     // in the future; do not warn about them not being used right now.
706     #![allow(dead_code)]
707
708     use getopts;
709     use super::RustcOptGroup;
710
711     type R = RustcOptGroup;
712     type S<'a> = &'a str;
713
714     fn stable(g: getopts::OptGroup) -> R { RustcOptGroup::stable(g) }
715     fn unstable(g: getopts::OptGroup) -> R { RustcOptGroup::unstable(g) }
716
717     // FIXME (pnkfelix): We default to stable since the current set of
718     // options is defacto stable.  However, it would be good to revise the
719     // code so that a stable option is the thing that takes extra effort
720     // to encode.
721
722     pub fn     opt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optopt(a, b, c, d)) }
723     pub fn   multi(a: S, b: S, c: S, d: S) -> R { stable(getopts::optmulti(a, b, c, d)) }
724     pub fn    flag(a: S, b: S, c: S)       -> R { stable(getopts::optflag(a, b, c)) }
725     pub fn flagopt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optflagopt(a, b, c, d)) }
726
727     pub fn     opt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optopt(a, b, c, d)) }
728     pub fn   multi_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optmulti(a, b, c, d)) }
729     pub fn    flag_u(a: S, b: S, c: S)       -> R { unstable(getopts::optflag(a, b, c)) }
730     pub fn flagopt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optflagopt(a, b, c, d)) }
731 }
732
733 /// Returns the "short" subset of the rustc command line options,
734 /// including metadata for each option, such as whether the option is
735 /// part of the stable long-term interface for rustc.
736 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
737     vec![
738         opt::flag("h", "help", "Display this message"),
739         opt::multi("", "cfg", "Configure the compilation environment", "SPEC"),
740         opt::multi("L", "",   "Add a directory to the library search path",
741                    "[KIND=]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",
750                "NAME"),
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 \
755                                print on stdout",
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 \
761                                 in <dir>", "DIR"),
762         opt::opt("", "explain", "Provide a detailed explanation of an error \
763                                message", "OPT"),
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/
768                               for details)",
769                "TRIPLE"),
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"),
777     ]
778 }
779
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();
785     opts.push_all(&[
786         opt::multi("", "extern", "Specify where an external rust library is \
787                                 located",
788                  "NAME=PATH"),
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"),
795
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).",
802                  "TYPE"),
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 {}`).",
808                      "TYPE"),
809         opt::opt_u("", "show-span", "Show spans for compiler debugging", "expr|pat|ty"),
810     ]);
811     opts
812 }
813
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(),
818                                           s.to_string(),
819                                           Vec::new(),
820                                           &parse::new_parse_sess())
821     }).collect::<ast::CrateConfig>()
822 }
823
824 pub fn build_session_options(matches: &getopts::Matches) -> Options {
825     let unparsed_crate_types = matches.opt_strs("crate-type");
826     let crate_types = parse_crate_types_from_list(unparsed_crate_types)
827         .unwrap_or_else(|e| early_error(&e[..]));
828
829     let mut lint_opts = vec!();
830     let mut describe_lints = false;
831
832     for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
833         for lint_name in matches.opt_strs(level.as_str()) {
834             if lint_name == "help" {
835                 describe_lints = true;
836             } else {
837                 lint_opts.push((lint_name.replace("-", "_"), level));
838             }
839         }
840     }
841
842     let debugging_opts = build_debugging_options(matches);
843
844     let parse_only = debugging_opts.parse_only;
845     let no_trans = debugging_opts.no_trans;
846     let no_analysis = debugging_opts.no_analysis;
847
848     if debugging_opts.debug_llvm {
849         unsafe { llvm::LLVMSetDebug(1); }
850     }
851
852     let mut output_types = Vec::new();
853     if !debugging_opts.parse_only && !no_trans {
854         let unparsed_output_types = matches.opt_strs("emit");
855         for unparsed_output_type in &unparsed_output_types {
856             for part in unparsed_output_type.split(',') {
857                 let output_type = match part {
858                     "asm" => OutputTypeAssembly,
859                     "llvm-ir" => OutputTypeLlvmAssembly,
860                     "llvm-bc" => OutputTypeBitcode,
861                     "obj" => OutputTypeObject,
862                     "link" => OutputTypeExe,
863                     "dep-info" => OutputTypeDepInfo,
864                     _ => {
865                         early_error(&format!("unknown emission type: `{}`",
866                                             part)[])
867                     }
868                 };
869                 output_types.push(output_type)
870             }
871         }
872     };
873     output_types.sort();
874     output_types.dedup();
875     if output_types.len() == 0 {
876         output_types.push(OutputTypeExe);
877     }
878
879     let cg = build_codegen_options(matches);
880
881     let sysroot_opt = matches.opt_str("sysroot").map(|m| Path::new(m));
882     let target = matches.opt_str("target").unwrap_or(
883         host_triple().to_string());
884     let opt_level = {
885         if matches.opt_present("O") {
886             if cg.opt_level.is_some() {
887                 early_error("-O and -C opt-level both provided");
888             }
889             Default
890         } else {
891             match cg.opt_level {
892                 None => No,
893                 Some(0) => No,
894                 Some(1) => Less,
895                 Some(2) => Default,
896                 Some(3) => Aggressive,
897                 Some(arg) => {
898                     early_error(&format!("optimization level needs to be \
899                                           between 0-3 (instead was `{}`)",
900                                          arg));
901                 }
902             }
903         }
904     };
905     let gc = debugging_opts.gc;
906     let debuginfo = if matches.opt_present("g") {
907         if cg.debuginfo.is_some() {
908             early_error("-g and -C debuginfo both provided");
909         }
910         FullDebugInfo
911     } else {
912         match cg.debuginfo {
913             None | Some(0) => NoDebugInfo,
914             Some(1) => LimitedDebugInfo,
915             Some(2) => FullDebugInfo,
916             Some(arg) => {
917                 early_error(&format!("debug info level needs to be between \
918                                       0-2 (instead was `{}`)",
919                                      arg));
920             }
921         }
922     };
923
924     let mut search_paths = SearchPaths::new();
925     for s in &matches.opt_strs("L") {
926         search_paths.add_path(&s[..]);
927     }
928
929     let libs = matches.opt_strs("l").into_iter().map(|s| {
930         let mut parts = s.splitn(1, '=');
931         let kind = parts.next().unwrap();
932         if let Some(name) = parts.next() {
933             let kind = match kind {
934                 "dylib" => cstore::NativeUnknown,
935                 "framework" => cstore::NativeFramework,
936                 "static" => cstore::NativeStatic,
937                 s => {
938                     early_error(&format!("unknown library kind `{}`, expected \
939                                           one of dylib, framework, or static",
940                                          s));
941                 }
942             };
943             return (name.to_string(), kind)
944         }
945
946         // FIXME(acrichto) remove this once crates have stopped using it, this
947         //                 is deprecated behavior now.
948         let mut parts = s.rsplitn(1, ':');
949         let kind = parts.next().unwrap();
950         let (name, kind) = match (parts.next(), kind) {
951             (None, name) |
952             (Some(name), "dylib") => (name, cstore::NativeUnknown),
953             (Some(name), "framework") => (name, cstore::NativeFramework),
954             (Some(name), "static") => (name, cstore::NativeStatic),
955             (_, s) => {
956                 early_error(&format!("unknown library kind `{}`, expected \
957                                      one of dylib, framework, or static",
958                                     s)[]);
959             }
960         };
961         (name.to_string(), kind)
962     }).collect();
963
964     let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
965     let test = matches.opt_present("test");
966     let write_dependency_info = (output_types.contains(&OutputTypeDepInfo), None);
967
968     let prints = matches.opt_strs("print").into_iter().map(|s| {
969         match &*s {
970             "crate-name" => PrintRequest::CrateName,
971             "file-names" => PrintRequest::FileNames,
972             "sysroot" => PrintRequest::Sysroot,
973             req => {
974                 early_error(&format!("unknown print request `{}`", req))
975             }
976         }
977     }).collect::<Vec<_>>();
978
979     if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
980         early_warn("-C remark will not show source locations without \
981                     --debuginfo");
982     }
983
984     let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
985         Some("auto")   => Auto,
986         Some("always") => Always,
987         Some("never")  => Never,
988
989         None => Auto,
990
991         Some(arg) => {
992             early_error(&format!("argument for --color must be auto, always \
993                                  or never (instead was `{}`)",
994                                 arg)[])
995         }
996     };
997
998     let mut externs = HashMap::new();
999     for arg in &matches.opt_strs("extern") {
1000         let mut parts = arg.splitn(1, '=');
1001         let name = match parts.next() {
1002             Some(s) => s,
1003             None => early_error("--extern value must not be empty"),
1004         };
1005         let location = match parts.next() {
1006             Some(s) => s,
1007             None => early_error("--extern value must be of the format `foo=bar`"),
1008         };
1009
1010         match externs.entry(name.to_string()) {
1011             Vacant(entry) => { entry.insert(vec![location.to_string()]); },
1012             Occupied(mut entry) => { entry.get_mut().push(location.to_string()); },
1013         }
1014     }
1015
1016     let crate_name = matches.opt_str("crate-name");
1017
1018     Options {
1019         crate_types: crate_types,
1020         gc: gc,
1021         optimize: opt_level,
1022         debuginfo: debuginfo,
1023         lint_opts: lint_opts,
1024         describe_lints: describe_lints,
1025         output_types: output_types,
1026         search_paths: search_paths,
1027         maybe_sysroot: sysroot_opt,
1028         target_triple: target,
1029         cfg: cfg,
1030         test: test,
1031         parse_only: parse_only,
1032         no_trans: no_trans,
1033         no_analysis: no_analysis,
1034         debugging_opts: debugging_opts,
1035         write_dependency_info: write_dependency_info,
1036         prints: prints,
1037         cg: cg,
1038         color: color,
1039         show_span: None,
1040         externs: externs,
1041         crate_name: crate_name,
1042         alt_std_name: None,
1043         libs: libs,
1044         unstable_features: get_unstable_features_setting(),
1045     }
1046 }
1047
1048 pub fn get_unstable_features_setting() -> UnstableFeatures {
1049     // Whether this is a feature-staged build, i.e. on the beta or stable channel
1050     let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
1051     // The secret key needed to get through the rustc build itself by
1052     // subverting the unstable features lints
1053     let bootstrap_secret_key = option_env!("CFG_BOOTSTRAP_KEY");
1054     // The matching key to the above, only known by the build system
1055     let bootstrap_provided_key = env::var("RUSTC_BOOTSTRAP_KEY").ok();
1056     match (disable_unstable_features, bootstrap_secret_key, bootstrap_provided_key) {
1057         (_, Some(ref s), Some(ref p)) if s == p => UnstableFeatures::Cheat,
1058         (true, _, _) => UnstableFeatures::Disallow,
1059         (false, _, _) => UnstableFeatures::Default
1060     }
1061 }
1062
1063 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
1064
1065     let mut crate_types: Vec<CrateType> = Vec::new();
1066     for unparsed_crate_type in &list_list {
1067         for part in unparsed_crate_type.split(',') {
1068             let new_part = match part {
1069                 "lib"       => default_lib_output(),
1070                 "rlib"      => CrateTypeRlib,
1071                 "staticlib" => CrateTypeStaticlib,
1072                 "dylib"     => CrateTypeDylib,
1073                 "bin"       => CrateTypeExecutable,
1074                 _ => {
1075                     return Err(format!("unknown crate type: `{}`",
1076                                        part));
1077                 }
1078             };
1079             if !crate_types.contains(&new_part) {
1080                 crate_types.push(new_part)
1081             }
1082         }
1083     }
1084
1085     return Ok(crate_types);
1086 }
1087
1088 impl fmt::Display for CrateType {
1089     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1090         match *self {
1091             CrateTypeExecutable => "bin".fmt(f),
1092             CrateTypeDylib => "dylib".fmt(f),
1093             CrateTypeRlib => "rlib".fmt(f),
1094             CrateTypeStaticlib => "staticlib".fmt(f)
1095         }
1096     }
1097 }
1098
1099 #[cfg(test)]
1100 mod test {
1101
1102     use session::config::{build_configuration, optgroups, build_session_options};
1103     use session::build_session;
1104
1105     use getopts::getopts;
1106     use syntax::attr;
1107     use syntax::attr::AttrMetaMethods;
1108     use syntax::diagnostics;
1109
1110     // When the user supplies --test we should implicitly supply --cfg test
1111     #[test]
1112     fn test_switch_implies_cfg_test() {
1113         let matches =
1114             &match getopts(&["--test".to_string()], &optgroups()[]) {
1115               Ok(m) => m,
1116               Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
1117             };
1118         let registry = diagnostics::registry::Registry::new(&[]);
1119         let sessopts = build_session_options(matches);
1120         let sess = build_session(sessopts, None, registry);
1121         let cfg = build_configuration(&sess);
1122         assert!((attr::contains_name(&cfg[..], "test")));
1123     }
1124
1125     // When the user supplies --test and --cfg test, don't implicitly add
1126     // another --cfg test
1127     #[test]
1128     fn test_switch_implies_cfg_test_unless_cfg_test() {
1129         let matches =
1130             &match getopts(&["--test".to_string(), "--cfg=test".to_string()],
1131                            &optgroups()[]) {
1132               Ok(m) => m,
1133               Err(f) => {
1134                 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
1135               }
1136             };
1137         let registry = diagnostics::registry::Registry::new(&[]);
1138         let sessopts = build_session_options(matches);
1139         let sess = build_session(sessopts, None, registry);
1140         let cfg = build_configuration(&sess);
1141         let mut test_items = cfg.iter().filter(|m| m.name() == "test");
1142         assert!(test_items.next().is_some());
1143         assert!(test_items.next().is_none());
1144     }
1145
1146     #[test]
1147     fn test_can_print_warnings() {
1148         {
1149             let matches = getopts(&[
1150                 "-Awarnings".to_string()
1151             ], &optgroups()[]).unwrap();
1152             let registry = diagnostics::registry::Registry::new(&[]);
1153             let sessopts = build_session_options(&matches);
1154             let sess = build_session(sessopts, None, registry);
1155             assert!(!sess.can_print_warnings);
1156         }
1157
1158         {
1159             let matches = getopts(&[
1160                 "-Awarnings".to_string(),
1161                 "-Dwarnings".to_string()
1162             ], &optgroups()[]).unwrap();
1163             let registry = diagnostics::registry::Registry::new(&[]);
1164             let sessopts = build_session_options(&matches);
1165             let sess = build_session(sessopts, None, registry);
1166             assert!(sess.can_print_warnings);
1167         }
1168
1169         {
1170             let matches = getopts(&[
1171                 "-Adead_code".to_string()
1172             ], &optgroups()[]).unwrap();
1173             let registry = diagnostics::registry::Registry::new(&[]);
1174             let sessopts = build_session_options(&matches);
1175             let sess = build_session(sessopts, None, registry);
1176             assert!(sess.can_print_warnings);
1177         }
1178     }
1179 }