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 // Fix fns and methods properly
24 // dead spans (comments) - in where clause (wait for fixed spans, test)
26 // Smoke testing till we can use it
27 // take config options from a file
34 extern crate rustc_driver;
39 use rustc::session::Session;
40 use rustc::session::config::{self, Input};
41 use rustc_driver::{driver, CompilerCalls, Compilation};
44 use syntax::codemap::CodeMap;
45 use syntax::diagnostics;
48 use std::path::PathBuf;
49 use std::collections::HashMap;
51 use changes::ChangeSet;
52 use visitor::FmtVisitor;
64 const IDEAL_WIDTH: usize = 80;
65 const LEEWAY: usize = 5;
66 const MAX_WIDTH: usize = 100;
67 const MIN_STRING: usize = 10;
68 const TAB_SPACES: usize = 4;
69 const FN_BRACE_STYLE: BraceStyle = BraceStyle::SameLineWhere;
70 const FN_RETURN_INDENT: ReturnIndent = ReturnIndent::WithArgs;
71 // When we get scoped annotations, we should have rustfmt::skip.
72 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
74 #[derive(Copy, Clone)]
77 // str is the extension of the new file
78 NewFile(&'static str),
79 // Write the output to stdout.
81 // Return the result as a mapping from filenames to StringBuffers.
82 Return(&'static Fn(HashMap<String, String>)),
85 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
89 // Prefer same line except where there is a where clause, in which case force
90 // the brace to the next line.
94 // How to indent a function's return type.
95 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
97 // Aligned with the arguments
99 // Aligned with the where clause
103 // Formatting which depends on the AST.
104 fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap) -> ChangeSet<'a> {
105 let mut visitor = FmtVisitor::from_codemap(codemap);
106 visit::walk_crate(&mut visitor, krate);
107 let files = codemap.files.borrow();
108 if let Some(last) = files.last() {
109 visitor.format_missing(last.end_pos);
115 // Formatting done on a char by char or line by line basis.
116 // TODO warn on TODOs and FIXMEs without an issue number
117 // TODO warn on bad license
118 // TODO other stuff for parity with make tidy
119 fn fmt_lines(changes: &mut ChangeSet) {
120 let mut truncate_todo = Vec::new();
122 // Iterate over the chars in the change set.
123 for (f, text) in changes.text() {
124 let mut trims = vec![];
125 let mut last_wspace: Option<usize> = None;
126 let mut line_len = 0;
127 let mut cur_line = 1;
128 let mut newline_count = 0;
129 for (c, b) in text.chars() {
130 if c == '\n' { // TOOD test for \r too
131 // Check for (and record) trailing whitespace.
132 if let Some(lw) = last_wspace {
133 trims.push((cur_line, lw, b));
136 // Check for any line width errors we couldn't correct.
137 if line_len > MAX_WIDTH {
138 // TODO store the error rather than reporting immediately.
139 println!("Rustfmt couldn't fix (sorry). {}:{}: line longer than {} characters",
140 f, cur_line, MAX_WIDTH);
149 if c.is_whitespace() {
150 if last_wspace.is_none() {
151 last_wspace = Some(b);
159 if newline_count > 1 {
160 debug!("track truncate: {} {} {}", f, text.len, newline_count);
161 truncate_todo.push((f, text.len - newline_count + 1))
164 for &(l, _, _) in trims.iter() {
165 // TODO store the error rather than reporting immediately.
166 println!("Rustfmt left trailing whitespace at {}:{} (sorry)", f, l);
170 for (f, l) in truncate_todo {
171 // This unsafe block and the ridiculous dance with the cast is because
172 // the borrow checker thinks the first borrow of changes lasts for the
175 (*(changes as *const ChangeSet as *mut ChangeSet)).get_mut(f).truncate(l);
180 struct RustFmtCalls {
181 input_path: Option<PathBuf>,
182 write_mode: WriteMode,
185 impl<'a> CompilerCalls<'a> for RustFmtCalls {
186 fn early_callback(&mut self,
187 _: &getopts::Matches,
188 _: &diagnostics::registry::Registry)
190 Compilation::Continue
193 fn some_input(&mut self,
195 input_path: Option<PathBuf>)
196 -> (Input, Option<PathBuf>) {
198 Some(ref ip) => self.input_path = Some(ip.clone()),
200 // FIXME should handle string input and write to stdout or something
201 panic!("No input path");
207 fn no_input(&mut self,
208 _: &getopts::Matches,
212 _: &diagnostics::registry::Registry)
213 -> Option<(Input, Option<PathBuf>)> {
214 panic!("No input supplied to RustFmt");
217 fn late_callback(&mut self,
218 _: &getopts::Matches,
224 Compilation::Continue
227 fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
228 let write_mode = self.write_mode;
229 let mut control = driver::CompileController::basic();
230 control.after_parse.stop = Compilation::Stop;
231 control.after_parse.callback = box move |state| {
232 let krate = state.krate.unwrap();
233 let codemap = state.session.codemap();
234 let mut changes = fmt_ast(krate, codemap);
235 // For some reason, the codemap does not include terminating newlines
236 // so we must add one on for each file. This is sad.
237 changes.append_newlines();
238 fmt_lines(&mut changes);
240 // FIXME(#5) Should be user specified whether to show or replace.
241 let result = changes.write_all_files(write_mode);
244 Err(msg) => println!("Error writing files: {}", msg),
246 if let WriteMode::Return(callback) = write_mode {
257 fn run(args: Vec<String>, write_mode: WriteMode) {
258 let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode };
259 rustc_driver::run_compiler(&args, &mut call_ctxt);
263 let args: Vec<_> = std::env::args().collect();
264 run(args, WriteMode::Display);
265 //run(args, WriteMode::NewFile("new"));
266 std::env::set_exit_status(0);
269 // let fmt = ListFormatting {
270 // tactic: ListTactic::Horizontal,
272 // trailing_separator: SeparatorTactic::Vertical,
277 // let inputs = vec![(format!("foo"), String::new()),
278 // (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 // let s = write_list(&inputs, &fmt);
286 // println!(" {}", s);
290 // comments aren't in the AST, which makes processing them difficult, but then
291 // comments are complicated anyway. I think I am happy putting off tackling them
292 // for now. Long term the soluton is for comments to be in the AST, but that means
293 // only the libsyntax AST, not the rustc one, which means waiting for the ASTs
294 // to diverge one day....
296 // Once we do have comments, we just have to implement a simple word wrapping
297 // algorithm to keep the width under IDEAL_WIDTH. We should also convert multiline
298 // /* ... */ comments to // and check doc comments are in the right place and of
301 // Should also make sure comments have the right indent
305 use std::collections::HashMap;
311 // For now, the only supported regression tests are idempotent tests - the input and
312 // output must match exactly.
313 // TODO would be good to check for error messages and fail on them, or at least report.
315 fn idempotent_tests() {
316 println!("Idempotent tests:");
317 unsafe { FAILURES = 0; }
319 // Get all files in the tests/idem directory
320 let files = fs::read_dir("tests/idem").unwrap();
321 // For each file, run rustfmt and collect the output
324 let path = entry.unwrap().path();
325 let file_name = path.to_str().unwrap();
326 println!("Testing '{}'...", file_name);
327 run(vec!["rustfmt".to_string(), file_name.to_string()], WriteMode::Return(HANDLE_RESULT));
330 // And also dogfood ourselves!
331 println!("Testing 'src/mod.rs'...");
332 run(vec!["rustfmt".to_string(), "src/mod.rs".to_string()], WriteMode::Return(HANDLE_RESULT));
336 let fails = unsafe { FAILURES };
337 println!("Ran {} idempotent tests; {} failures.", count, fails);
338 assert!(fails == 0, "{} idempotent tests failed", fails);
341 // 'global' used by sys_tests and handle_result.
342 static mut FAILURES: i32 = 0;
343 // Ick, just needed to get a &'static to handle_result.
344 static HANDLE_RESULT: &'static Fn(HashMap<String, String>) = &handle_result;
346 // Compare output to input.
347 fn handle_result(result: HashMap<String, String>) {
350 for file_name in result.keys() {
351 let mut f = fs::File::open(file_name).unwrap();
352 let mut text = String::new();
353 f.read_to_string(&mut text).unwrap();
354 if result[file_name] != text {
356 println!("Mismatch in {}.", file_name);