]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/config.rs
librustc::session : Make DebuggingOpts use the options! macro
[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 std::collections::HashMap;
37 use std::collections::hash_map::Entry::{Occupied, Vacant};
38 use getopts;
39 use std::fmt;
40
41 use llvm;
42
43 pub struct Config {
44     pub target: Target,
45     pub int_type: IntTy,
46     pub uint_type: UintTy,
47 }
48
49 #[derive(Clone, Copy, PartialEq)]
50 pub enum OptLevel {
51     No, // -O0
52     Less, // -O1
53     Default, // -O2
54     Aggressive // -O3
55 }
56
57 #[derive(Clone, Copy, PartialEq)]
58 pub enum DebugInfoLevel {
59     NoDebugInfo,
60     LimitedDebugInfo,
61     FullDebugInfo,
62 }
63
64 #[derive(Clone, Copy, PartialEq, PartialOrd, Ord, Eq)]
65 pub enum OutputType {
66     OutputTypeBitcode,
67     OutputTypeAssembly,
68     OutputTypeLlvmAssembly,
69     OutputTypeObject,
70     OutputTypeExe,
71     OutputTypeDepInfo,
72 }
73
74 #[derive(Clone)]
75 pub struct Options {
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>,
79
80     pub gc: bool,
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
88     // this.
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,
98     pub test: bool,
99     pub parse_only: bool,
100     pub no_trans: bool,
101     pub no_analysis: bool,
102     pub debugging_opts: DebuggingOptions,
103     /// Whether to write dependency files. It's (enabled, optional filename).
104     pub write_dependency_info: (bool, Option<Path>),
105     pub prints: Vec<PrintRequest>,
106     pub cg: CodegenOptions,
107     pub color: ColorConfig,
108     pub show_span: Option<String>,
109     pub externs: HashMap<String, Vec<String>>,
110     pub crate_name: Option<String>,
111     /// An optional name to use as the crate for std during std injection,
112     /// written `extern crate std = "name"`. Default to "std". Used by
113     /// out-of-tree drivers.
114     pub alt_std_name: Option<String>,
115     /// Indicates how the compiler should treat unstable features
116     pub unstable_features: UnstableFeatures
117 }
118
119 #[derive(Clone, Copy)]
120 pub enum UnstableFeatures {
121     /// Hard errors for unstable features are active, as on
122     /// beta/stable channels.
123     Disallow,
124     /// Use the default lint levels
125     Default,
126     /// Errors are bypassed for bootstrapping. This is required any time
127     /// during the build that feature-related lints are set to warn or above
128     /// because the build turns on warnings-as-errors and uses lots of unstable
129     /// features. As a result, this this is always required for building Rust
130     /// itself.
131     Cheat
132 }
133
134 #[derive(Clone, PartialEq, Eq)]
135 #[allow(missing_copy_implementations)]
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)]
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     #[allow(missing_copy_implementations)]
294     pub struct $struct_name { $(pub $opt: $t),* }
295
296     pub fn $defaultfn() -> $struct_name {
297         $struct_name { $($opt: $init),* }
298     }
299
300     pub fn $buildfn(matches: &getopts::Matches) -> $struct_name
301     {
302         let mut op = $defaultfn();
303         for option in matches.opt_strs($prefix).into_iter() {
304             let mut iter = option.splitn(1, '=');
305             let key = iter.next().unwrap();
306             let value = iter.next();
307             let option_to_lookup = key.replace("-", "_");
308             let mut found = false;
309             for &(candidate, setter, opt_type_desc, _) in $stat.iter() {
310                 if option_to_lookup != candidate { continue }
311                 if !setter(&mut op, value) {
312                     match (value, opt_type_desc) {
313                         (Some(..), None) => {
314                             early_error(format!("{} option `{}` takes no \
315                                                  value", $outputname, key)[])
316                         }
317                         (None, Some(type_desc)) => {
318                             early_error(format!("{0} option `{1}` requires \
319                                                  {2} ({3} {1}=<value>)",
320                                                 $outputname, key, type_desc, $prefix)[])
321                         }
322                         (Some(value), Some(type_desc)) => {
323                             early_error(format!("incorrect value `{}` for {} \
324                                                  option `{}` - {} was expected",
325                                                  value, $outputname, key, type_desc)[])
326                         }
327                         (None, None) => unreachable!()
328                     }
329                 }
330                 found = true;
331                 break;
332             }
333             if !found {
334                 early_error(format!("unknown codegen option: `{}`",
335                                     key)[]);
336             }
337         }
338         return op;
339     }
340
341     pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
342     pub const $stat: &'static [(&'static str, $setter_name,
343                                      Option<&'static str>, &'static str)] =
344         &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
345
346     #[allow(non_upper_case_globals, dead_code)]
347     mod $mod_desc {
348         pub const parse_bool: Option<&'static str> = None;
349         pub const parse_opt_bool: Option<&'static str> = None;
350         pub const parse_string: Option<&'static str> = Some("a string");
351         pub const parse_opt_string: Option<&'static str> = Some("a string");
352         pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
353         pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
354         pub const parse_uint: Option<&'static str> = Some("a number");
355         pub const parse_passes: Option<&'static str> =
356             Some("a space-separated list of passes, or `all`");
357         pub const parse_opt_uint: Option<&'static str> =
358             Some("a number");
359     }
360
361     #[allow(dead_code)]
362     mod $mod_set {
363         use super::{$struct_name, Passes, SomePasses, AllPasses};
364
365         $(
366             pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
367                 $parse(&mut cg.$opt, v)
368             }
369         )*
370
371         fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
372             match v {
373                 Some(..) => false,
374                 None => { *slot = true; true }
375             }
376         }
377
378         fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
379             match v {
380                 Some(..) => false,
381                 None => { *slot = Some(true); true }
382             }
383         }
384
385         fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
386             match v {
387                 Some(s) => { *slot = Some(s.to_string()); true },
388                 None => false,
389             }
390         }
391
392         fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
393             match v {
394                 Some(s) => { *slot = s.to_string(); true },
395                 None => false,
396             }
397         }
398
399         fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
400                       -> bool {
401             match v {
402                 Some(s) => {
403                     for s in s.words() {
404                         slot.push(s.to_string());
405                     }
406                     true
407                 },
408                 None => false,
409             }
410         }
411
412         fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
413                       -> bool {
414             match v {
415                 Some(s) => {
416                     let v = s.words().map(|s| s.to_string()).collect();
417                     *slot = Some(v);
418                     true
419                 },
420                 None => false,
421             }
422         }
423
424         fn parse_uint(slot: &mut uint, v: Option<&str>) -> bool {
425             match v.and_then(|s| s.parse()) {
426                 Some(i) => { *slot = i; true },
427                 None => false
428             }
429         }
430
431         fn parse_opt_uint(slot: &mut Option<uint>, v: Option<&str>) -> bool {
432             match v {
433                 Some(s) => { *slot = s.parse(); slot.is_some() }
434                 None => { *slot = None; true }
435             }
436         }
437
438         fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
439             match v {
440                 Some("all") => {
441                     *slot = AllPasses;
442                     true
443                 }
444                 v => {
445                     let mut passes = vec!();
446                     if parse_list(&mut passes, v) {
447                         *slot = SomePasses(passes);
448                         true
449                     } else {
450                         false
451                     }
452                 }
453             }
454         }
455     }
456 ) }
457
458 options! {CodegenOptions, CodegenSetter, basic_codegen_options,
459          build_codegen_options, "C", "codegen",
460          CG_OPTIONS, cg_type_desc, cgsetters,
461     ar: Option<String> = (None, parse_opt_string,
462         "tool to assemble archives with"),
463     linker: Option<String> = (None, parse_opt_string,
464         "system linker to link outputs with"),
465     link_args: Option<Vec<String>> = (None, parse_opt_list,
466         "extra arguments to pass to the linker (space separated)"),
467     lto: bool = (false, parse_bool,
468         "perform LLVM link-time optimizations"),
469     target_cpu: Option<String> = (None, parse_opt_string,
470         "select target processor (llc -mcpu=help for details)"),
471     target_feature: String = ("".to_string(), parse_string,
472         "target specific attributes (llc -mattr=help for details)"),
473     passes: Vec<String> = (Vec::new(), parse_list,
474         "a list of extra LLVM passes to run (space separated)"),
475     llvm_args: Vec<String> = (Vec::new(), parse_list,
476         "a list of arguments to pass to llvm (space separated)"),
477     save_temps: bool = (false, parse_bool,
478         "save all temporary output files during compilation"),
479     rpath: bool = (false, parse_bool,
480         "set rpath values in libs/exes"),
481     no_prepopulate_passes: bool = (false, parse_bool,
482         "don't pre-populate the pass manager with a list of passes"),
483     no_vectorize_loops: bool = (false, parse_bool,
484         "don't run the loop vectorization optimization passes"),
485     no_vectorize_slp: bool = (false, parse_bool,
486         "don't run LLVM's SLP vectorization pass"),
487     soft_float: bool = (false, parse_bool,
488         "generate software floating point library calls"),
489     prefer_dynamic: bool = (false, parse_bool,
490         "prefer dynamic linking to static linking"),
491     no_integrated_as: bool = (false, parse_bool,
492         "use an external assembler rather than LLVM's integrated one"),
493     no_redzone: Option<bool> = (None, parse_opt_bool,
494         "disable the use of the redzone"),
495     relocation_model: Option<String> = (None, parse_opt_string,
496          "choose the relocation model to use (llc -relocation-model for details)"),
497     code_model: Option<String> = (None, parse_opt_string,
498          "choose the code model to use (llc -code-model for details)"),
499     metadata: Vec<String> = (Vec::new(), parse_list,
500          "metadata to mangle symbol names with"),
501     extra_filename: String = ("".to_string(), parse_string,
502          "extra data to put in each output filename"),
503     codegen_units: uint = (1, parse_uint,
504         "divide crate into N units to optimize in parallel"),
505     remark: Passes = (SomePasses(Vec::new()), parse_passes,
506         "print remarks for these optimization passes (space separated, or \"all\")"),
507     no_stack_check: bool = (false, parse_bool,
508         "disable checks for stack exhaustion (a memory-safety hazard!)"),
509     debuginfo: Option<uint> = (None, parse_opt_uint,
510         "debug info emission level, 0 = no debug info, 1 = line tables only, \
511          2 = full debug info with variable and type information"),
512     opt_level: Option<uint> = (None, parse_opt_uint,
513         "Optimize with possible levels 0-3"),
514 }
515
516
517 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
518          build_debugging_options, "Z", "debugging",
519          DB_OPTIONS, db_type_desc, dbsetters,
520     verbose: bool = (false, parse_bool,
521         "in general, enable more debug printouts"),
522     time_passes: bool = (false, parse_bool,
523         "measure time of each rustc pass"),
524     count_llvm_insns: bool = (false, parse_bool,
525         "count where LLVM instrs originate"),
526     time_llvm_passes: bool = (false, parse_bool,
527         "measure time of each LLVM pass"),
528     trans_stats: bool = (false, parse_bool,
529         "gather trans statistics"),
530     asm_comments: bool = (false, parse_bool,
531         "generate comments into the assembly (may change behavior)"),
532     no_verify: bool = (false, parse_bool,
533         "skip LLVM verification"),
534     borrowck_stats: bool = (false, parse_bool,
535         "gather borrowck statistics"),
536     no_landing_pads: bool = (false, parse_bool,
537         "omit landing pads for unwinding"),
538     debug_llvm: bool = (false, parse_bool,
539         "enable debug output from LLVM"),
540     count_type_sizes: bool = (false, parse_bool,
541         "count the sizes of aggregate types"),
542     meta_stats: bool = (false, parse_bool,
543         "gather metadata statistics"),
544     print_link_args: bool = (false, parse_bool,
545         "Print the arguments passed to the linker"),
546     gc: bool = (false, parse_bool,
547         "Garbage collect shared data (experimental)"),
548     print_llvm_passes: bool = (false, parse_bool,
549         "Prints the llvm optimization passes being run"),
550     ast_json: bool = (false, parse_bool,
551         "Print the AST as JSON and halt"),
552     ast_json_noexpand: bool = (false, parse_bool,
553         "Print the pre-expansion AST as JSON and halt"),
554     ls: bool = (false, parse_bool,
555         "List the symbols defined by a library crate"),
556     save_analysis: bool = (false, parse_bool,
557         "Write syntax and type analysis information in addition to normal output"),
558     print_move_fragments: bool = (false, parse_bool,
559         "Print out move-fragment data for every fn"),
560     flowgraph_print_loans: bool = (false, parse_bool,
561         "Include loan analysis data in --pretty flowgraph output"),
562     flowgraph_print_moves: bool = (false, parse_bool,
563         "Include move analysis data in --pretty flowgraph output"),
564     flowgraph_print_assigns: bool = (false, parse_bool,
565         "Include assignment analysis data in --pretty flowgraph output"),
566     flowgraph_print_all: bool = (false, parse_bool,
567         "Include all dataflow analysis data in --pretty flowgraph output"),
568     print_region_graph: bool = (false, parse_bool,
569          "Prints region inference graph. \
570           Use with RUST_REGION_GRAPH=help for more info"),
571     parse_only: bool = (false, parse_bool,
572           "Parse only; do not compile, assemble, or link"),
573     no_trans: bool = (false, parse_bool,
574           "Run all passes except translation; no output"),
575     no_analysis: bool = (false, parse_bool,
576           "Parse and expand the source, but run no analysis"),
577     unstable_options: bool = (false, parse_bool,
578           "Adds unstable command line options to rustc interface"),
579     print_enum_sizes: bool = (false, parse_bool,
580           "Print the size of enums and their variants"),
581 }
582
583 pub fn default_lib_output() -> CrateType {
584     CrateTypeRlib
585 }
586
587 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
588     use syntax::parse::token::intern_and_get_ident as intern;
589
590     let end = &sess.target.target.target_endian[];
591     let arch = &sess.target.target.arch[];
592     let wordsz = &sess.target.target.target_pointer_width[];
593     let os = &sess.target.target.target_os[];
594
595     let fam = match sess.target.target.options.is_like_windows {
596         true  => InternedString::new("windows"),
597         false => InternedString::new("unix")
598     };
599
600     let mk = attr::mk_name_value_item_str;
601     return vec!(// Target bindings.
602          attr::mk_word_item(fam.clone()),
603          mk(InternedString::new("target_os"), intern(os)),
604          mk(InternedString::new("target_family"), fam),
605          mk(InternedString::new("target_arch"), intern(arch)),
606          mk(InternedString::new("target_endian"), intern(end)),
607          mk(InternedString::new("target_pointer_width"),
608             intern(wordsz))
609     );
610 }
611
612 pub fn append_configuration(cfg: &mut ast::CrateConfig,
613                             name: InternedString) {
614     if !cfg.iter().any(|mi| mi.name() == name) {
615         cfg.push(attr::mk_word_item(name))
616     }
617 }
618
619 pub fn build_configuration(sess: &Session) -> ast::CrateConfig {
620     // Combine the configuration requested by the session (command line) with
621     // some default and generated configuration items
622     let default_cfg = default_configuration(sess);
623     let mut user_cfg = sess.opts.cfg.clone();
624     // If the user wants a test runner, then add the test cfg
625     if sess.opts.test {
626         append_configuration(&mut user_cfg, InternedString::new("test"))
627     }
628     let mut v = user_cfg.into_iter().collect::<Vec<_>>();
629     v.push_all(&default_cfg[]);
630     v
631 }
632
633 pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config {
634     let target = match Target::search(&opts.target_triple[]) {
635         Ok(t) => t,
636         Err(e) => {
637             sp.handler().fatal((format!("Error loading target specification: {}", e)).as_slice());
638     }
639     };
640
641     let (int_type, uint_type) = match &target.target_pointer_width[] {
642         "32" => (ast::TyI32, ast::TyU32),
643         "64" => (ast::TyI64, ast::TyU64),
644         w    => sp.handler().fatal(&format!("target specification was invalid: unrecognized \
645                                             target-word-size {}", w)[])
646     };
647
648     Config {
649         target: target,
650         int_type: int_type,
651         uint_type: uint_type,
652     }
653 }
654
655 /// Returns the "short" subset of the stable rustc command line options.
656 pub fn short_optgroups() -> Vec<getopts::OptGroup> {
657     rustc_short_optgroups().into_iter()
658         .filter(|g|g.is_stable())
659         .map(|g|g.opt_group)
660         .collect()
661 }
662
663 /// Returns all of the stable rustc command line options.
664 pub fn optgroups() -> Vec<getopts::OptGroup> {
665     rustc_optgroups().into_iter()
666         .filter(|g|g.is_stable())
667         .map(|g|g.opt_group)
668         .collect()
669 }
670
671 #[derive(Copy, Clone, PartialEq, Eq, Show)]
672 pub enum OptionStability { Stable, Unstable }
673
674 #[derive(Clone, PartialEq, Eq)]
675 pub struct RustcOptGroup {
676     pub opt_group: getopts::OptGroup,
677     pub stability: OptionStability,
678 }
679
680 impl RustcOptGroup {
681     pub fn is_stable(&self) -> bool {
682         self.stability == OptionStability::Stable
683     }
684
685     fn stable(g: getopts::OptGroup) -> RustcOptGroup {
686         RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
687     }
688
689     fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
690         RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
691     }
692 }
693
694 // The `opt` local module holds wrappers around the `getopts` API that
695 // adds extra rustc-specific metadata to each option; such metadata
696 // is exposed by .  The public
697 // functions below ending with `_u` are the functions that return
698 // *unstable* options, i.e. options that are only enabled when the
699 // user also passes the `-Z unstable-options` debugging flag.
700 mod opt {
701     // The `fn opt_u` etc below are written so that we can use them
702     // in the future; do not warn about them not being used right now.
703     #![allow(dead_code)]
704
705     use getopts;
706     use super::RustcOptGroup;
707
708     type R = RustcOptGroup;
709     type S<'a> = &'a str;
710
711     fn stable(g: getopts::OptGroup) -> R { RustcOptGroup::stable(g) }
712     fn unstable(g: getopts::OptGroup) -> R { RustcOptGroup::unstable(g) }
713
714     // FIXME (pnkfelix): We default to stable since the current set of
715     // options is defacto stable.  However, it would be good to revise the
716     // code so that a stable option is the thing that takes extra effort
717     // to encode.
718
719     pub fn     opt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optopt(a, b, c, d)) }
720     pub fn   multi(a: S, b: S, c: S, d: S) -> R { stable(getopts::optmulti(a, b, c, d)) }
721     pub fn    flag(a: S, b: S, c: S)       -> R { stable(getopts::optflag(a, b, c)) }
722     pub fn flagopt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optflagopt(a, b, c, d)) }
723
724     pub fn     opt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optopt(a, b, c, d)) }
725     pub fn   multi_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optmulti(a, b, c, d)) }
726     pub fn    flag_u(a: S, b: S, c: S)       -> R { unstable(getopts::optflag(a, b, c)) }
727     pub fn flagopt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optflagopt(a, b, c, d)) }
728 }
729
730 /// Returns the "short" subset of the rustc command line options,
731 /// including metadata for each option, such as whether the option is
732 /// part of the stable long-term interface for rustc.
733 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
734     vec![
735         opt::flag("h", "help", "Display this message"),
736         opt::multi("", "cfg", "Configure the compilation environment", "SPEC"),
737         opt::multi("L", "",   "Add a directory to the library search path", "PATH"),
738         opt::multi("l", "",   "Link the generated crate(s) to the specified native
739                              library NAME. The optional KIND can be one of,
740                              static, dylib, or framework. If omitted, dylib is
741                              assumed.", "[KIND=]NAME"),
742         opt::multi("", "crate-type", "Comma separated list of types of crates
743                                     for the compiler to emit",
744                    "[bin|lib|rlib|dylib|staticlib]"),
745         opt::opt("", "crate-name", "Specify the name of the crate being built",
746                "NAME"),
747         opt::multi("", "emit", "Comma separated list of types of output for \
748                               the compiler to emit",
749                  "[asm|llvm-bc|llvm-ir|obj|link|dep-info]"),
750         opt::multi("", "print", "Comma separated list of compiler information to \
751                                print on stdout",
752                  "[crate-name|file-names|sysroot]"),
753         opt::flag("g",  "",  "Equivalent to -C debuginfo=2"),
754         opt::flag("O", "", "Equivalent to -C opt-level=2"),
755         opt::opt("o", "", "Write output to <filename>", "FILENAME"),
756         opt::opt("",  "out-dir", "Write output to compiler-chosen filename \
757                                 in <dir>", "DIR"),
758         opt::opt("", "explain", "Provide a detailed explanation of an error \
759                                message", "OPT"),
760         opt::flag("", "test", "Build a test harness"),
761         opt::opt("", "target", "Target triple cpu-manufacturer-kernel[-os] \
762                               to compile for (see chapter 3.4 of \
763                               http://www.sourceware.org/autobook/
764                               for details)",
765                "TRIPLE"),
766         opt::multi("W", "warn", "Set lint warnings", "OPT"),
767         opt::multi("A", "allow", "Set lint allowed", "OPT"),
768         opt::multi("D", "deny", "Set lint denied", "OPT"),
769         opt::multi("F", "forbid", "Set lint forbidden", "OPT"),
770         opt::multi("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
771         opt::flag("V", "version", "Print version info and exit"),
772         opt::flag("v", "verbose", "Use verbose output"),
773     ]
774 }
775
776 /// Returns all rustc command line options, including metadata for
777 /// each option, such as whether the option is part of the stable
778 /// long-term interface for rustc.
779 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
780     let mut opts = rustc_short_optgroups();
781     opts.push_all(&[
782         opt::multi("", "extern", "Specify where an external rust library is \
783                                 located",
784                  "NAME=PATH"),
785         opt::opt("", "opt-level", "Optimize with possible levels 0-3", "LEVEL"),
786         opt::opt("", "sysroot", "Override the system root", "PATH"),
787         opt::multi("Z", "", "Set internal debugging options", "FLAG"),
788         opt::opt("", "color", "Configure coloring of output:
789             auto   = colorize, if output goes to a tty (default);
790             always = always colorize output;
791             never  = never colorize output", "auto|always|never"),
792
793         // DEPRECATED
794         opt::flag("", "print-crate-name", "Output the crate name and exit"),
795         opt::flag("", "print-file-name", "Output the file(s) that would be \
796                                         written if compilation \
797                                         continued and exit"),
798         opt::opt("",  "debuginfo",  "Emit DWARF debug info to the objects created:
799              0 = no debug info,
800              1 = line-tables only (for stacktraces and breakpoints),
801              2 = full debug info with variable and type information \
802                     (same as -g)", "LEVEL"),
803         opt::flag("", "no-trans", "Run all passes except translation; no output"),
804         opt::flag("", "no-analysis", "Parse and expand the source, but run no \
805                                     analysis and produce no output"),
806         opt::flag("", "parse-only", "Parse only; do not compile, assemble, \
807                                    or link"),
808         opt::flagopt("", "pretty",
809                    "Pretty-print the input instead of compiling;
810                    valid types are: `normal` (un-annotated source),
811                    `expanded` (crates expanded),
812                    `typed` (crates expanded, with type annotations), or
813                    `expanded,identified` (fully parenthesized, AST nodes with IDs).",
814                  "TYPE"),
815         opt::flagopt_u("", "xpretty",
816                      "Pretty-print the input instead of compiling, unstable variants;
817                       valid types are any of the types for `--pretty`, as well as:
818                       `flowgraph=<nodeid>` (graphviz formatted flowgraph for node), or
819                       `everybody_loops` (all function bodies replaced with `loop {}`).",
820                      "TYPE"),
821         opt::opt_u("", "show-span", "Show spans for compiler debugging", "expr|pat|ty"),
822         opt::flagopt("", "dep-info",
823                  "Output dependency info to <filename> after compiling, \
824                   in a format suitable for use by Makefiles", "FILENAME"),
825     ]);
826     opts
827 }
828
829 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
830 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
831     cfgspecs.into_iter().map(|s| {
832         parse::parse_meta_from_source_str("cfgspec".to_string(),
833                                           s.to_string(),
834                                           Vec::new(),
835                                           &parse::new_parse_sess())
836     }).collect::<ast::CrateConfig>()
837 }
838
839 pub fn build_session_options(matches: &getopts::Matches) -> Options {
840
841     let unparsed_crate_types = matches.opt_strs("crate-type");
842     let crate_types = parse_crate_types_from_list(unparsed_crate_types)
843         .unwrap_or_else(|e| early_error(&e[]));
844
845     let mut lint_opts = vec!();
846     let mut describe_lints = false;
847
848     for &level in [lint::Allow, lint::Warn, lint::Deny, lint::Forbid].iter() {
849         for lint_name in matches.opt_strs(level.as_str()).into_iter() {
850             if lint_name == "help" {
851                 describe_lints = true;
852             } else {
853                 lint_opts.push((lint_name.replace("-", "_"), level));
854             }
855         }
856     }
857
858     let debugging_opts = build_debugging_options(matches);
859
860     let parse_only = if matches.opt_present("parse-only") {
861         // FIXME(acrichto) remove this eventually
862         early_warn("--parse-only is deprecated in favor of -Z parse-only");
863         true
864     } else {
865         debugging_opts.parse_only
866     };
867     let no_trans = if matches.opt_present("no-trans") {
868         // FIXME(acrichto) remove this eventually
869         early_warn("--no-trans is deprecated in favor of -Z no-trans");
870         true
871     } else {
872         debugging_opts.no_trans
873     };
874     let no_analysis = if matches.opt_present("no-analysis") {
875         // FIXME(acrichto) remove this eventually
876         early_warn("--no-analysis is deprecated in favor of -Z no-analysis");
877         true
878     } else {
879         debugging_opts.no_analysis
880     };
881
882     if debugging_opts.debug_llvm {
883         unsafe { llvm::LLVMSetDebug(1); }
884     }
885
886     let mut output_types = Vec::new();
887     if !debugging_opts.parse_only && !no_trans {
888         let unparsed_output_types = matches.opt_strs("emit");
889         for unparsed_output_type in unparsed_output_types.iter() {
890             for part in unparsed_output_type.split(',') {
891                 let output_type = match part.as_slice() {
892                     "asm" => OutputTypeAssembly,
893                     "llvm-ir" => OutputTypeLlvmAssembly,
894                     "llvm-bc" => OutputTypeBitcode,
895                     "obj" => OutputTypeObject,
896                     "link" => OutputTypeExe,
897                     "dep-info" => OutputTypeDepInfo,
898                     _ => {
899                         early_error(&format!("unknown emission type: `{}`",
900                                             part)[])
901                     }
902                 };
903                 output_types.push(output_type)
904             }
905         }
906     };
907     output_types.sort();
908     output_types.dedup();
909     if output_types.len() == 0 {
910         output_types.push(OutputTypeExe);
911     }
912
913     let cg = build_codegen_options(matches);
914
915     let sysroot_opt = matches.opt_str("sysroot").map(|m| Path::new(m));
916     let target = matches.opt_str("target").unwrap_or(
917         host_triple().to_string());
918     let opt_level = {
919         if matches.opt_present("O") {
920             if matches.opt_present("opt-level") {
921                 early_error("-O and --opt-level both provided");
922             }
923             if cg.opt_level.is_some() {
924                 early_error("-O and -C opt-level both provided");
925             }
926             Default
927         } else if matches.opt_present("opt-level") {
928             // FIXME(acrichto) remove this eventually
929             early_warn("--opt-level=N is deprecated in favor of -C opt-level=N");
930             match matches.opt_str("opt-level").as_ref().map(|s| s.as_slice()) {
931                 None      |
932                 Some("0") => No,
933                 Some("1") => Less,
934                 Some("2") => Default,
935                 Some("3") => Aggressive,
936                 Some(arg) => {
937                     early_error(&format!("optimization level needs to be \
938                                          between 0-3 (instead was `{}`)",
939                                         arg)[]);
940                 }
941             }
942         } else {
943             match cg.opt_level {
944                 None => No,
945                 Some(0) => No,
946                 Some(1) => Less,
947                 Some(2) => Default,
948                 Some(3) => Aggressive,
949                 Some(arg) => {
950                     early_error(format!("optimization level needs to be \
951                                          between 0-3 (instead was `{}`)",
952                                         arg).as_slice());
953                 }
954             }
955         }
956     };
957     let gc = debugging_opts.gc;
958     let debuginfo = if matches.opt_present("g") {
959         if matches.opt_present("debuginfo") {
960             early_error("-g and --debuginfo both provided");
961         }
962         if cg.debuginfo.is_some() {
963             early_error("-g and -C debuginfo both provided");
964         }
965         FullDebugInfo
966     } else if matches.opt_present("debuginfo") {
967         // FIXME(acrichto) remove this eventually
968         early_warn("--debuginfo=N is deprecated in favor of -C debuginfo=N");
969         match matches.opt_str("debuginfo").as_ref().map(|s| s.as_slice()) {
970             Some("0") => NoDebugInfo,
971             Some("1") => LimitedDebugInfo,
972             None      |
973             Some("2") => FullDebugInfo,
974             Some(arg) => {
975                 early_error(&format!("debug info level needs to be between \
976                                      0-2 (instead was `{}`)",
977                                     arg)[]);
978             }
979         }
980     } else {
981         match cg.debuginfo {
982             None | Some(0) => NoDebugInfo,
983             Some(1) => LimitedDebugInfo,
984             Some(2) => FullDebugInfo,
985             Some(arg) => {
986                 early_error(format!("debug info level needs to be between \
987                                      0-2 (instead was `{}`)",
988                                     arg).as_slice());
989             }
990         }
991     };
992
993     let mut search_paths = SearchPaths::new();
994     for s in matches.opt_strs("L").iter() {
995         search_paths.add_path(&s[]);
996     }
997
998     let libs = matches.opt_strs("l").into_iter().map(|s| {
999         let mut parts = s.splitn(1, '=');
1000         let kind = parts.next().unwrap();
1001         if let Some(name) = parts.next() {
1002             let kind = match kind {
1003                 "dylib" => cstore::NativeUnknown,
1004                 "framework" => cstore::NativeFramework,
1005                 "static" => cstore::NativeStatic,
1006                 s => {
1007                     early_error(format!("unknown library kind `{}`, expected \
1008                                          one of dylib, framework, or static",
1009                                         s).as_slice());
1010                 }
1011             };
1012             return (name.to_string(), kind)
1013         }
1014
1015         // FIXME(acrichto) remove this once crates have stopped using it, this
1016         //                 is deprecated behavior now.
1017         let mut parts = s.rsplitn(1, ':');
1018         let kind = parts.next().unwrap();
1019         let (name, kind) = match (parts.next(), kind) {
1020             (None, name) |
1021             (Some(name), "dylib") => (name, cstore::NativeUnknown),
1022             (Some(name), "framework") => (name, cstore::NativeFramework),
1023             (Some(name), "static") => (name, cstore::NativeStatic),
1024             (_, s) => {
1025                 early_error(&format!("unknown library kind `{}`, expected \
1026                                      one of dylib, framework, or static",
1027                                     s)[]);
1028             }
1029         };
1030         (name.to_string(), kind)
1031     }).collect();
1032
1033     let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
1034     let test = matches.opt_present("test");
1035     let write_dependency_info = if matches.opt_present("dep-info") {
1036         // FIXME(acrichto) remove this eventually
1037         early_warn("--dep-info has been deprecated in favor of --emit");
1038         (true, matches.opt_str("dep-info").map(|p| Path::new(p)))
1039     } else {
1040         (output_types.contains(&OutputTypeDepInfo), None)
1041     };
1042
1043     let mut prints = matches.opt_strs("print").into_iter().map(|s| {
1044         match s.as_slice() {
1045             "crate-name" => PrintRequest::CrateName,
1046             "file-names" => PrintRequest::FileNames,
1047             "sysroot" => PrintRequest::Sysroot,
1048             req => {
1049                 early_error(format!("unknown print request `{}`", req).as_slice())
1050             }
1051         }
1052     }).collect::<Vec<_>>();
1053     if matches.opt_present("print-crate-name") {
1054         // FIXME(acrichto) remove this eventually
1055         early_warn("--print-crate-name has been deprecated in favor of \
1056                     --print crate-name");
1057         prints.push(PrintRequest::CrateName);
1058     }
1059     if matches.opt_present("print-file-name") {
1060         // FIXME(acrichto) remove this eventually
1061         early_warn("--print-file-name has been deprecated in favor of \
1062                     --print file-names");
1063         prints.push(PrintRequest::FileNames);
1064     }
1065
1066     if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
1067         early_warn("-C remark will not show source locations without \
1068                     --debuginfo");
1069     }
1070
1071     let color = match matches.opt_str("color").as_ref().map(|s| &s[]) {
1072         Some("auto")   => Auto,
1073         Some("always") => Always,
1074         Some("never")  => Never,
1075
1076         None => Auto,
1077
1078         Some(arg) => {
1079             early_error(&format!("argument for --color must be auto, always \
1080                                  or never (instead was `{}`)",
1081                                 arg)[])
1082         }
1083     };
1084
1085     let mut externs = HashMap::new();
1086     for arg in matches.opt_strs("extern").iter() {
1087         let mut parts = arg.splitn(1, '=');
1088         let name = match parts.next() {
1089             Some(s) => s,
1090             None => early_error("--extern value must not be empty"),
1091         };
1092         let location = match parts.next() {
1093             Some(s) => s,
1094             None => early_error("--extern value must be of the format `foo=bar`"),
1095         };
1096
1097         match externs.entry(name.to_string()) {
1098             Vacant(entry) => { entry.insert(vec![location.to_string()]); },
1099             Occupied(mut entry) => { entry.get_mut().push(location.to_string()); },
1100         }
1101     }
1102
1103     let crate_name = matches.opt_str("crate-name");
1104
1105     Options {
1106         crate_types: crate_types,
1107         gc: gc,
1108         optimize: opt_level,
1109         debuginfo: debuginfo,
1110         lint_opts: lint_opts,
1111         describe_lints: describe_lints,
1112         output_types: output_types,
1113         search_paths: search_paths,
1114         maybe_sysroot: sysroot_opt,
1115         target_triple: target,
1116         cfg: cfg,
1117         test: test,
1118         parse_only: parse_only,
1119         no_trans: no_trans,
1120         no_analysis: no_analysis,
1121         debugging_opts: debugging_opts,
1122         write_dependency_info: write_dependency_info,
1123         prints: prints,
1124         cg: cg,
1125         color: color,
1126         show_span: None,
1127         externs: externs,
1128         crate_name: crate_name,
1129         alt_std_name: None,
1130         libs: libs,
1131         unstable_features: UnstableFeatures::Disallow
1132     }
1133 }
1134
1135 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
1136
1137     let mut crate_types: Vec<CrateType> = Vec::new();
1138     for unparsed_crate_type in list_list.iter() {
1139         for part in unparsed_crate_type.split(',') {
1140             let new_part = match part {
1141                 "lib"       => default_lib_output(),
1142                 "rlib"      => CrateTypeRlib,
1143                 "staticlib" => CrateTypeStaticlib,
1144                 "dylib"     => CrateTypeDylib,
1145                 "bin"       => CrateTypeExecutable,
1146                 _ => {
1147                     return Err(format!("unknown crate type: `{}`",
1148                                        part));
1149                 }
1150             };
1151             crate_types.push(new_part)
1152         }
1153     }
1154
1155     return Ok(crate_types);
1156 }
1157
1158 impl fmt::Show for CrateType {
1159     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1160         match *self {
1161             CrateTypeExecutable => "bin".fmt(f),
1162             CrateTypeDylib => "dylib".fmt(f),
1163             CrateTypeRlib => "rlib".fmt(f),
1164             CrateTypeStaticlib => "staticlib".fmt(f)
1165         }
1166     }
1167 }
1168
1169 #[cfg(test)]
1170 mod test {
1171
1172     use session::config::{build_configuration, optgroups, build_session_options};
1173     use session::build_session;
1174
1175     use getopts::getopts;
1176     use syntax::attr;
1177     use syntax::attr::AttrMetaMethods;
1178     use syntax::diagnostics;
1179
1180     // When the user supplies --test we should implicitly supply --cfg test
1181     #[test]
1182     fn test_switch_implies_cfg_test() {
1183         let matches =
1184             &match getopts(&["--test".to_string()], &optgroups()[]) {
1185               Ok(m) => m,
1186               Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
1187             };
1188         let registry = diagnostics::registry::Registry::new(&[]);
1189         let sessopts = build_session_options(matches);
1190         let sess = build_session(sessopts, None, registry);
1191         let cfg = build_configuration(&sess);
1192         assert!((attr::contains_name(&cfg[], "test")));
1193     }
1194
1195     // When the user supplies --test and --cfg test, don't implicitly add
1196     // another --cfg test
1197     #[test]
1198     fn test_switch_implies_cfg_test_unless_cfg_test() {
1199         let matches =
1200             &match getopts(&["--test".to_string(), "--cfg=test".to_string()],
1201                            &optgroups()[]) {
1202               Ok(m) => m,
1203               Err(f) => {
1204                 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
1205               }
1206             };
1207         let registry = diagnostics::registry::Registry::new(&[]);
1208         let sessopts = build_session_options(matches);
1209         let sess = build_session(sessopts, None, registry);
1210         let cfg = build_configuration(&sess);
1211         let mut test_items = cfg.iter().filter(|m| m.name() == "test");
1212         assert!(test_items.next().is_some());
1213         assert!(test_items.next().is_none());
1214     }
1215
1216     #[test]
1217     fn test_can_print_warnings() {
1218         {
1219             let matches = getopts(&[
1220                 "-Awarnings".to_string()
1221             ], &optgroups()[]).unwrap();
1222             let registry = diagnostics::registry::Registry::new(&[]);
1223             let sessopts = build_session_options(&matches);
1224             let sess = build_session(sessopts, None, registry);
1225             assert!(!sess.can_print_warnings);
1226         }
1227
1228         {
1229             let matches = getopts(&[
1230                 "-Awarnings".to_string(),
1231                 "-Dwarnings".to_string()
1232             ], &optgroups()[]).unwrap();
1233             let registry = diagnostics::registry::Registry::new(&[]);
1234             let sessopts = build_session_options(&matches);
1235             let sess = build_session(sessopts, None, registry);
1236             assert!(sess.can_print_warnings);
1237         }
1238
1239         {
1240             let matches = getopts(&[
1241                 "-Adead_code".to_string()
1242             ], &optgroups()[]).unwrap();
1243             let registry = diagnostics::registry::Registry::new(&[]);
1244             let sessopts = build_session_options(&matches);
1245             let sess = build_session(sessopts, None, registry);
1246             assert!(sess.can_print_warnings);
1247         }
1248     }
1249 }