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;
27 extern crate rustc_serialize;
31 use rustc::session::Session;
32 use rustc::session::config as rustc_config;
33 use rustc::session::config::Input;
34 use rustc_driver::{driver, CompilerCalls, Compilation};
36 use rustc_serialize::{Decodable, Decoder};
39 use syntax::codemap::CodeMap;
40 use syntax::diagnostics;
43 use std::path::PathBuf;
44 use std::collections::HashMap;
46 use changes::ChangeSet;
47 use visitor::FmtVisitor;
61 const MIN_STRING: usize = 10;
62 // When we get scoped annotations, we should have rustfmt::skip.
63 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
65 static mut CONFIG: Option<config::Config> = None;
67 // Macro for deriving implementations of Decodable for enums
68 macro_rules! impl_enum_decodable {
69 ( $e:ident, $( $x:ident ),* ) => {
70 impl Decodable for $e {
71 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
72 let s = try!(d.read_str());
75 stringify!($x) => Ok($e::$x),
77 _ => Err(d.error("Bad variant")),
84 #[derive(Copy, Clone)]
87 // str is the extension of the new file
88 NewFile(&'static str),
89 // Write the output to stdout.
91 // Return the result as a mapping from filenames to StringBuffers.
92 Return(&'static Fn(HashMap<String, String>)),
95 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
96 pub enum NewlineStyle {
101 impl_enum_decodable!(NewlineStyle, Windows, Unix);
103 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
104 pub enum BraceStyle {
107 // Prefer same line except where there is a where clause, in which case force
108 // the brace to the next line.
112 impl_enum_decodable!(BraceStyle, AlwaysNextLine, PreferSameLine, SameLineWhere);
114 // How to indent a function's return type.
115 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
116 pub enum ReturnIndent {
117 // Aligned with the arguments
119 // Aligned with the where clause
123 impl_enum_decodable!(ReturnIndent, WithArgs, WithWhereClause);
125 // Formatting which depends on the AST.
126 fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap) -> ChangeSet<'a> {
127 let mut visitor = FmtVisitor::from_codemap(codemap);
128 visit::walk_crate(&mut visitor, krate);
129 let files = codemap.files.borrow();
130 if let Some(last) = files.last() {
131 visitor.format_missing(last.end_pos);
137 // Formatting done on a char by char or line by line basis.
138 // TODO warn on TODOs and FIXMEs without an issue number
139 // TODO warn on bad license
140 // TODO other stuff for parity with make tidy
141 fn fmt_lines(changes: &mut ChangeSet) {
142 let mut truncate_todo = Vec::new();
144 // Iterate over the chars in the change set.
145 for (f, text) in changes.text() {
146 let mut trims = vec![];
147 let mut last_wspace: Option<usize> = None;
148 let mut line_len = 0;
149 let mut cur_line = 1;
150 let mut newline_count = 0;
151 for (c, b) in text.chars() {
152 if c == '\r' { continue; }
154 // Check for (and record) trailing whitespace.
155 if let Some(lw) = last_wspace {
156 trims.push((cur_line, lw, b));
159 // Check for any line width errors we couldn't correct.
160 if line_len > config!(max_width) {
161 // TODO store the error rather than reporting immediately.
162 println!("Rustfmt couldn't fix (sorry). {}:{}: line longer than {} characters",
163 f, cur_line, config!(max_width));
172 if c.is_whitespace() {
173 if last_wspace.is_none() {
174 last_wspace = Some(b);
182 if newline_count > 1 {
183 debug!("track truncate: {} {} {}", f, text.len, newline_count);
184 truncate_todo.push((f.to_string(), text.len - newline_count + 1))
187 for &(l, _, _) in trims.iter() {
188 // TODO store the error rather than reporting immediately.
189 println!("Rustfmt left trailing whitespace at {}:{} (sorry)", f, l);
193 for (f, l) in truncate_todo {
194 changes.get_mut(&f).truncate(l);
198 struct RustFmtCalls {
199 input_path: Option<PathBuf>,
200 write_mode: WriteMode,
203 impl<'a> CompilerCalls<'a> for RustFmtCalls {
204 fn early_callback(&mut self,
205 _: &getopts::Matches,
206 _: &diagnostics::registry::Registry)
208 Compilation::Continue
211 fn some_input(&mut self,
213 input_path: Option<PathBuf>)
214 -> (Input, Option<PathBuf>) {
216 Some(ref ip) => self.input_path = Some(ip.clone()),
218 // FIXME should handle string input and write to stdout or something
219 panic!("No input path");
225 fn no_input(&mut self,
226 _: &getopts::Matches,
227 _: &rustc_config::Options,
230 _: &diagnostics::registry::Registry)
231 -> Option<(Input, Option<PathBuf>)> {
232 panic!("No input supplied to RustFmt");
235 fn late_callback(&mut self,
236 _: &getopts::Matches,
242 Compilation::Continue
245 fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
246 let write_mode = self.write_mode;
247 let mut control = driver::CompileController::basic();
248 control.after_parse.stop = Compilation::Stop;
249 control.after_parse.callback = Box::new(move |state| {
250 let krate = state.krate.unwrap();
251 let codemap = state.session.codemap();
252 let mut changes = fmt_ast(krate, codemap);
253 // For some reason, the codemap does not include terminating newlines
254 // so we must add one on for each file. This is sad.
255 changes.append_newlines();
256 fmt_lines(&mut changes);
258 let result = changes.write_all_files(write_mode);
261 Err(msg) => println!("Error writing files: {}", msg),
263 if let WriteMode::Return(callback) = write_mode {
274 // args are the arguments passed on the command line, generally passed through
276 // write_mode determines what happens to the result of running rustfmt, see
278 // default_config is a string of toml data to be used to configure rustfmt.
279 pub fn run(args: Vec<String>, write_mode: WriteMode, default_config: &str) {
280 config::set_config(default_config);
282 let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode };
283 rustc_driver::run_compiler(&args, &mut call_ctxt);