]> git.lizzy.rs Git - rust.git/blob - src/librustc/driver/mod.rs
Use names in Lint structs in an ASCII-case-insensitive way
[rust.git] / src / librustc / driver / mod.rs
1 // Copyright 2012 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 pub use syntax::diagnostic;
12
13 use back::link;
14 use driver::driver::{Input, FileInput, StrInput};
15 use driver::session::{Session, build_session};
16 use lint::Lint;
17 use lint;
18 use metadata;
19
20 use std::any::AnyRefExt;
21 use std::io;
22 use std::os;
23 use std::str;
24 use std::task::TaskBuilder;
25
26 use syntax::ast;
27 use syntax::parse;
28 use syntax::diagnostic::Emitter;
29
30 use getopts;
31
32
33 pub mod driver;
34 pub mod session;
35 pub mod config;
36
37
38 pub fn main_args(args: &[String]) -> int {
39     let owned_args = args.to_owned();
40     monitor(proc() run_compiler(owned_args.as_slice()));
41     0
42 }
43
44 static BUG_REPORT_URL: &'static str =
45     "http://doc.rust-lang.org/complement-bugreport.html";
46
47 fn run_compiler(args: &[String]) {
48     let matches = match handle_options(Vec::from_slice(args)) {
49         Some(matches) => matches,
50         None => return
51     };
52     let sopts = config::build_session_options(&matches);
53
54     let (input, input_file_path) = match matches.free.len() {
55         0u => {
56             if sopts.describe_lints {
57                 let mut ls = lint::LintStore::new();
58                 ls.register_builtin(None);
59                 describe_lints(&ls);
60                 return;
61             }
62             early_error("no input filename given");
63         }
64         1u => {
65             let ifile = matches.free.get(0).as_slice();
66             if ifile == "-" {
67                 let contents = io::stdin().read_to_end().unwrap();
68                 let src = str::from_utf8(contents.as_slice()).unwrap()
69                                                              .to_string();
70                 (StrInput(src), None)
71             } else {
72                 (FileInput(Path::new(ifile)), Some(Path::new(ifile)))
73             }
74         }
75         _ => early_error("multiple input filenames provided")
76     };
77
78     let sess = build_session(sopts, input_file_path);
79     let cfg = config::build_configuration(&sess);
80     let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
81     let ofile = matches.opt_str("o").map(|o| Path::new(o));
82
83     let pretty = matches.opt_default("pretty", "normal").map(|a| {
84         parse_pretty(&sess, a.as_slice())
85     });
86     match pretty {
87         Some::<PpMode>(ppm) => {
88             driver::pretty_print_input(sess, cfg, &input, ppm, ofile);
89             return;
90         }
91         None::<PpMode> => {/* continue */ }
92     }
93
94     let r = matches.opt_strs("Z");
95     if r.contains(&("ls".to_string())) {
96         match input {
97             FileInput(ref ifile) => {
98                 let mut stdout = io::stdout();
99                 list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
100             }
101             StrInput(_) => {
102                 early_error("can not list metadata for stdin");
103             }
104         }
105         return;
106     }
107
108     if print_crate_info(&sess, &input, &odir, &ofile) {
109         return;
110     }
111
112     driver::compile_input(sess, cfg, &input, &odir, &ofile);
113 }
114
115 pub fn version(command: &str) {
116     let vers = match option_env!("CFG_VERSION") {
117         Some(vers) => vers,
118         None => "unknown version"
119     };
120     println!("{} {}", command, vers);
121     println!("host: {}", driver::host_triple());
122 }
123
124 fn usage() {
125     let message = format!("Usage: rustc [OPTIONS] INPUT");
126     println!("{}\n\
127 Additional help:
128     -C help             Print codegen options
129     -W help             Print 'lint' options and default settings
130     -Z help             Print internal options for debugging rustc\n",
131               getopts::usage(message.as_slice(),
132                              config::optgroups().as_slice()));
133 }
134
135 fn describe_lints(lint_store: &lint::LintStore) {
136     println!("
137 Available lint options:
138     -W <foo>           Warn about <foo>
139     -A <foo>           Allow <foo>
140     -D <foo>           Deny <foo>
141     -F <foo>           Forbid <foo> (deny, and deny all overrides)
142
143 ");
144
145     fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
146         let mut lints: Vec<_> = lints.move_iter().map(|(x, _)| x).collect();
147         lints.sort_by(|x: &&Lint, y: &&Lint| {
148             match x.default_level.cmp(&y.default_level) {
149                 // The sort doesn't case-fold but it's doubtful we care.
150                 Equal => x.name.cmp(&y.name),
151                 r => r,
152             }
153         });
154         lints
155     }
156
157     let (_plugin, builtin) = lint_store.get_lints().partitioned(|&(_, p)| p);
158     // let plugin = sort_lints(plugin);
159     let builtin = sort_lints(builtin);
160
161     // FIXME (#7043): We should use the width in character cells rather than
162     // the number of codepoints.
163     let max_name_len = builtin.iter()
164         .map(|&s| s.name.char_len())
165         .max().unwrap_or(0);
166     let padded = |x: &str| {
167         " ".repeat(max_name_len - x.char_len()).append(x)
168     };
169
170     println!("Lint checks provided by rustc:\n");
171     println!("    {}  {:7.7s}  {}", padded("name"), "default", "meaning");
172     println!("    {}  {:7.7s}  {}", padded("----"), "-------", "-------");
173
174     let print_lints = |lints: Vec<&Lint>| {
175         for lint in lints.move_iter() {
176             let name = lint.name_lower().replace("_", "-");
177             println!("    {}  {:7.7s}  {}",
178                 padded(name.as_slice()), lint.default_level.as_str(), lint.desc);
179         }
180         println!("\n");
181     };
182
183     print_lints(builtin);
184
185     // Describe lint plugins here once they exist.
186 }
187
188 fn describe_debug_flags() {
189     println!("\nAvailable debug options:\n");
190     let r = config::debugging_opts_map();
191     for tuple in r.iter() {
192         match *tuple {
193             (ref name, ref desc, _) => {
194                 println!("    -Z {:>20s} -- {}", *name, *desc);
195             }
196         }
197     }
198 }
199
200 fn describe_codegen_flags() {
201     println!("\nAvailable codegen options:\n");
202     let mut cg = config::basic_codegen_options();
203     for &(name, parser, desc) in config::CG_OPTIONS.iter() {
204         // we invoke the parser function on `None` to see if this option needs
205         // an argument or not.
206         let (width, extra) = if parser(&mut cg, None) {
207             (25, "")
208         } else {
209             (21, "=val")
210         };
211         println!("    -C {:>width$s}{} -- {}", name.replace("_", "-"),
212                  extra, desc, width=width);
213     }
214 }
215
216 /// Process command line options. Emits messages as appropriate. If compilation
217 /// should continue, returns a getopts::Matches object parsed from args, otherwise
218 /// returns None.
219 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
220     // Throw away the first argument, the name of the binary
221     let _binary = args.shift().unwrap();
222
223     if args.is_empty() {
224         usage();
225         return None;
226     }
227
228     let matches =
229         match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) {
230             Ok(m) => m,
231             Err(f) => {
232                 early_error(f.to_str().as_slice());
233             }
234         };
235
236     if matches.opt_present("h") || matches.opt_present("help") {
237         usage();
238         return None;
239     }
240
241     // Don't handle -W help here, because we might first load plugins.
242
243     let r = matches.opt_strs("Z");
244     if r.iter().any(|x| x.as_slice() == "help") {
245         describe_debug_flags();
246         return None;
247     }
248
249     let cg_flags = matches.opt_strs("C");
250     if cg_flags.iter().any(|x| x.as_slice() == "help") {
251         describe_codegen_flags();
252         return None;
253     }
254
255     if cg_flags.contains(&"passes=list".to_string()) {
256         unsafe { ::lib::llvm::llvm::LLVMRustPrintPasses(); }
257         return None;
258     }
259
260     if matches.opt_present("v") || matches.opt_present("version") {
261         version("rustc");
262         return None;
263     }
264
265     Some(matches)
266 }
267
268 fn print_crate_info(sess: &Session,
269                     input: &Input,
270                     odir: &Option<Path>,
271                     ofile: &Option<Path>)
272                     -> bool {
273     let (crate_id, crate_name, crate_file_name) = sess.opts.print_metas;
274     // these nasty nested conditions are to avoid doing extra work
275     if crate_id || crate_name || crate_file_name {
276         let attrs = parse_crate_attrs(sess, input);
277         let t_outputs = driver::build_output_filenames(input,
278                                                        odir,
279                                                        ofile,
280                                                        attrs.as_slice(),
281                                                        sess);
282         let id = link::find_crate_id(attrs.as_slice(),
283                                      t_outputs.out_filestem.as_slice());
284
285         if crate_id {
286             println!("{}", id.to_str());
287         }
288         if crate_name {
289             println!("{}", id.name);
290         }
291         if crate_file_name {
292             let crate_types = driver::collect_crate_types(sess, attrs.as_slice());
293             for &style in crate_types.iter() {
294                 let fname = link::filename_for_input(sess, style, &id,
295                                                      &t_outputs.with_extension(""));
296                 println!("{}", fname.filename_display());
297             }
298         }
299
300         true
301     } else {
302         false
303     }
304 }
305
306 pub enum PpMode {
307     PpmNormal,
308     PpmExpanded,
309     PpmTyped,
310     PpmIdentified,
311     PpmExpandedIdentified,
312     PpmFlowGraph(ast::NodeId),
313 }
314
315 pub fn parse_pretty(sess: &Session, name: &str) -> PpMode {
316     let mut split = name.splitn('=', 1);
317     let first = split.next().unwrap();
318     let opt_second = split.next();
319     match (opt_second, first) {
320         (None, "normal")       => PpmNormal,
321         (None, "expanded")     => PpmExpanded,
322         (None, "typed")        => PpmTyped,
323         (None, "expanded,identified") => PpmExpandedIdentified,
324         (None, "identified")   => PpmIdentified,
325         (arg, "flowgraph") => {
326              match arg.and_then(from_str) {
327                  Some(id) => PpmFlowGraph(id),
328                  None => {
329                      sess.fatal(format!("`pretty flowgraph=<nodeid>` needs \
330                                          an integer <nodeid>; got {}",
331                                         arg.unwrap_or("nothing")).as_slice())
332                  }
333              }
334         }
335         _ => {
336             sess.fatal(format!(
337                 "argument to `pretty` must be one of `normal`, \
338                  `expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
339                  or `expanded,identified`; got {}", name).as_slice());
340         }
341     }
342 }
343
344 fn parse_crate_attrs(sess: &Session, input: &Input) ->
345                      Vec<ast::Attribute> {
346     let result = match *input {
347         FileInput(ref ifile) => {
348             parse::parse_crate_attrs_from_file(ifile,
349                                                Vec::new(),
350                                                &sess.parse_sess)
351         }
352         StrInput(ref src) => {
353             parse::parse_crate_attrs_from_source_str(
354                 driver::anon_src().to_string(),
355                 src.to_string(),
356                 Vec::new(),
357                 &sess.parse_sess)
358         }
359     };
360     result.move_iter().collect()
361 }
362
363 pub fn early_error(msg: &str) -> ! {
364     let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto);
365     emitter.emit(None, msg, diagnostic::Fatal);
366     fail!(diagnostic::FatalError);
367 }
368
369 pub fn list_metadata(sess: &Session, path: &Path,
370                      out: &mut io::Writer) -> io::IoResult<()> {
371     metadata::loader::list_file_metadata(sess.targ_cfg.os, path, out)
372 }
373
374 /// Run a procedure which will detect failures in the compiler and print nicer
375 /// error messages rather than just failing the test.
376 ///
377 /// The diagnostic emitter yielded to the procedure should be used for reporting
378 /// errors of the compiler.
379 fn monitor(f: proc():Send) {
380     // FIXME: This is a hack for newsched since it doesn't support split stacks.
381     // rustc needs a lot of stack! When optimizations are disabled, it needs
382     // even *more* stack than usual as well.
383     #[cfg(rtopt)]
384     static STACK_SIZE: uint = 6000000;  // 6MB
385     #[cfg(not(rtopt))]
386     static STACK_SIZE: uint = 20000000; // 20MB
387
388     let (tx, rx) = channel();
389     let w = io::ChanWriter::new(tx);
390     let mut r = io::ChanReader::new(rx);
391
392     let mut task = TaskBuilder::new().named("rustc").stderr(box w);
393
394     // FIXME: Hacks on hacks. If the env is trying to override the stack size
395     // then *don't* set it explicitly.
396     if os::getenv("RUST_MIN_STACK").is_none() {
397         task = task.stack_size(STACK_SIZE);
398     }
399
400     match task.try(f) {
401         Ok(()) => { /* fallthrough */ }
402         Err(value) => {
403             // Task failed without emitting a fatal diagnostic
404             if !value.is::<diagnostic::FatalError>() {
405                 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto);
406
407                 // a .span_bug or .bug call has already printed what
408                 // it wants to print.
409                 if !value.is::<diagnostic::ExplicitBug>() {
410                     emitter.emit(
411                         None,
412                         "unexpected failure",
413                         diagnostic::Bug);
414                 }
415
416                 let xs = [
417                     "the compiler hit an unexpected failure path. this is a bug.".to_string(),
418                     format!("we would appreciate a bug report: {}",
419                             BUG_REPORT_URL),
420                     "run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
421                 ];
422                 for note in xs.iter() {
423                     emitter.emit(None, note.as_slice(), diagnostic::Note)
424                 }
425
426                 match r.read_to_str() {
427                     Ok(s) => println!("{}", s),
428                     Err(e) => {
429                         emitter.emit(None,
430                                      format!("failed to read internal \
431                                               stderr: {}",
432                                              e).as_slice(),
433                                      diagnostic::Error)
434                     }
435                 }
436             }
437
438             // Fail so the process returns a failure code, but don't pollute the
439             // output with some unnecessary failure messages, we've already
440             // printed everything that we needed to.
441             io::stdio::set_stderr(box io::util::NullWriter);
442             fail!();
443         }
444     }
445 }