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