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