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(rustc_private)]
12 #![feature(collections)]
15 // TODO we're going to allocate a whole bunch of temp Strings, is it worth
16 // keeping some scratch mem for this and running our own StrPool?
17 // TODO for lint violations of names, emit a refactor script
25 extern crate rustc_driver;
30 use rustc::session::Session;
31 use rustc::session::config::{self, Input};
32 use rustc_driver::{driver, CompilerCalls, Compilation};
35 use syntax::codemap::CodeMap;
36 use syntax::diagnostics;
39 use std::path::PathBuf;
40 use std::collections::HashMap;
42 use changes::ChangeSet;
43 use visitor::FmtVisitor;
55 const IDEAL_WIDTH: usize = 80;
56 const LEEWAY: usize = 5;
57 const MAX_WIDTH: usize = 100;
58 const MIN_STRING: usize = 10;
59 const TAB_SPACES: usize = 4;
60 const NEWLINE_STYLE: NewlineStyle = NewlineStyle::Unix;
61 const FN_BRACE_STYLE: BraceStyle = BraceStyle::SameLineWhere;
62 const FN_RETURN_INDENT: ReturnIndent = ReturnIndent::WithArgs;
63 // When we get scoped annotations, we should have rustfmt::skip.
64 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
66 #[derive(Copy, Clone)]
69 // str is the extension of the new file
70 NewFile(&'static str),
71 // Write the output to stdout.
73 // Return the result as a mapping from filenames to StringBuffers.
74 Return(&'static Fn(HashMap<String, String>)),
77 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
83 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
87 // Prefer same line except where there is a where clause, in which case force
88 // the brace to the next line.
92 // How to indent a function's return type.
93 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
95 // Aligned with the arguments
97 // Aligned with the where clause
101 // Formatting which depends on the AST.
102 fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap) -> ChangeSet<'a> {
103 let mut visitor = FmtVisitor::from_codemap(codemap);
104 visit::walk_crate(&mut visitor, krate);
105 let files = codemap.files.borrow();
106 if let Some(last) = files.last() {
107 visitor.format_missing(last.end_pos);
113 // Formatting done on a char by char or line by line basis.
114 // TODO warn on TODOs and FIXMEs without an issue number
115 // TODO warn on bad license
116 // TODO other stuff for parity with make tidy
117 fn fmt_lines(changes: &mut ChangeSet) {
118 let mut truncate_todo = Vec::new();
120 // Iterate over the chars in the change set.
121 for (f, text) in changes.text() {
122 let mut trims = vec![];
123 let mut last_wspace: Option<usize> = None;
124 let mut line_len = 0;
125 let mut cur_line = 1;
126 let mut newline_count = 0;
127 for (c, b) in text.chars() {
128 if c == '\r' { continue; }
130 // Check for (and record) trailing whitespace.
131 if let Some(lw) = last_wspace {
132 trims.push((cur_line, lw, b));
135 // Check for any line width errors we couldn't correct.
136 if line_len > MAX_WIDTH {
137 // TODO store the error rather than reporting immediately.
138 println!("Rustfmt couldn't fix (sorry). {}:{}: line longer than {} characters",
139 f, cur_line, MAX_WIDTH);
148 if c.is_whitespace() {
149 if last_wspace.is_none() {
150 last_wspace = Some(b);
158 if newline_count > 1 {
159 debug!("track truncate: {} {} {}", f, text.len, newline_count);
160 truncate_todo.push((f.to_string(), text.len - newline_count + 1))
163 for &(l, _, _) in trims.iter() {
164 // TODO store the error rather than reporting immediately.
165 println!("Rustfmt left trailing whitespace at {}:{} (sorry)", f, l);
169 for (f, l) in truncate_todo {
170 changes.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::new(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 pub 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);