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 // TODO we're going to allocate a whole bunch of temp Strings, is it worth
18 // keeping some scratch mem for this and running our own StrPool?
19 // TODO for lint violations of names, emit a refactor script
27 extern crate rustc_driver;
32 use rustc::session::Session;
33 use rustc::session::config::{self, Input};
34 use rustc_driver::{driver, CompilerCalls, Compilation};
37 use syntax::codemap::CodeMap;
38 use syntax::diagnostics;
41 use std::path::PathBuf;
42 use std::collections::HashMap;
44 use changes::ChangeSet;
45 use visitor::FmtVisitor;
57 const IDEAL_WIDTH: usize = 80;
58 const LEEWAY: usize = 5;
59 const MAX_WIDTH: usize = 100;
60 const MIN_STRING: usize = 10;
61 const TAB_SPACES: usize = 4;
62 const NEWLINE_STYLE: NewlineStyle = NewlineStyle::Unix;
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)]
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.to_string(), 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 changes.get_mut(&f).truncate(l);
175 struct RustFmtCalls {
176 input_path: Option<PathBuf>,
177 write_mode: WriteMode,
180 impl<'a> CompilerCalls<'a> for RustFmtCalls {
181 fn early_callback(&mut self,
182 _: &getopts::Matches,
183 _: &diagnostics::registry::Registry)
185 Compilation::Continue
188 fn some_input(&mut self,
190 input_path: Option<PathBuf>)
191 -> (Input, Option<PathBuf>) {
193 Some(ref ip) => self.input_path = Some(ip.clone()),
195 // FIXME should handle string input and write to stdout or something
196 panic!("No input path");
202 fn no_input(&mut self,
203 _: &getopts::Matches,
207 _: &diagnostics::registry::Registry)
208 -> Option<(Input, Option<PathBuf>)> {
209 panic!("No input supplied to RustFmt");
212 fn late_callback(&mut self,
213 _: &getopts::Matches,
219 Compilation::Continue
222 fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
223 let write_mode = self.write_mode;
224 let mut control = driver::CompileController::basic();
225 control.after_parse.stop = Compilation::Stop;
226 control.after_parse.callback = box move |state| {
227 let krate = state.krate.unwrap();
228 let codemap = state.session.codemap();
229 let mut changes = fmt_ast(krate, codemap);
230 // For some reason, the codemap does not include terminating newlines
231 // so we must add one on for each file. This is sad.
232 changes.append_newlines();
233 fmt_lines(&mut changes);
235 // FIXME(#5) Should be user specified whether to show or replace.
236 let result = changes.write_all_files(write_mode);
239 Err(msg) => println!("Error writing files: {}", msg),
241 if let WriteMode::Return(callback) = write_mode {
252 pub fn run(args: Vec<String>, write_mode: WriteMode) {
253 let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode };
254 rustc_driver::run_compiler(&args, &mut call_ctxt);