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
23 // annotations/doc comments
24 // Fix fns and methods properly
25 // dead spans (comments) - in where clause - test
27 // Smoke testing till we can use it
28 // take config options from a file
35 extern crate rustc_driver;
40 use rustc::session::Session;
41 use rustc::session::config::{self, Input};
42 use rustc_driver::{driver, CompilerCalls, Compilation};
45 use syntax::codemap::CodeMap;
46 use syntax::diagnostics;
49 use std::path::PathBuf;
50 use std::collections::HashMap;
52 use changes::ChangeSet;
53 use visitor::FmtVisitor;
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::WithArgs;
72 // When we get scoped annotations, we should have rustfmt::skip.
73 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
75 #[derive(Copy, Clone)]
78 // str is the extension of the new file
79 NewFile(&'static str),
80 // Write the output to stdout.
82 // Return the result as a mapping from filenames to StringBuffers.
83 Return(&'static Fn(HashMap<String, String>)),
86 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
90 // Prefer same line except where there is a where clause, in which case force
91 // the brace to the next line.
95 // How to indent a function's return type.
96 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
98 // Aligned with the arguments
100 // Aligned with the where clause
104 // Formatting which depends on the AST.
105 fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap) -> ChangeSet<'a> {
106 let mut visitor = FmtVisitor::from_codemap(codemap);
107 visit::walk_crate(&mut visitor, krate);
108 let files = codemap.files.borrow();
109 if let Some(last) = files.last() {
110 visitor.format_missing(last.end_pos);
116 // Formatting done on a char by char or line by line basis.
117 // TODO warn on TODOs and FIXMEs without an issue number
118 // TODO warn on bad license
119 // TODO other stuff for parity with make tidy
120 fn fmt_lines(changes: &mut ChangeSet) {
121 let mut truncate_todo = Vec::new();
123 // Iterate over the chars in the change set.
124 for (f, text) in changes.text() {
125 let mut trims = vec![];
126 let mut last_wspace: Option<usize> = None;
127 let mut line_len = 0;
128 let mut cur_line = 1;
129 let mut newline_count = 0;
130 for (c, b) in text.chars() {
131 if c == '\n' { // TOOD test for \r too
132 // Check for (and record) trailing whitespace.
133 if let Some(lw) = last_wspace {
134 trims.push((cur_line, lw, b));
137 // Check for any line width errors we couldn't correct.
138 if line_len > MAX_WIDTH {
139 // TODO store the error rather than reporting immediately.
140 println!("Rustfmt couldn't fix (sorry). {}:{}: line longer than {} characters",
141 f, cur_line, MAX_WIDTH);
150 if c.is_whitespace() {
151 if last_wspace.is_none() {
152 last_wspace = Some(b);
160 if newline_count > 1 {
161 debug!("track truncate: {} {} {}", f, text.len, newline_count);
162 truncate_todo.push((f, text.len - newline_count + 1))
165 for &(l, _, _) in trims.iter() {
166 // TODO store the error rather than reporting immediately.
167 println!("Rustfmt left trailing whitespace at {}:{} (sorry)", f, l);
171 for (f, l) in truncate_todo {
172 // This unsafe block and the ridiculous dance with the cast is because
173 // the borrow checker thinks the first borrow of changes lasts for the
176 (*(changes as *const ChangeSet as *mut ChangeSet)).get_mut(f).truncate(l);
181 struct RustFmtCalls {
182 input_path: Option<PathBuf>,
183 write_mode: WriteMode,
186 impl<'a> CompilerCalls<'a> for RustFmtCalls {
187 fn early_callback(&mut self,
188 _: &getopts::Matches,
189 _: &diagnostics::registry::Registry)
191 Compilation::Continue
194 fn some_input(&mut self,
196 input_path: Option<PathBuf>)
197 -> (Input, Option<PathBuf>) {
199 Some(ref ip) => self.input_path = Some(ip.clone()),
201 // FIXME should handle string input and write to stdout or something
202 panic!("No input path");
208 fn no_input(&mut self,
209 _: &getopts::Matches,
213 _: &diagnostics::registry::Registry)
214 -> Option<(Input, Option<PathBuf>)> {
215 panic!("No input supplied to RustFmt");
218 fn late_callback(&mut self,
219 _: &getopts::Matches,
225 Compilation::Continue
228 fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
229 let write_mode = self.write_mode;
230 let mut control = driver::CompileController::basic();
231 control.after_parse.stop = Compilation::Stop;
232 control.after_parse.callback = box move |state| {
233 let krate = state.krate.unwrap();
234 let codemap = state.session.codemap();
235 let mut changes = fmt_ast(krate, codemap);
236 // For some reason, the codemap does not include terminating newlines
237 // so we must add one on for each file. This is sad.
238 changes.append_newlines();
239 fmt_lines(&mut changes);
241 // FIXME(#5) Should be user specified whether to show or replace.
242 let result = changes.write_all_files(write_mode);
245 Err(msg) => println!("Error writing files: {}", msg),
247 if let WriteMode::Return(callback) = write_mode {
258 fn run(args: Vec<String>, write_mode: WriteMode) {
259 let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode };
260 rustc_driver::run_compiler(&args, &mut call_ctxt);
264 let args: Vec<_> = std::env::args().collect();
265 //run(args, WriteMode::Display);
266 run(args, WriteMode::Overwrite);
267 std::env::set_exit_status(0);
270 // let fmt = ListFormatting {
271 // tactic: ListTactic::Horizontal,
273 // trailing_separator: SeparatorTactic::Vertical,
278 // let inputs = vec![(format!("foo"), String::new()),
279 // (format!("foo"), String::new()),
280 // (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 // let s = write_list(&inputs, &fmt);
287 // println!(" {}", s);
291 // comments aren't in the AST, which makes processing them difficult, but then
292 // comments are complicated anyway. I think I am happy putting off tackling them
293 // for now. Long term the soluton is for comments to be in the AST, but that means
294 // only the libsyntax AST, not the rustc one, which means waiting for the ASTs
295 // to diverge one day....
297 // Once we do have comments, we just have to implement a simple word wrapping
298 // algorithm to keep the width under IDEAL_WIDTH. We should also convert multiline
299 // /* ... */ comments to // and check doc comments are in the right place and of
302 // Should also make sure comments have the right indent
306 use std::collections::HashMap;
312 // For now, the only supported regression tests are idempotent tests - the input and
313 // output must match exactly.
314 // TODO would be good to check for error messages and fail on them, or at least report.
316 fn idempotent_tests() {
317 println!("Idempotent tests:");
318 unsafe { FAILURES = 0; }
320 // Get all files in the tests/idem directory
321 let files = fs::read_dir("tests/idem").unwrap();
322 // For each file, run rustfmt and collect the output
325 let path = entry.unwrap().path();
326 let file_name = path.to_str().unwrap();
327 println!("Testing '{}'...", file_name);
328 run(vec!["rustfmt".to_string(), file_name.to_string()], WriteMode::Return(HANDLE_RESULT));
331 // And also dogfood ourselves!
332 println!("Testing 'src/mod.rs'...");
333 run(vec!["rustfmt".to_string(), "src/mod.rs".to_string()], WriteMode::Return(HANDLE_RESULT));
337 let fails = unsafe { FAILURES };
338 println!("Ran {} idempotent tests; {} failures.", count, fails);
339 assert!(fails == 0, "{} idempotent tests failed", fails);
342 // 'global' used by sys_tests and handle_result.
343 static mut FAILURES: i32 = 0;
344 // Ick, just needed to get a &'static to handle_result.
345 static HANDLE_RESULT: &'static Fn(HashMap<String, String>) = &handle_result;
347 // Compare output to input.
348 fn handle_result(result: HashMap<String, String>) {
351 for file_name in result.keys() {
352 let mut f = fs::File::open(file_name).unwrap();
353 let mut text = String::new();
354 f.read_to_string(&mut text).unwrap();
355 if result[file_name] != text {
357 println!("Mismatch in {}.", file_name);
358 println!("{}", result[file_name]);