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.
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.
11 #![feature(box_syntax)]
12 #![feature(box_patterns)]
13 #![feature(rustc_private)]
14 #![feature(collections)]
17 #![cfg_attr(not(test), feature(exit_status))]
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
29 extern crate rustc_driver;
34 use rustc::session::Session;
35 use rustc::session::config::{self, Input};
36 use rustc_driver::{driver, CompilerCalls, Compilation};
39 use syntax::codemap::CodeMap;
40 use syntax::diagnostics;
43 use std::path::PathBuf;
44 use std::collections::HashMap;
46 use changes::ChangeSet;
47 use visitor::FmtVisitor;
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";
69 #[derive(Copy, Clone)]
72 // str is the extension of the new file
73 NewFile(&'static str),
74 // Write the output to stdout.
76 // Return the result as a mapping from filenames to StringBuffers.
77 Return(&'static Fn(HashMap<String, String>)),
80 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
84 // Prefer same line except where there is a where clause, in which case force
85 // the brace to the next line.
89 // How to indent a function's return type.
90 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
92 // Aligned with the arguments
94 // Aligned with the where clause
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);
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();
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));
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);
144 if c.is_whitespace() {
145 if last_wspace.is_none() {
146 last_wspace = Some(b);
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))
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);
165 for (f, l) in truncate_todo {
166 changes.get_mut(&f).truncate(l);
170 struct RustFmtCalls {
171 input_path: Option<PathBuf>,
172 write_mode: WriteMode,
175 impl<'a> CompilerCalls<'a> for RustFmtCalls {
176 fn early_callback(&mut self,
177 _: &getopts::Matches,
178 _: &diagnostics::registry::Registry)
180 Compilation::Continue
183 fn some_input(&mut self,
185 input_path: Option<PathBuf>)
186 -> (Input, Option<PathBuf>) {
188 Some(ref ip) => self.input_path = Some(ip.clone()),
190 // FIXME should handle string input and write to stdout or something
191 panic!("No input path");
197 fn no_input(&mut self,
198 _: &getopts::Matches,
202 _: &diagnostics::registry::Registry)
203 -> Option<(Input, Option<PathBuf>)> {
204 panic!("No input supplied to RustFmt");
207 fn late_callback(&mut self,
208 _: &getopts::Matches,
214 Compilation::Continue
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);
230 // FIXME(#5) Should be user specified whether to show or replace.
231 let result = changes.write_all_files(write_mode);
234 Err(msg) => println!("Error writing files: {}", msg),
236 if let WriteMode::Return(callback) = write_mode {
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);
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);
260 // let fmt = ListFormatting {
261 // tactic: ListTactic::Horizontal,
263 // trailing_separator: SeparatorTactic::Vertical,
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);
283 use std::collections::HashMap;
286 use std::sync::atomic;
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.
294 fn idempotent_tests() {
295 println!("Idempotent tests:");
296 FAILURES.store(0, atomic::Ordering::Relaxed);
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
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));
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));
316 let fails = FAILURES.load(atomic::Ordering::Relaxed);
317 println!("Ran {} idempotent tests; {} failures.", count, fails);
318 assert!(fails == 0, "{} idempotent tests failed", fails);
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;
326 // Compare output to input.
327 fn handle_result(result: HashMap<String, String>) {
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 {
336 println!("Mismatch in {}.", file_name);
337 println!("{}", result[file_name]);
342 FAILURES.fetch_add(1, atomic::Ordering::Relaxed);