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