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