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