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 #[derive(Copy, Clone)]
70 // str is the extension of the new file
71 NewFile(&'static str),
72 // Write the output to stdout.
74 // Return the result as a mapping from filenames to StringBuffers.
75 Return(&'static Fn(HashMap<String, String>)),
78 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
79 pub enum NewlineStyle {
84 impl Decodable for NewlineStyle {
85 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
86 let s = try!(d.read_str());
88 "Windows" => Ok(NewlineStyle::Windows),
89 "Unix" => Ok(NewlineStyle::Unix),
90 _ => Err(d.error("Bad variant")),
95 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
99 // Prefer same line except where there is a where clause, in which case force
100 // the brace to the next line.
104 impl Decodable for BraceStyle {
105 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
106 let s = try!(d.read_str());
108 "AlwaysNextLine" => Ok(BraceStyle::AlwaysNextLine),
109 "PreferSameLine" => Ok(BraceStyle::PreferSameLine),
110 "SameLineWhere" => Ok(BraceStyle::SameLineWhere),
111 _ => Err(d.error("Bad variant")),
116 // How to indent a function's return type.
117 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
118 pub enum ReturnIndent {
119 // Aligned with the arguments
121 // Aligned with the where clause
125 // TODO could use a macro for all these Decodable impls.
126 impl Decodable for ReturnIndent {
127 fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
128 let s = try!(d.read_str());
130 "WithArgs" => Ok(ReturnIndent::WithArgs),
131 "WithWhereClause" => Ok(ReturnIndent::WithWhereClause),
132 _ => Err(d.error("Bad variant")),
137 // Formatting which depends on the AST.
138 fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap) -> ChangeSet<'a> {
139 let mut visitor = FmtVisitor::from_codemap(codemap);
140 visit::walk_crate(&mut visitor, krate);
141 let files = codemap.files.borrow();
142 if let Some(last) = files.last() {
143 visitor.format_missing(last.end_pos);
149 // Formatting done on a char by char or line by line basis.
150 // TODO warn on TODOs and FIXMEs without an issue number
151 // TODO warn on bad license
152 // TODO other stuff for parity with make tidy
153 fn fmt_lines(changes: &mut ChangeSet) {
154 let mut truncate_todo = Vec::new();
156 // Iterate over the chars in the change set.
157 for (f, text) in changes.text() {
158 let mut trims = vec![];
159 let mut last_wspace: Option<usize> = None;
160 let mut line_len = 0;
161 let mut cur_line = 1;
162 let mut newline_count = 0;
163 for (c, b) in text.chars() {
164 if c == '\r' { continue; }
166 // Check for (and record) trailing whitespace.
167 if let Some(lw) = last_wspace {
168 trims.push((cur_line, lw, b));
171 // Check for any line width errors we couldn't correct.
172 if line_len > config!(max_width) {
173 // TODO store the error rather than reporting immediately.
174 println!("Rustfmt couldn't fix (sorry). {}:{}: line longer than {} characters",
175 f, cur_line, config!(max_width));
184 if c.is_whitespace() {
185 if last_wspace.is_none() {
186 last_wspace = Some(b);
194 if newline_count > 1 {
195 debug!("track truncate: {} {} {}", f, text.len, newline_count);
196 truncate_todo.push((f.to_string(), text.len - newline_count + 1))
199 for &(l, _, _) in trims.iter() {
200 // TODO store the error rather than reporting immediately.
201 println!("Rustfmt left trailing whitespace at {}:{} (sorry)", f, l);
205 for (f, l) in truncate_todo {
206 changes.get_mut(&f).truncate(l);
210 struct RustFmtCalls {
211 input_path: Option<PathBuf>,
212 write_mode: WriteMode,
215 impl<'a> CompilerCalls<'a> for RustFmtCalls {
216 fn early_callback(&mut self,
217 _: &getopts::Matches,
218 _: &diagnostics::registry::Registry)
220 Compilation::Continue
223 fn some_input(&mut self,
225 input_path: Option<PathBuf>)
226 -> (Input, Option<PathBuf>) {
228 Some(ref ip) => self.input_path = Some(ip.clone()),
230 // FIXME should handle string input and write to stdout or something
231 panic!("No input path");
237 fn no_input(&mut self,
238 _: &getopts::Matches,
239 _: &rustc_config::Options,
242 _: &diagnostics::registry::Registry)
243 -> Option<(Input, Option<PathBuf>)> {
244 panic!("No input supplied to RustFmt");
247 fn late_callback(&mut self,
248 _: &getopts::Matches,
254 Compilation::Continue
257 fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
258 let write_mode = self.write_mode;
259 let mut control = driver::CompileController::basic();
260 control.after_parse.stop = Compilation::Stop;
261 control.after_parse.callback = Box::new(move |state| {
262 let krate = state.krate.unwrap();
263 let codemap = state.session.codemap();
264 let mut changes = fmt_ast(krate, codemap);
265 // For some reason, the codemap does not include terminating newlines
266 // so we must add one on for each file. This is sad.
267 changes.append_newlines();
268 fmt_lines(&mut changes);
270 let result = changes.write_all_files(write_mode);
273 Err(msg) => println!("Error writing files: {}", msg),
275 if let WriteMode::Return(callback) = write_mode {
286 // args are the arguments passed on the command line, generally passed through
288 // write_mode determines what happens to the result of running rustfmt, see
290 // default_config is a string of toml data to be used to configure rustfmt.
291 pub fn run(args: Vec<String>, write_mode: WriteMode, default_config: &str) {
292 config::set_config(default_config);
294 let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode };
295 rustc_driver::run_compiler(&args, &mut call_ctxt);