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