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)]
15 #![feature(exit_status)]
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
28 extern crate rustc_driver;
33 use rustc::session::Session;
34 use rustc::session::config::{self, Input};
35 use rustc_driver::{driver, CompilerCalls, Compilation};
38 use syntax::codemap::CodeMap;
39 use syntax::diagnostics;
42 use std::path::PathBuf;
43 use std::collections::HashMap;
45 use changes::ChangeSet;
46 use visitor::FmtVisitor;
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";
68 #[derive(Copy, Clone)]
71 // str is the extension of the new file
72 NewFile(&'static str),
73 // Write the output to stdout.
75 // Return the result as a mapping from filenames to StringBuffers.
76 Return(&'static Fn(HashMap<String, String>)),
79 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
83 // Prefer same line except where there is a where clause, in which case force
84 // the brace to the next line.
88 // How to indent a function's return type.
89 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
91 // Aligned with the arguments
93 // Aligned with the where clause
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);
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();
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));
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);
143 if c.is_whitespace() {
144 if last_wspace.is_none() {
145 last_wspace = Some(b);
153 if newline_count > 1 {
154 debug!("track truncate: {} {} {}", f, text.len, newline_count);
155 truncate_todo.push((f, text.len - newline_count + 1))
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);
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
169 (*(changes as *const ChangeSet as *mut ChangeSet)).get_mut(f).truncate(l);
174 struct RustFmtCalls {
175 input_path: Option<PathBuf>,
176 write_mode: WriteMode,
179 impl<'a> CompilerCalls<'a> for RustFmtCalls {
180 fn early_callback(&mut self,
181 _: &getopts::Matches,
182 _: &diagnostics::registry::Registry)
184 Compilation::Continue
187 fn some_input(&mut self,
189 input_path: Option<PathBuf>)
190 -> (Input, Option<PathBuf>) {
192 Some(ref ip) => self.input_path = Some(ip.clone()),
194 // FIXME should handle string input and write to stdout or something
195 panic!("No input path");
201 fn no_input(&mut self,
202 _: &getopts::Matches,
206 _: &diagnostics::registry::Registry)
207 -> Option<(Input, Option<PathBuf>)> {
208 panic!("No input supplied to RustFmt");
211 fn late_callback(&mut self,
212 _: &getopts::Matches,
218 Compilation::Continue
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);
234 // FIXME(#5) Should be user specified whether to show or replace.
235 let result = changes.write_all_files(write_mode);
238 Err(msg) => println!("Error writing files: {}", msg),
240 if let WriteMode::Return(callback) = write_mode {
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);
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);
263 // let fmt = ListFormatting {
264 // tactic: ListTactic::Horizontal,
266 // trailing_separator: SeparatorTactic::Vertical,
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);
286 use std::collections::HashMap;
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.
296 fn idempotent_tests() {
297 println!("Idempotent tests:");
298 unsafe { FAILURES = 0; }
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
305 let path = entry.unwrap().path();
306 let file_name = path.to_str().unwrap();
307 println!("Testing '{}'...", file_name);
308 run(vec!["rustfmt".to_string(), file_name.to_string()], WriteMode::Return(HANDLE_RESULT));
311 // And also dogfood ourselves!
312 println!("Testing 'src/mod.rs'...");
313 run(vec!["rustfmt".to_string(), "src/mod.rs".to_string()], WriteMode::Return(HANDLE_RESULT));
317 let fails = unsafe { FAILURES };
318 println!("Ran {} idempotent tests; {} failures.", count, fails);
319 assert!(fails == 0, "{} idempotent tests failed", fails);
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;
327 // Compare output to input.
328 fn handle_result(result: HashMap<String, String>) {
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 {
337 println!("Mismatch in {}.", file_name);
338 println!("{}", result[file_name]);