]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
main.rs -> lib.rs
[rust.git] / src / lib.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.to_string(), 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         changes.get_mut(&f).truncate(l);
167     }
168 }
169
170 struct RustFmtCalls {
171     input_path: Option<PathBuf>,
172     write_mode: WriteMode,
173 }
174
175 impl<'a> CompilerCalls<'a> for RustFmtCalls {
176     fn early_callback(&mut self,
177                       _: &getopts::Matches,
178                       _: &diagnostics::registry::Registry)
179                       -> Compilation {
180         Compilation::Continue
181     }
182
183     fn some_input(&mut self,
184                   input: Input,
185                   input_path: Option<PathBuf>)
186                   -> (Input, Option<PathBuf>) {
187         match input_path {
188             Some(ref ip) => self.input_path = Some(ip.clone()),
189             _ => {
190                 // FIXME should handle string input and write to stdout or something
191                 panic!("No input path");
192             }
193         }
194         (input, input_path)
195     }
196
197     fn no_input(&mut self,
198                 _: &getopts::Matches,
199                 _: &config::Options,
200                 _: &Option<PathBuf>,
201                 _: &Option<PathBuf>,
202                 _: &diagnostics::registry::Registry)
203                 -> Option<(Input, Option<PathBuf>)> {
204         panic!("No input supplied to RustFmt");
205     }
206
207     fn late_callback(&mut self,
208                      _: &getopts::Matches,
209                      _: &Session,
210                      _: &Input,
211                      _: &Option<PathBuf>,
212                      _: &Option<PathBuf>)
213                      -> Compilation {
214         Compilation::Continue
215     }
216
217     fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
218         let write_mode = self.write_mode;
219         let mut control = driver::CompileController::basic();
220         control.after_parse.stop = Compilation::Stop;
221         control.after_parse.callback = box move |state| {
222             let krate = state.krate.unwrap();
223             let codemap = state.session.codemap();
224             let mut changes = fmt_ast(krate, codemap);
225             // For some reason, the codemap does not include terminating newlines
226             // so we must add one on for each file. This is sad.
227             changes.append_newlines();
228             fmt_lines(&mut changes);
229
230             // FIXME(#5) Should be user specified whether to show or replace.
231             let result = changes.write_all_files(write_mode);
232
233             match result {
234                 Err(msg) => println!("Error writing files: {}", msg),
235                 Ok(result) => {
236                     if let WriteMode::Return(callback) = write_mode {
237                         callback(result);
238                     }
239                 }
240             }
241         };
242
243         control
244     }
245 }
246
247 fn run(args: Vec<String>, write_mode: WriteMode) {
248     let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode };
249     rustc_driver::run_compiler(&args, &mut call_ctxt);
250 }
251
252 #[cfg(not(test))]
253 fn main() {
254     let args: Vec<_> = std::env::args().collect();
255     //run(args, WriteMode::Display);
256     run(args, WriteMode::Overwrite);
257     std::env::set_exit_status(0);
258
259     // TODO unit tests
260     // let fmt = ListFormatting {
261     //     tactic: ListTactic::Horizontal,
262     //     separator: ",",
263     //     trailing_separator: SeparatorTactic::Vertical,
264     //     indent: 2,
265     //     h_width: 80,
266     //     v_width: 100,
267     // };
268     // let inputs = vec![(format!("foo"), String::new()),
269     //                   (format!("foo"), String::new()),
270     //                   (format!("foo"), String::new()),
271     //                   (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     // let s = write_list(&inputs, &fmt);
277     // println!("  {}", s);
278 }
279
280
281 #[cfg(test)]
282 mod test {
283     use std::collections::HashMap;
284     use std::fs;
285     use std::io::Read;
286     use std::sync::atomic;
287     use super::*;
288     use super::run;
289
290     // For now, the only supported regression tests are idempotent tests - the input and
291     // output must match exactly.
292     // FIXME(#28) would be good to check for error messages and fail on them, or at least report.
293     #[test]
294     fn idempotent_tests() {
295         println!("Idempotent tests:");
296         FAILURES.store(0, atomic::Ordering::Relaxed);
297
298         // Get all files in the tests/idem directory
299         let files = fs::read_dir("tests/idem").unwrap();
300         // For each file, run rustfmt and collect the output
301         let mut count = 0;
302         for entry in files {
303             let path = entry.unwrap().path();
304             let file_name = path.to_str().unwrap();
305             println!("Testing '{}'...", file_name);
306             run(vec!["rustfmt".to_owned(), file_name.to_owned()], WriteMode::Return(HANDLE_RESULT));
307             count += 1;
308         }
309         // And also dogfood ourselves!
310         println!("Testing 'src/main.rs'...");
311         run(vec!["rustfmt".to_string(), "src/main.rs".to_string()],
312             WriteMode::Return(HANDLE_RESULT));
313         count += 1;
314
315         // Display results
316         let fails = FAILURES.load(atomic::Ordering::Relaxed);
317         println!("Ran {} idempotent tests; {} failures.", count, fails);
318         assert!(fails == 0, "{} idempotent tests failed", fails);
319     }
320
321     // 'global' used by sys_tests and handle_result.
322     static FAILURES: atomic::AtomicUsize = atomic::ATOMIC_USIZE_INIT;
323     // Ick, just needed to get a &'static to handle_result.
324     static HANDLE_RESULT: &'static Fn(HashMap<String, String>) = &handle_result;
325
326     // Compare output to input.
327     fn handle_result(result: HashMap<String, String>) {
328         let mut fails = 0;
329
330         for file_name in result.keys() {
331             let mut f = fs::File::open(file_name).unwrap();
332             let mut text = String::new();
333             f.read_to_string(&mut text).unwrap();
334             if result[file_name] != text {
335                 fails += 1;
336                 println!("Mismatch in {}.", file_name);
337                 println!("{}", result[file_name]);
338             }
339         }
340
341         if fails > 0 {
342             FAILURES.fetch_add(1, atomic::Ordering::Relaxed);
343         }
344     }
345 }