]> git.lizzy.rs Git - rust.git/blob - src/mod.rs
Fix warnings in `cargo test`
[rust.git] / src / mod.rs
1 // Copyright 2015 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 #![feature(box_syntax)]
12 #![feature(box_patterns)]
13 #![feature(rustc_private)]
14 #![feature(collections)]
15 #![feature(str_char)]
16
17 #![cfg_attr(not(test), feature(exit_status))]
18
19 // TODO we're going to allocate a whole bunch of temp Strings, is it worth
20 // keeping some scratch mem for this and running our own StrPool?
21 // TODO for lint violations of names, emit a refactor script
22
23
24 #[macro_use]
25 extern crate log;
26
27 extern crate getopts;
28 extern crate rustc;
29 extern crate rustc_driver;
30 extern crate syntax;
31
32 extern crate strings;
33
34 use rustc::session::Session;
35 use rustc::session::config::{self, Input};
36 use rustc_driver::{driver, CompilerCalls, Compilation};
37
38 use syntax::ast;
39 use syntax::codemap::CodeMap;
40 use syntax::diagnostics;
41 use syntax::visit;
42
43 use std::path::PathBuf;
44 use std::collections::HashMap;
45
46 use changes::ChangeSet;
47 use visitor::FmtVisitor;
48
49 mod changes;
50 mod visitor;
51 mod functions;
52 mod missed_spans;
53 mod lists;
54 mod utils;
55 mod types;
56 mod expr;
57 mod imports;
58
59 const IDEAL_WIDTH: usize = 80;
60 const LEEWAY: usize = 5;
61 const MAX_WIDTH: usize = 100;
62 const MIN_STRING: usize = 10;
63 const TAB_SPACES: usize = 4;
64 const FN_BRACE_STYLE: BraceStyle = BraceStyle::SameLineWhere;
65 const FN_RETURN_INDENT: ReturnIndent = ReturnIndent::WithArgs;
66 // When we get scoped annotations, we should have rustfmt::skip.
67 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
68
69 #[derive(Copy, Clone)]
70 pub enum WriteMode {
71     Overwrite,
72     // str is the extension of the new file
73     NewFile(&'static str),
74     // Write the output to stdout.
75     Display,
76     // Return the result as a mapping from filenames to StringBuffers.
77     Return(&'static Fn(HashMap<String, String>)),
78 }
79
80 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
81 enum BraceStyle {
82     AlwaysNextLine,
83     PreferSameLine,
84     // Prefer same line except where there is a where clause, in which case force
85     // the brace to the next line.
86     SameLineWhere,
87 }
88
89 // How to indent a function's return type.
90 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
91 enum ReturnIndent {
92     // Aligned with the arguments
93     WithArgs,
94     // Aligned with the where clause
95     WithWhereClause,
96 }
97
98 // Formatting which depends on the AST.
99 fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap) -> ChangeSet<'a> {
100     let mut visitor = FmtVisitor::from_codemap(codemap);
101     visit::walk_crate(&mut visitor, krate);
102     let files = codemap.files.borrow();
103     if let Some(last) = files.last() {
104         visitor.format_missing(last.end_pos);
105     }
106
107     visitor.changes
108 }
109
110 // Formatting done on a char by char or line by line basis.
111 // TODO warn on TODOs and FIXMEs without an issue number
112 // TODO warn on bad license
113 // TODO other stuff for parity with make tidy
114 fn fmt_lines(changes: &mut ChangeSet) {
115     let mut truncate_todo = Vec::new();
116
117     // Iterate over the chars in the change set.
118     for (f, text) in changes.text() {
119         let mut trims = vec![];
120         let mut last_wspace: Option<usize> = None;
121         let mut line_len = 0;
122         let mut cur_line = 1;
123         let mut newline_count = 0;
124         for (c, b) in text.chars() {
125             if c == '\n' { // TOOD test for \r too
126                 // Check for (and record) trailing whitespace.
127                 if let Some(lw) = last_wspace {
128                     trims.push((cur_line, lw, b));
129                     line_len -= b - lw;
130                 }
131                 // Check for any line width errors we couldn't correct.
132                 if line_len > MAX_WIDTH {
133                     // TODO store the error rather than reporting immediately.
134                     println!("Rustfmt couldn't fix (sorry). {}:{}: line longer than {} characters",
135                              f, cur_line, MAX_WIDTH);
136                 }
137                 line_len = 0;
138                 cur_line += 1;
139                 newline_count += 1;
140                 last_wspace = None;
141             } else {
142                 newline_count = 0;
143                 line_len += 1;
144                 if c.is_whitespace() {
145                     if last_wspace.is_none() {
146                         last_wspace = Some(b);
147                     }
148                 } else {
149                     last_wspace = None;
150                 }
151             }
152         }
153
154         if newline_count > 1 {
155             debug!("track truncate: {} {} {}", f, text.len, newline_count);
156             truncate_todo.push((f, text.len - newline_count + 1))
157         }
158
159         for &(l, _, _) in trims.iter() {
160             // TODO store the error rather than reporting immediately.
161             println!("Rustfmt left trailing whitespace at {}:{} (sorry)", f, l);
162         }
163     }
164
165     for (f, l) in truncate_todo {
166         // This unsafe block and the ridiculous dance with the cast is because
167         // the borrow checker thinks the first borrow of changes lasts for the
168         // whole function.
169         unsafe {
170             (*(changes as *const ChangeSet as *mut ChangeSet)).get_mut(f).truncate(l);
171         }
172     }
173 }
174
175 struct RustFmtCalls {
176     input_path: Option<PathBuf>,
177     write_mode: WriteMode,
178 }
179
180 impl<'a> CompilerCalls<'a> for RustFmtCalls {
181     fn early_callback(&mut self,
182                       _: &getopts::Matches,
183                       _: &diagnostics::registry::Registry)
184                       -> Compilation {
185         Compilation::Continue
186     }
187
188     fn some_input(&mut self,
189                   input: Input,
190                   input_path: Option<PathBuf>)
191                   -> (Input, Option<PathBuf>) {
192         match input_path {
193             Some(ref ip) => self.input_path = Some(ip.clone()),
194             _ => {
195                 // FIXME should handle string input and write to stdout or something
196                 panic!("No input path");
197             }
198         }
199         (input, input_path)
200     }
201
202     fn no_input(&mut self,
203                 _: &getopts::Matches,
204                 _: &config::Options,
205                 _: &Option<PathBuf>,
206                 _: &Option<PathBuf>,
207                 _: &diagnostics::registry::Registry)
208                 -> Option<(Input, Option<PathBuf>)> {
209         panic!("No input supplied to RustFmt");
210     }
211
212     fn late_callback(&mut self,
213                      _: &getopts::Matches,
214                      _: &Session,
215                      _: &Input,
216                      _: &Option<PathBuf>,
217                      _: &Option<PathBuf>)
218                      -> Compilation {
219         Compilation::Continue
220     }
221
222     fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
223         let write_mode = self.write_mode;
224         let mut control = driver::CompileController::basic();
225         control.after_parse.stop = Compilation::Stop;
226         control.after_parse.callback = box move |state| {
227             let krate = state.krate.unwrap();
228             let codemap = state.session.codemap();
229             let mut changes = fmt_ast(krate, codemap);
230             // For some reason, the codemap does not include terminating newlines
231             // so we must add one on for each file. This is sad.
232             changes.append_newlines();
233             fmt_lines(&mut changes);
234
235             // FIXME(#5) Should be user specified whether to show or replace.
236             let result = changes.write_all_files(write_mode);
237
238             match result {
239                 Err(msg) => println!("Error writing files: {}", msg),
240                 Ok(result) => {
241                     if let WriteMode::Return(callback) = write_mode {
242                         callback(result);
243                     }
244                 }
245             }
246         };
247
248         control
249     }
250 }
251
252 fn run(args: Vec<String>, write_mode: WriteMode) {
253     let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode };
254     rustc_driver::run_compiler(&args, &mut call_ctxt);
255 }
256
257 #[cfg(not(test))]
258 fn main() {
259     let args: Vec<_> = std::env::args().collect();
260     //run(args, WriteMode::Display);
261     run(args, WriteMode::Overwrite);
262     std::env::set_exit_status(0);
263
264     // TODO unit tests
265     // let fmt = ListFormatting {
266     //     tactic: ListTactic::Horizontal,
267     //     separator: ",",
268     //     trailing_separator: SeparatorTactic::Vertical,
269     //     indent: 2,
270     //     h_width: 80,
271     //     v_width: 100,
272     // };
273     // let inputs = vec![(format!("foo"), String::new()),
274     //                   (format!("foo"), String::new()),
275     //                   (format!("foo"), String::new()),
276     //                   (format!("foo"), String::new()),
277     //                   (format!("foo"), String::new()),
278     //                   (format!("foo"), String::new()),
279     //                   (format!("foo"), String::new()),
280     //                   (format!("foo"), String::new())];
281     // let s = write_list(&inputs, &fmt);
282     // println!("  {}", s);
283 }
284
285
286 #[cfg(test)]
287 mod test {
288     use std::collections::HashMap;
289     use std::fs;
290     use std::io::Read;
291     use super::*;
292     use super::run;
293
294     // For now, the only supported regression tests are idempotent tests - the input and
295     // output must match exactly.
296     // FIXME(#28) would be good to check for error messages and fail on them, or at least report.
297     #[test]
298     fn idempotent_tests() {
299         println!("Idempotent tests:");
300         unsafe { FAILURES = 0; }
301
302         // Get all files in the tests/idem directory
303         let files = fs::read_dir("tests/idem").unwrap();
304         // For each file, run rustfmt and collect the output
305         let mut count = 0;
306         for entry in files {
307             let path = entry.unwrap().path();
308             let file_name = path.to_str().unwrap();
309             println!("Testing '{}'...", file_name);
310             run(vec!["rustfmt".to_string(), file_name.to_string()], WriteMode::Return(HANDLE_RESULT));
311             count += 1;
312         }
313         // And also dogfood ourselves!
314         println!("Testing 'src/mod.rs'...");
315         run(vec!["rustfmt".to_string(), "src/mod.rs".to_string()], WriteMode::Return(HANDLE_RESULT));
316         count += 1;
317
318         // Display results
319         let fails = unsafe { FAILURES };
320         println!("Ran {} idempotent tests; {} failures.", count, fails);
321         assert!(fails == 0, "{} idempotent tests failed", fails);
322     }
323
324     // 'global' used by sys_tests and handle_result.
325     static mut FAILURES: i32 = 0;
326     // Ick, just needed to get a &'static to handle_result.
327     static HANDLE_RESULT: &'static Fn(HashMap<String, String>) = &handle_result;
328
329     // Compare output to input.
330     fn handle_result(result: HashMap<String, String>) {
331         let mut fails = 0;
332
333         for file_name in result.keys() {
334             let mut f = fs::File::open(file_name).unwrap();
335             let mut text = String::new();
336             f.read_to_string(&mut text).unwrap();
337             if result[file_name] != text {
338                 fails += 1;
339                 println!("Mismatch in {}.", file_name);
340                 println!("{}", result[file_name]);
341             }
342         }
343
344         if fails > 0 {
345             unsafe {
346                 FAILURES += 1;
347             }
348         }
349     }
350 }