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