]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/config.rs
5d691af49dccb30dca2f45a12e9a6a0905a5ee2e
[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::DebugInfoLevel::*;
19
20 use session::{early_error, early_warn, Session};
21 use session::search_paths::SearchPaths;
22
23 use rustc_back::target::Target;
24 use lint;
25 use middle::cstore;
26
27 use syntax::ast::{self, IntTy, UintTy};
28 use syntax::attr;
29 use syntax::attr::AttrMetaMethods;
30 use syntax::diagnostic::{ColorConfig, Auto, Always, Never, SpanHandler};
31 use syntax::parse;
32 use syntax::parse::token::InternedString;
33 use syntax::feature_gate::UnstableFeatures;
34
35 use getopts;
36 use std::collections::HashMap;
37 use std::env;
38 use std::fmt;
39 use std::path::PathBuf;
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, Eq, Hash)]
65 pub enum OutputType {
66     Bitcode,
67     Assembly,
68     LlvmAssembly,
69     Object,
70     Exe,
71     DepInfo,
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 debug_assertions: bool,
83     pub debuginfo: DebugInfoLevel,
84     pub lint_opts: Vec<(String, lint::Level)>,
85     pub lint_cap: Option<lint::Level>,
86     pub describe_lints: bool,
87     pub output_types: HashMap<OutputType, Option<PathBuf>>,
88     // This was mutable for rustpkg, which updates search paths based on the
89     // parsed code. It remains mutable in case its replacements wants to use
90     // this.
91     pub search_paths: SearchPaths,
92     pub libs: Vec<(String, cstore::NativeLibraryKind)>,
93     pub maybe_sysroot: Option<PathBuf>,
94     pub target_triple: String,
95     // User-specified cfg meta items. The compiler itself will add additional
96     // items to the crate config, and during parsing the entire crate config
97     // will be added to the crate AST node.  This should not be used for
98     // anything except building the full crate config prior to parsing.
99     pub cfg: ast::CrateConfig,
100     pub test: bool,
101     pub parse_only: bool,
102     pub no_trans: bool,
103     pub treat_err_as_bug: bool,
104     pub no_analysis: bool,
105     pub debugging_opts: DebuggingOptions,
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, PartialEq, Eq)]
121 pub enum PrintRequest {
122     FileNames,
123     Sysroot,
124     CrateName,
125 }
126
127 pub enum Input {
128     /// Load source from file
129     File(PathBuf),
130     /// The string is the source
131     Str(String)
132 }
133
134 impl Input {
135     pub fn filestem(&self) -> String {
136         match *self {
137             Input::File(ref ifile) => ifile.file_stem().unwrap()
138                                            .to_str().unwrap().to_string(),
139             Input::Str(_) => "rust_out".to_string(),
140         }
141     }
142 }
143
144 #[derive(Clone)]
145 pub struct OutputFilenames {
146     pub out_directory: PathBuf,
147     pub out_filestem: String,
148     pub single_output_file: Option<PathBuf>,
149     pub extra: String,
150     pub outputs: HashMap<OutputType, Option<PathBuf>>,
151 }
152
153 impl OutputFilenames {
154     pub fn path(&self, flavor: OutputType) -> PathBuf {
155         self.outputs.get(&flavor).and_then(|p| p.to_owned())
156             .or_else(|| self.single_output_file.clone())
157             .unwrap_or_else(|| self.temp_path(flavor))
158     }
159
160     pub fn temp_path(&self, flavor: OutputType) -> PathBuf {
161         let base = self.out_directory.join(&self.filestem());
162         match flavor {
163             OutputType::Bitcode => base.with_extension("bc"),
164             OutputType::Assembly => base.with_extension("s"),
165             OutputType::LlvmAssembly => base.with_extension("ll"),
166             OutputType::Object => base.with_extension("o"),
167             OutputType::DepInfo => base.with_extension("d"),
168             OutputType::Exe => base,
169         }
170     }
171
172     pub fn with_extension(&self, extension: &str) -> PathBuf {
173         self.out_directory.join(&self.filestem()).with_extension(extension)
174     }
175
176     pub fn filestem(&self) -> String {
177         format!("{}{}", self.out_filestem, self.extra)
178     }
179 }
180
181 pub fn host_triple() -> &'static str {
182     // Get the host triple out of the build environment. This ensures that our
183     // idea of the host triple is the same as for the set of libraries we've
184     // actually built.  We can't just take LLVM's host triple because they
185     // normalize all ix86 architectures to i386.
186     //
187     // Instead of grabbing the host triple (for the current host), we grab (at
188     // compile time) the target triple that this rustc is built with and
189     // calling that (at runtime) the host triple.
190     (option_env!("CFG_COMPILER_HOST_TRIPLE")).
191         expect("CFG_COMPILER_HOST_TRIPLE")
192 }
193
194 /// Some reasonable defaults
195 pub fn basic_options() -> Options {
196     Options {
197         crate_types: Vec::new(),
198         gc: false,
199         optimize: No,
200         debuginfo: NoDebugInfo,
201         lint_opts: Vec::new(),
202         lint_cap: None,
203         describe_lints: false,
204         output_types: HashMap::new(),
205         search_paths: SearchPaths::new(),
206         maybe_sysroot: None,
207         target_triple: host_triple().to_string(),
208         cfg: Vec::new(),
209         test: false,
210         parse_only: false,
211         no_trans: false,
212         treat_err_as_bug: false,
213         no_analysis: false,
214         debugging_opts: basic_debugging_options(),
215         prints: Vec::new(),
216         cg: basic_codegen_options(),
217         color: Auto,
218         show_span: None,
219         externs: HashMap::new(),
220         crate_name: None,
221         alt_std_name: None,
222         libs: Vec::new(),
223         unstable_features: UnstableFeatures::Disallow,
224         debug_assertions: true,
225     }
226 }
227
228 // The type of entry function, so
229 // users can have their own entry
230 // functions that don't start a
231 // scheduler
232 #[derive(Copy, Clone, PartialEq)]
233 pub enum EntryFnType {
234     EntryMain,
235     EntryStart,
236     EntryNone,
237 }
238
239 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
240 pub enum CrateType {
241     CrateTypeExecutable,
242     CrateTypeDylib,
243     CrateTypeRlib,
244     CrateTypeStaticlib,
245 }
246
247 #[derive(Clone)]
248 pub enum Passes {
249     SomePasses(Vec<String>),
250     AllPasses,
251 }
252
253 impl Passes {
254     pub fn is_empty(&self) -> bool {
255         match *self {
256             SomePasses(ref v) => v.is_empty(),
257             AllPasses => false,
258         }
259     }
260 }
261
262 /// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
263 /// at once. The goal of this macro is to define an interface that can be
264 /// programmatically used by the option parser in order to initialize the struct
265 /// without hardcoding field names all over the place.
266 ///
267 /// The goal is to invoke this macro once with the correct fields, and then this
268 /// macro generates all necessary code. The main gotcha of this macro is the
269 /// cgsetters module which is a bunch of generated code to parse an option into
270 /// its respective field in the struct. There are a few hand-written parsers for
271 /// parsing specific types of values in this module.
272 macro_rules! options {
273     ($struct_name:ident, $setter_name:ident, $defaultfn:ident,
274      $buildfn:ident, $prefix:expr, $outputname:expr,
275      $stat:ident, $mod_desc:ident, $mod_set:ident,
276      $($opt:ident : $t:ty = ($init:expr, $parse:ident, $desc:expr)),* ,) =>
277 (
278     #[derive(Clone)]
279     pub struct $struct_name { $(pub $opt: $t),* }
280
281     pub fn $defaultfn() -> $struct_name {
282         $struct_name { $($opt: $init),* }
283     }
284
285     pub fn $buildfn(matches: &getopts::Matches, color: ColorConfig) -> $struct_name
286     {
287         let mut op = $defaultfn();
288         for option in matches.opt_strs($prefix) {
289             let mut iter = option.splitn(2, '=');
290             let key = iter.next().unwrap();
291             let value = iter.next();
292             let option_to_lookup = key.replace("-", "_");
293             let mut found = false;
294             for &(candidate, setter, opt_type_desc, _) in $stat {
295                 if option_to_lookup != candidate { continue }
296                 if !setter(&mut op, value) {
297                     match (value, opt_type_desc) {
298                         (Some(..), None) => {
299                             early_error(color, &format!("{} option `{}` takes no \
300                                                          value", $outputname, key))
301                         }
302                         (None, Some(type_desc)) => {
303                             early_error(color, &format!("{0} option `{1}` requires \
304                                                          {2} ({3} {1}=<value>)",
305                                                         $outputname, key,
306                                                         type_desc, $prefix))
307                         }
308                         (Some(value), Some(type_desc)) => {
309                             early_error(color, &format!("incorrect value `{}` for {} \
310                                                          option `{}` - {} was expected",
311                                                         value, $outputname,
312                                                         key, type_desc))
313                         }
314                         (None, None) => unreachable!()
315                     }
316                 }
317                 found = true;
318                 break;
319             }
320             if !found {
321                 early_error(color, &format!("unknown {} option: `{}`",
322                                             $outputname, key));
323             }
324         }
325         return op;
326     }
327
328     pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
329     pub const $stat: &'static [(&'static str, $setter_name,
330                                      Option<&'static str>, &'static str)] =
331         &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
332
333     #[allow(non_upper_case_globals, dead_code)]
334     mod $mod_desc {
335         pub const parse_bool: Option<&'static str> = None;
336         pub const parse_opt_bool: Option<&'static str> =
337             Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
338         pub const parse_string: Option<&'static str> = Some("a string");
339         pub const parse_opt_string: Option<&'static str> = Some("a string");
340         pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
341         pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
342         pub const parse_uint: Option<&'static str> = Some("a number");
343         pub const parse_passes: Option<&'static str> =
344             Some("a space-separated list of passes, or `all`");
345         pub const parse_opt_uint: Option<&'static str> =
346             Some("a number");
347     }
348
349     #[allow(dead_code)]
350     mod $mod_set {
351         use super::{$struct_name, Passes, SomePasses, AllPasses};
352
353         $(
354             pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
355                 $parse(&mut cg.$opt, v)
356             }
357         )*
358
359         fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
360             match v {
361                 Some(..) => false,
362                 None => { *slot = true; true }
363             }
364         }
365
366         fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
367             match v {
368                 Some(s) => {
369                     match s {
370                         "n" | "no" | "off" => {
371                             *slot = Some(false);
372                         }
373                         "y" | "yes" | "on" => {
374                             *slot = Some(true);
375                         }
376                         _ => { return false; }
377                     }
378
379                     true
380                 },
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.split_whitespace() {
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.split_whitespace().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 usize, v: Option<&str>) -> bool {
425             match v.and_then(|s| s.parse().ok()) {
426                 Some(i) => { *slot = i; true },
427                 None => false
428             }
429         }
430
431         fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
432             match v {
433                 Some(s) => { *slot = s.parse().ok(); 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: usize = (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<usize> = (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<usize> = (None, parse_opt_uint,
513         "optimize with possible levels 0-3"),
514     debug_assertions: Option<bool> = (None, parse_opt_bool,
515         "explicitly enable the cfg(debug_assertions) directive"),
516     inline_threshold: Option<usize> = (None, parse_opt_uint,
517         "set the inlining threshold for"),
518 }
519
520
521 options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
522          build_debugging_options, "Z", "debugging",
523          DB_OPTIONS, db_type_desc, dbsetters,
524     verbose: bool = (false, parse_bool,
525         "in general, enable more debug printouts"),
526     time_passes: bool = (false, parse_bool,
527         "measure time of each rustc pass"),
528     count_llvm_insns: bool = (false, parse_bool,
529         "count where LLVM instrs originate"),
530     time_llvm_passes: bool = (false, parse_bool,
531         "measure time of each LLVM pass"),
532     input_stats: bool = (false, parse_bool,
533         "gather statistics about the input"),
534     trans_stats: bool = (false, parse_bool,
535         "gather trans statistics"),
536     asm_comments: bool = (false, parse_bool,
537         "generate comments into the assembly (may change behavior)"),
538     no_verify: bool = (false, parse_bool,
539         "skip LLVM verification"),
540     borrowck_stats: bool = (false, parse_bool,
541         "gather borrowck statistics"),
542     no_landing_pads: bool = (false, parse_bool,
543         "omit landing pads for unwinding"),
544     debug_llvm: bool = (false, parse_bool,
545         "enable debug output from LLVM"),
546     count_type_sizes: bool = (false, parse_bool,
547         "count the sizes of aggregate types"),
548     meta_stats: bool = (false, parse_bool,
549         "gather metadata statistics"),
550     print_link_args: bool = (false, parse_bool,
551         "print the arguments passed to the linker"),
552     gc: bool = (false, parse_bool,
553         "garbage collect shared data (experimental)"),
554     print_llvm_passes: bool = (false, parse_bool,
555         "prints the llvm optimization passes being run"),
556     ast_json: bool = (false, parse_bool,
557         "print the AST as JSON and halt"),
558     ast_json_noexpand: bool = (false, parse_bool,
559         "print the pre-expansion AST as JSON and halt"),
560     ls: bool = (false, parse_bool,
561         "list the symbols defined by a library crate"),
562     save_analysis: bool = (false, parse_bool,
563         "write syntax and type analysis information in addition to normal output"),
564     print_move_fragments: bool = (false, parse_bool,
565         "print out move-fragment data for every fn"),
566     flowgraph_print_loans: bool = (false, parse_bool,
567         "include loan analysis data in --unpretty flowgraph output"),
568     flowgraph_print_moves: bool = (false, parse_bool,
569         "include move analysis data in --unpretty flowgraph output"),
570     flowgraph_print_assigns: bool = (false, parse_bool,
571         "include assignment analysis data in --unpretty flowgraph output"),
572     flowgraph_print_all: bool = (false, parse_bool,
573         "include all dataflow analysis data in --unpretty flowgraph output"),
574     print_region_graph: bool = (false, parse_bool,
575          "prints region inference graph. \
576           Use with RUST_REGION_GRAPH=help for more info"),
577     parse_only: bool = (false, parse_bool,
578           "parse only; do not compile, assemble, or link"),
579     no_trans: bool = (false, parse_bool,
580           "run all passes except translation; no output"),
581     treat_err_as_bug: bool = (false, parse_bool,
582           "treat all errors that occur as bugs"),
583     no_analysis: bool = (false, parse_bool,
584           "parse and expand the source, but run no analysis"),
585     extra_plugins: Vec<String> = (Vec::new(), parse_list,
586         "load extra plugins"),
587     unstable_options: bool = (false, parse_bool,
588           "adds unstable command line options to rustc interface"),
589     print_enum_sizes: bool = (false, parse_bool,
590           "print the size of enums and their variants"),
591     force_overflow_checks: Option<bool> = (None, parse_opt_bool,
592           "force overflow checks on or off"),
593     force_dropflag_checks: Option<bool> = (None, parse_opt_bool,
594           "force drop flag checks on or off"),
595     trace_macros: bool = (false, parse_bool,
596           "for every macro invocation, print its name and arguments"),
597     enable_nonzeroing_move_hints: bool = (false, parse_bool,
598           "force nonzeroing move optimization on"),
599     keep_mtwt_tables: bool = (false, parse_bool,
600           "don't clear the resolution tables after analysis"),
601 }
602
603 pub fn default_lib_output() -> CrateType {
604     CrateTypeRlib
605 }
606
607 pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
608     use syntax::parse::token::intern_and_get_ident as intern;
609
610     let end = &sess.target.target.target_endian;
611     let arch = &sess.target.target.arch;
612     let wordsz = &sess.target.target.target_pointer_width;
613     let os = &sess.target.target.target_os;
614     let env = &sess.target.target.target_env;
615     let vendor = &sess.target.target.target_vendor;
616
617     let fam = if let Some(ref fam) = sess.target.target.options.target_family {
618         intern(fam)
619     } else if sess.target.target.options.is_like_windows {
620         InternedString::new("windows")
621     } else {
622         InternedString::new("unix")
623     };
624
625     let mk = attr::mk_name_value_item_str;
626     let mut ret = vec![ // Target bindings.
627         mk(InternedString::new("target_os"), intern(os)),
628         mk(InternedString::new("target_family"), fam.clone()),
629         mk(InternedString::new("target_arch"), intern(arch)),
630         mk(InternedString::new("target_endian"), intern(end)),
631         mk(InternedString::new("target_pointer_width"), intern(wordsz)),
632         mk(InternedString::new("target_env"), intern(env)),
633         mk(InternedString::new("target_vendor"), intern(vendor)),
634     ];
635     match &fam[..] {
636         "windows" | "unix" => ret.push(attr::mk_word_item(fam)),
637         _ => (),
638     }
639     if sess.opts.debug_assertions {
640         ret.push(attr::mk_word_item(InternedString::new("debug_assertions")));
641     }
642     return ret;
643 }
644
645 pub fn append_configuration(cfg: &mut ast::CrateConfig,
646                             name: InternedString) {
647     if !cfg.iter().any(|mi| mi.name() == name) {
648         cfg.push(attr::mk_word_item(name))
649     }
650 }
651
652 pub fn build_configuration(sess: &Session) -> ast::CrateConfig {
653     // Combine the configuration requested by the session (command line) with
654     // some default and generated configuration items
655     let default_cfg = default_configuration(sess);
656     let mut user_cfg = sess.opts.cfg.clone();
657     // If the user wants a test runner, then add the test cfg
658     if sess.opts.test {
659         append_configuration(&mut user_cfg, InternedString::new("test"))
660     }
661     let mut v = user_cfg.into_iter().collect::<Vec<_>>();
662     v.push_all(&default_cfg[..]);
663     v
664 }
665
666 pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config {
667     let target = match Target::search(&opts.target_triple) {
668         Ok(t) => t,
669         Err(e) => {
670             panic!(sp.handler().fatal(&format!("Error loading target specification: {}", e)));
671         }
672     };
673
674     let (int_type, uint_type) = match &target.target_pointer_width[..] {
675         "32" => (ast::TyI32, ast::TyU32),
676         "64" => (ast::TyI64, ast::TyU64),
677         w    => panic!(sp.handler().fatal(&format!("target specification was invalid: \
678                                                     unrecognized target-pointer-width {}", w))),
679     };
680
681     Config {
682         target: target,
683         int_type: int_type,
684         uint_type: uint_type,
685     }
686 }
687
688 /// Returns the "short" subset of the stable rustc command line options.
689 pub fn short_optgroups() -> Vec<getopts::OptGroup> {
690     rustc_short_optgroups().into_iter()
691         .filter(|g|g.is_stable())
692         .map(|g|g.opt_group)
693         .collect()
694 }
695
696 /// Returns all of the stable rustc command line options.
697 pub fn optgroups() -> Vec<getopts::OptGroup> {
698     rustc_optgroups().into_iter()
699         .filter(|g|g.is_stable())
700         .map(|g|g.opt_group)
701         .collect()
702 }
703
704 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
705 pub enum OptionStability { Stable, Unstable }
706
707 #[derive(Clone, PartialEq, Eq)]
708 pub struct RustcOptGroup {
709     pub opt_group: getopts::OptGroup,
710     pub stability: OptionStability,
711 }
712
713 impl RustcOptGroup {
714     pub fn is_stable(&self) -> bool {
715         self.stability == OptionStability::Stable
716     }
717
718     fn stable(g: getopts::OptGroup) -> RustcOptGroup {
719         RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
720     }
721
722     fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
723         RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
724     }
725 }
726
727 // The `opt` local module holds wrappers around the `getopts` API that
728 // adds extra rustc-specific metadata to each option; such metadata
729 // is exposed by .  The public
730 // functions below ending with `_u` are the functions that return
731 // *unstable* options, i.e. options that are only enabled when the
732 // user also passes the `-Z unstable-options` debugging flag.
733 mod opt {
734     // The `fn opt_u` etc below are written so that we can use them
735     // in the future; do not warn about them not being used right now.
736     #![allow(dead_code)]
737
738     use getopts;
739     use super::RustcOptGroup;
740
741     pub type R = RustcOptGroup;
742     pub type S<'a> = &'a str;
743
744     fn stable(g: getopts::OptGroup) -> R { RustcOptGroup::stable(g) }
745     fn unstable(g: getopts::OptGroup) -> R { RustcOptGroup::unstable(g) }
746
747     // FIXME (pnkfelix): We default to stable since the current set of
748     // options is defacto stable.  However, it would be good to revise the
749     // code so that a stable option is the thing that takes extra effort
750     // to encode.
751
752     pub fn     opt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optopt(a, b, c, d)) }
753     pub fn   multi(a: S, b: S, c: S, d: S) -> R { stable(getopts::optmulti(a, b, c, d)) }
754     pub fn    flag(a: S, b: S, c: S)       -> R { stable(getopts::optflag(a, b, c)) }
755     pub fn flagopt(a: S, b: S, c: S, d: S) -> R { stable(getopts::optflagopt(a, b, c, d)) }
756     pub fn flagmulti(a: S, b: S, c: S)     -> R { stable(getopts::optflagmulti(a, b, c)) }
757
758
759     pub fn     opt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optopt(a, b, c, d)) }
760     pub fn   multi_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optmulti(a, b, c, d)) }
761     pub fn    flag_u(a: S, b: S, c: S)       -> R { unstable(getopts::optflag(a, b, c)) }
762     pub fn flagopt_u(a: S, b: S, c: S, d: S) -> R { unstable(getopts::optflagopt(a, b, c, d)) }
763     pub fn flagmulti_u(a: S, b: S, c: S)     -> R { unstable(getopts::optflagmulti(a, b, c)) }
764 }
765
766 /// Returns the "short" subset of the rustc command line options,
767 /// including metadata for each option, such as whether the option is
768 /// part of the stable long-term interface for rustc.
769 pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
770     vec![
771         opt::flag("h", "help", "Display this message"),
772         opt::multi("", "cfg", "Configure the compilation environment", "SPEC"),
773         opt::multi("L", "",   "Add a directory to the library search path",
774                    "[KIND=]PATH"),
775         opt::multi("l", "",   "Link the generated crate(s) to the specified native
776                              library NAME. The optional KIND can be one of,
777                              static, dylib, or framework. If omitted, dylib is
778                              assumed.", "[KIND=]NAME"),
779         opt::multi("", "crate-type", "Comma separated list of types of crates
780                                     for the compiler to emit",
781                    "[bin|lib|rlib|dylib|staticlib]"),
782         opt::opt("", "crate-name", "Specify the name of the crate being built",
783                "NAME"),
784         opt::multi("", "emit", "Comma separated list of types of output for \
785                               the compiler to emit",
786                  "[asm|llvm-bc|llvm-ir|obj|link|dep-info]"),
787         opt::multi("", "print", "Comma separated list of compiler information to \
788                                print on stdout",
789                  "[crate-name|file-names|sysroot]"),
790         opt::flagmulti("g",  "",  "Equivalent to -C debuginfo=2"),
791         opt::flagmulti("O", "", "Equivalent to -C opt-level=2"),
792         opt::opt("o", "", "Write output to <filename>", "FILENAME"),
793         opt::opt("",  "out-dir", "Write output to compiler-chosen filename \
794                                 in <dir>", "DIR"),
795         opt::opt("", "explain", "Provide a detailed explanation of an error \
796                                message", "OPT"),
797         opt::flag("", "test", "Build a test harness"),
798         opt::opt("", "target", "Target triple cpu-manufacturer-kernel[-os] \
799                               to compile for (see chapter 3.4 of \
800                               http://www.sourceware.org/autobook/
801                               for details)",
802                "TRIPLE"),
803         opt::multi("W", "warn", "Set lint warnings", "OPT"),
804         opt::multi("A", "allow", "Set lint allowed", "OPT"),
805         opt::multi("D", "deny", "Set lint denied", "OPT"),
806         opt::multi("F", "forbid", "Set lint forbidden", "OPT"),
807         opt::multi("", "cap-lints", "Set the most restrictive lint level. \
808                                      More restrictive lints are capped at this \
809                                      level", "LEVEL"),
810         opt::multi("C", "codegen", "Set a codegen option", "OPT[=VALUE]"),
811         opt::flag("V", "version", "Print version info and exit"),
812         opt::flag("v", "verbose", "Use verbose output"),
813     ]
814 }
815
816 /// Returns all rustc command line options, including metadata for
817 /// each option, such as whether the option is part of the stable
818 /// long-term interface for rustc.
819 pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
820     let mut opts = rustc_short_optgroups();
821     opts.push_all(&[
822         opt::multi("", "extern", "Specify where an external rust library is \
823                                 located",
824                  "NAME=PATH"),
825         opt::opt("", "sysroot", "Override the system root", "PATH"),
826         opt::multi("Z", "", "Set internal debugging options", "FLAG"),
827         opt::opt("", "color", "Configure coloring of output:
828             auto   = colorize, if output goes to a tty (default);
829             always = always colorize output;
830             never  = never colorize output", "auto|always|never"),
831
832         opt::flagopt_u("", "pretty",
833                    "Pretty-print the input instead of compiling;
834                    valid types are: `normal` (un-annotated source),
835                    `expanded` (crates expanded), or
836                    `expanded,identified` (fully parenthesized, AST nodes with IDs).",
837                  "TYPE"),
838         opt::flagopt_u("", "unpretty",
839                      "Present the input source, unstable (and less-pretty) variants;
840                       valid types are any of the types for `--pretty`, as well as:
841                       `flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
842                       `everybody_loops` (all function bodies replaced with `loop {}`),
843                       `hir` (the HIR), `hir,identified`, or
844                       `hir,typed` (HIR with types for each node).",
845                      "TYPE"),
846         opt::opt_u("", "show-span", "Show spans for compiler debugging", "expr|pat|ty"),
847     ]);
848     opts
849 }
850
851 // Convert strings provided as --cfg [cfgspec] into a crate_cfg
852 pub fn parse_cfgspecs(cfgspecs: Vec<String> ) -> ast::CrateConfig {
853     cfgspecs.into_iter().map(|s| {
854         parse::parse_meta_from_source_str("cfgspec".to_string(),
855                                           s.to_string(),
856                                           Vec::new(),
857                                           &parse::ParseSess::new())
858     }).collect::<ast::CrateConfig>()
859 }
860
861 pub fn build_session_options(matches: &getopts::Matches) -> Options {
862     let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
863         Some("auto")   => Auto,
864         Some("always") => Always,
865         Some("never")  => Never,
866
867         None => Auto,
868
869         Some(arg) => {
870             early_error(Auto, &format!("argument for --color must be auto, always \
871                                         or never (instead was `{}`)",
872                                        arg))
873         }
874     };
875
876     let unparsed_crate_types = matches.opt_strs("crate-type");
877     let crate_types = parse_crate_types_from_list(unparsed_crate_types)
878         .unwrap_or_else(|e| early_error(color, &e[..]));
879
880     let mut lint_opts = vec!();
881     let mut describe_lints = false;
882
883     for &level in &[lint::Allow, lint::Warn, lint::Deny, lint::Forbid] {
884         for lint_name in matches.opt_strs(level.as_str()) {
885             if lint_name == "help" {
886                 describe_lints = true;
887             } else {
888                 lint_opts.push((lint_name.replace("-", "_"), level));
889             }
890         }
891     }
892
893     let lint_cap = matches.opt_str("cap-lints").map(|cap| {
894         lint::Level::from_str(&cap).unwrap_or_else(|| {
895             early_error(color, &format!("unknown lint level: `{}`", cap))
896         })
897     });
898
899     let debugging_opts = build_debugging_options(matches, color);
900
901     let parse_only = debugging_opts.parse_only;
902     let no_trans = debugging_opts.no_trans;
903     let treat_err_as_bug = debugging_opts.treat_err_as_bug;
904     let no_analysis = debugging_opts.no_analysis;
905
906     if debugging_opts.debug_llvm {
907         unsafe { llvm::LLVMSetDebug(1); }
908     }
909
910     let mut output_types = HashMap::new();
911     if !debugging_opts.parse_only && !no_trans {
912         for list in matches.opt_strs("emit") {
913             for output_type in list.split(',') {
914                 let mut parts = output_type.splitn(2, '=');
915                 let output_type = match parts.next().unwrap() {
916                     "asm" => OutputType::Assembly,
917                     "llvm-ir" => OutputType::LlvmAssembly,
918                     "llvm-bc" => OutputType::Bitcode,
919                     "obj" => OutputType::Object,
920                     "link" => OutputType::Exe,
921                     "dep-info" => OutputType::DepInfo,
922                     part => {
923                         early_error(color, &format!("unknown emission type: `{}`",
924                                                     part))
925                     }
926                 };
927                 let path = parts.next().map(PathBuf::from);
928                 output_types.insert(output_type, path);
929             }
930         }
931     };
932     if output_types.is_empty() {
933         output_types.insert(OutputType::Exe, None);
934     }
935
936     let cg = build_codegen_options(matches, color);
937
938     let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
939     let target = matches.opt_str("target").unwrap_or(
940         host_triple().to_string());
941     let opt_level = {
942         if matches.opt_present("O") {
943             if cg.opt_level.is_some() {
944                 early_error(color, "-O and -C opt-level both provided");
945             }
946             Default
947         } else {
948             match cg.opt_level {
949                 None => No,
950                 Some(0) => No,
951                 Some(1) => Less,
952                 Some(2) => Default,
953                 Some(3) => Aggressive,
954                 Some(arg) => {
955                     early_error(color, &format!("optimization level needs to be \
956                                                  between 0-3 (instead was `{}`)",
957                                                 arg));
958                 }
959             }
960         }
961     };
962     let debug_assertions = cg.debug_assertions.unwrap_or(opt_level == No);
963     let gc = debugging_opts.gc;
964     let debuginfo = if matches.opt_present("g") {
965         if cg.debuginfo.is_some() {
966             early_error(color, "-g and -C debuginfo both provided");
967         }
968         FullDebugInfo
969     } else {
970         match cg.debuginfo {
971             None | Some(0) => NoDebugInfo,
972             Some(1) => LimitedDebugInfo,
973             Some(2) => FullDebugInfo,
974             Some(arg) => {
975                 early_error(color, &format!("debug info level needs to be between \
976                                              0-2 (instead was `{}`)",
977                                             arg));
978             }
979         }
980     };
981
982     let mut search_paths = SearchPaths::new();
983     for s in &matches.opt_strs("L") {
984         search_paths.add_path(&s[..], color);
985     }
986
987     let libs = matches.opt_strs("l").into_iter().map(|s| {
988         let mut parts = s.splitn(2, '=');
989         let kind = parts.next().unwrap();
990         let (name, kind) = match (parts.next(), kind) {
991             (None, name) |
992             (Some(name), "dylib") => (name, cstore::NativeUnknown),
993             (Some(name), "framework") => (name, cstore::NativeFramework),
994             (Some(name), "static") => (name, cstore::NativeStatic),
995             (_, s) => {
996                 early_error(color, &format!("unknown library kind `{}`, expected \
997                                              one of dylib, framework, or static",
998                                             s));
999             }
1000         };
1001         (name.to_string(), kind)
1002     }).collect();
1003
1004     let cfg = parse_cfgspecs(matches.opt_strs("cfg"));
1005     let test = matches.opt_present("test");
1006
1007     let prints = matches.opt_strs("print").into_iter().map(|s| {
1008         match &*s {
1009             "crate-name" => PrintRequest::CrateName,
1010             "file-names" => PrintRequest::FileNames,
1011             "sysroot" => PrintRequest::Sysroot,
1012             req => {
1013                 early_error(color, &format!("unknown print request `{}`", req))
1014             }
1015         }
1016     }).collect::<Vec<_>>();
1017
1018     if !cg.remark.is_empty() && debuginfo == NoDebugInfo {
1019         early_warn(color, "-C remark will not show source locations without \
1020                            --debuginfo");
1021     }
1022
1023     let mut externs = HashMap::new();
1024     for arg in &matches.opt_strs("extern") {
1025         let mut parts = arg.splitn(2, '=');
1026         let name = match parts.next() {
1027             Some(s) => s,
1028             None => early_error(color, "--extern value must not be empty"),
1029         };
1030         let location = match parts.next() {
1031             Some(s) => s,
1032             None => early_error(color, "--extern value must be of the format `foo=bar`"),
1033         };
1034
1035         externs.entry(name.to_string()).or_insert(vec![]).push(location.to_string());
1036     }
1037
1038     let crate_name = matches.opt_str("crate-name");
1039
1040     Options {
1041         crate_types: crate_types,
1042         gc: gc,
1043         optimize: opt_level,
1044         debuginfo: debuginfo,
1045         lint_opts: lint_opts,
1046         lint_cap: lint_cap,
1047         describe_lints: describe_lints,
1048         output_types: output_types,
1049         search_paths: search_paths,
1050         maybe_sysroot: sysroot_opt,
1051         target_triple: target,
1052         cfg: cfg,
1053         test: test,
1054         parse_only: parse_only,
1055         no_trans: no_trans,
1056         treat_err_as_bug: treat_err_as_bug,
1057         no_analysis: no_analysis,
1058         debugging_opts: debugging_opts,
1059         prints: prints,
1060         cg: cg,
1061         color: color,
1062         show_span: None,
1063         externs: externs,
1064         crate_name: crate_name,
1065         alt_std_name: None,
1066         libs: libs,
1067         unstable_features: get_unstable_features_setting(),
1068         debug_assertions: debug_assertions,
1069     }
1070 }
1071
1072 pub fn get_unstable_features_setting() -> UnstableFeatures {
1073     // Whether this is a feature-staged build, i.e. on the beta or stable channel
1074     let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
1075     // The secret key needed to get through the rustc build itself by
1076     // subverting the unstable features lints
1077     let bootstrap_secret_key = option_env!("CFG_BOOTSTRAP_KEY");
1078     // The matching key to the above, only known by the build system
1079     let bootstrap_provided_key = env::var("RUSTC_BOOTSTRAP_KEY").ok();
1080     match (disable_unstable_features, bootstrap_secret_key, bootstrap_provided_key) {
1081         (_, Some(ref s), Some(ref p)) if s == p => UnstableFeatures::Cheat,
1082         (true, _, _) => UnstableFeatures::Disallow,
1083         (false, _, _) => UnstableFeatures::Allow
1084     }
1085 }
1086
1087 pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
1088
1089     let mut crate_types: Vec<CrateType> = Vec::new();
1090     for unparsed_crate_type in &list_list {
1091         for part in unparsed_crate_type.split(',') {
1092             let new_part = match part {
1093                 "lib"       => default_lib_output(),
1094                 "rlib"      => CrateTypeRlib,
1095                 "staticlib" => CrateTypeStaticlib,
1096                 "dylib"     => CrateTypeDylib,
1097                 "bin"       => CrateTypeExecutable,
1098                 _ => {
1099                     return Err(format!("unknown crate type: `{}`",
1100                                        part));
1101                 }
1102             };
1103             if !crate_types.contains(&new_part) {
1104                 crate_types.push(new_part)
1105             }
1106         }
1107     }
1108
1109     return Ok(crate_types);
1110 }
1111
1112 impl fmt::Display for CrateType {
1113     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1114         match *self {
1115             CrateTypeExecutable => "bin".fmt(f),
1116             CrateTypeDylib => "dylib".fmt(f),
1117             CrateTypeRlib => "rlib".fmt(f),
1118             CrateTypeStaticlib => "staticlib".fmt(f)
1119         }
1120     }
1121 }
1122
1123 #[cfg(test)]
1124 mod tests {
1125
1126     use session::config::{build_configuration, optgroups, build_session_options};
1127     use session::build_session;
1128
1129     use getopts::getopts;
1130     use syntax::attr;
1131     use syntax::attr::AttrMetaMethods;
1132     use syntax::diagnostics;
1133
1134     // When the user supplies --test we should implicitly supply --cfg test
1135     #[test]
1136     fn test_switch_implies_cfg_test() {
1137         let matches =
1138             &match getopts(&["--test".to_string()], &optgroups()) {
1139               Ok(m) => m,
1140               Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
1141             };
1142         let registry = diagnostics::registry::Registry::new(&[]);
1143         let sessopts = build_session_options(matches);
1144         let sess = build_session(sessopts, None, registry);
1145         let cfg = build_configuration(&sess);
1146         assert!((attr::contains_name(&cfg[..], "test")));
1147     }
1148
1149     // When the user supplies --test and --cfg test, don't implicitly add
1150     // another --cfg test
1151     #[test]
1152     fn test_switch_implies_cfg_test_unless_cfg_test() {
1153         let matches =
1154             &match getopts(&["--test".to_string(), "--cfg=test".to_string()],
1155                            &optgroups()) {
1156               Ok(m) => m,
1157               Err(f) => {
1158                 panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
1159               }
1160             };
1161         let registry = diagnostics::registry::Registry::new(&[]);
1162         let sessopts = build_session_options(matches);
1163         let sess = build_session(sessopts, None, registry);
1164         let cfg = build_configuration(&sess);
1165         let mut test_items = cfg.iter().filter(|m| m.name() == "test");
1166         assert!(test_items.next().is_some());
1167         assert!(test_items.next().is_none());
1168     }
1169
1170     #[test]
1171     fn test_can_print_warnings() {
1172         {
1173             let matches = getopts(&[
1174                 "-Awarnings".to_string()
1175             ], &optgroups()).unwrap();
1176             let registry = diagnostics::registry::Registry::new(&[]);
1177             let sessopts = build_session_options(&matches);
1178             let sess = build_session(sessopts, None, registry);
1179             assert!(!sess.can_print_warnings);
1180         }
1181
1182         {
1183             let matches = getopts(&[
1184                 "-Awarnings".to_string(),
1185                 "-Dwarnings".to_string()
1186             ], &optgroups()).unwrap();
1187             let registry = diagnostics::registry::Registry::new(&[]);
1188             let sessopts = build_session_options(&matches);
1189             let sess = build_session(sessopts, None, registry);
1190             assert!(sess.can_print_warnings);
1191         }
1192
1193         {
1194             let matches = getopts(&[
1195                 "-Adead_code".to_string()
1196             ], &optgroups()).unwrap();
1197             let registry = diagnostics::registry::Registry::new(&[]);
1198             let sessopts = build_session_options(&matches);
1199             let sess = build_session(sessopts, None, registry);
1200             assert!(sess.can_print_warnings);
1201         }
1202     }
1203 }