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