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(str_escape)]
14 #![feature(slice_extras)]
16 // TODO we're going to allocate a whole bunch of temp Strings, is it worth
17 // keeping some scratch mem for this and running our own StrPool?
18 // TODO for lint violations of names, emit a refactor script
26 extern crate rustc_driver;
28 extern crate rustc_serialize;
32 use rustc::session::Session;
33 use rustc::session::config as rustc_config;
34 use rustc::session::config::Input;
35 use rustc_driver::{driver, CompilerCalls, Compilation};
38 use syntax::codemap::CodeMap;
39 use syntax::diagnostics;
42 use std::path::PathBuf;
43 use std::collections::HashMap;
47 use issues::{BadIssueSeeker, Issue};
48 use changes::ChangeSet;
49 use visitor::FmtVisitor;
69 const MIN_STRING: usize = 10;
70 // When we get scoped annotations, we should have rustfmt::skip.
71 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
73 #[derive(Copy, Clone)]
76 // str is the extension of the new file
77 NewFile(&'static str),
78 // Write the output to stdout.
80 // Return the result as a mapping from filenames to StringBuffers.
81 Return(&'static Fn(HashMap<String, String>)),
84 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
85 pub enum NewlineStyle {
90 impl_enum_decodable!(NewlineStyle, Windows, Unix);
92 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
96 // Prefer same line except where there is a where clause, in which case force
97 // the brace to the next line.
101 impl_enum_decodable!(BraceStyle, AlwaysNextLine, PreferSameLine, SameLineWhere);
103 // How to indent a function's return type.
104 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
105 pub enum ReturnIndent {
106 // Aligned with the arguments
108 // Aligned with the where clause
112 impl_enum_decodable!(ReturnIndent, WithArgs, WithWhereClause);
115 // Line has exceeded character limit
117 // Line ends in whitespace
119 // TO-DO or FIX-ME item without an issue number
123 impl fmt::Display for ErrorKind {
124 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
126 ErrorKind::LineOverflow => {
127 write!(fmt, "line exceeded maximum length")
129 ErrorKind::TrailingWhitespace => {
130 write!(fmt, "left behind trailing whitespace")
132 ErrorKind::BadIssue(issue) => {
133 write!(fmt, "found {}", issue)
139 // Formatting errors that are identified *after* rustfmt has run
140 struct FormattingError {
145 struct FormatReport {
146 // Maps stringified file paths to their associated formatting errors
147 file_error_map: HashMap<String, Vec<FormattingError>>,
150 impl fmt::Display for FormatReport {
151 // Prints all the formatting errors.
152 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
153 for (file, errors) in self.file_error_map.iter() {
154 for error in errors {
156 "Rustfmt failed at {}:{}: {} (sorry)\n",
166 // Formatting which depends on the AST.
167 fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap, config: &'a Config) -> ChangeSet<'a> {
168 let mut visitor = FmtVisitor::from_codemap(codemap, config);
169 visit::walk_crate(&mut visitor, krate);
173 // Formatting done on a char by char or line by line basis.
174 // TODO warn on bad license
175 // TODO other stuff for parity with make tidy
176 fn fmt_lines(changes: &mut ChangeSet, config: &Config) -> FormatReport {
177 let mut truncate_todo = Vec::new();
178 let mut report = FormatReport { file_error_map: HashMap::new() };
180 // Iterate over the chars in the change set.
181 for (f, text) in changes.text() {
182 let mut trims = vec![];
183 let mut last_wspace: Option<usize> = None;
184 let mut line_len = 0;
185 let mut cur_line = 1;
186 let mut newline_count = 0;
187 let mut errors = vec![];
188 let mut issue_seeker = BadIssueSeeker::new(config.report_todo,
189 config.report_fixme);
191 for (c, b) in text.chars() {
192 if c == '\r' { continue; }
194 // Add warnings for bad todos/ fixmes
195 if let Some(issue) = issue_seeker.inspect(c) {
196 errors.push(FormattingError {
198 kind: ErrorKind::BadIssue(issue)
203 // Check for (and record) trailing whitespace.
204 if let Some(lw) = last_wspace {
205 trims.push((cur_line, lw, b));
208 // Check for any line width errors we couldn't correct.
209 if line_len > config.max_width {
210 errors.push(FormattingError {
212 kind: ErrorKind::LineOverflow
222 if c.is_whitespace() {
223 if last_wspace.is_none() {
224 last_wspace = Some(b);
232 if newline_count > 1 {
233 debug!("track truncate: {} {} {}", f, text.len, newline_count);
234 truncate_todo.push((f.to_owned(), text.len - newline_count + 1))
237 for &(l, _, _) in trims.iter() {
238 errors.push(FormattingError {
240 kind: ErrorKind::TrailingWhitespace
244 report.file_error_map.insert(f.to_owned(), errors);
247 for (f, l) in truncate_todo {
248 changes.get_mut(&f).truncate(l);
254 struct RustFmtCalls {
255 input_path: Option<PathBuf>,
256 write_mode: WriteMode,
257 config: Option<Box<config::Config>>,
260 impl<'a> CompilerCalls<'a> for RustFmtCalls {
261 fn early_callback(&mut self,
262 _: &getopts::Matches,
263 _: &diagnostics::registry::Registry)
265 Compilation::Continue
268 fn some_input(&mut self,
270 input_path: Option<PathBuf>)
271 -> (Input, Option<PathBuf>) {
273 Some(ref ip) => self.input_path = Some(ip.clone()),
275 // FIXME should handle string input and write to stdout or something
276 panic!("No input path");
282 fn no_input(&mut self,
283 _: &getopts::Matches,
284 _: &rustc_config::Options,
287 _: &diagnostics::registry::Registry)
288 -> Option<(Input, Option<PathBuf>)> {
289 panic!("No input supplied to RustFmt");
292 fn late_callback(&mut self,
293 _: &getopts::Matches,
299 Compilation::Continue
302 fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
303 let write_mode = self.write_mode;
305 let mut config_option = None;
306 swap(&mut self.config, &mut config_option);
307 let config = config_option.unwrap();
309 let mut control = driver::CompileController::basic();
310 control.after_parse.stop = Compilation::Stop;
311 control.after_parse.callback = Box::new(move |state| {
312 let krate = state.krate.unwrap();
313 let codemap = state.session.codemap();
314 let mut changes = fmt_ast(krate, codemap, &*config);
315 // For some reason, the codemap does not include terminating newlines
316 // so we must add one on for each file. This is sad.
317 changes.append_newlines();
318 println!("{}", fmt_lines(&mut changes, &*config));
320 let result = changes.write_all_files(write_mode, &*config);
323 Err(msg) => println!("Error writing files: {}", msg),
325 if let WriteMode::Return(callback) = write_mode {
336 // args are the arguments passed on the command line, generally passed through
338 // write_mode determines what happens to the result of running rustfmt, see
340 // default_config is a string of toml data to be used to configure rustfmt.
341 pub fn run(args: Vec<String>, write_mode: WriteMode, default_config: &str) {
342 let config = Some(Box::new(config::Config::from_toml(default_config)));
343 let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode, config: config };
344 rustc_driver::run_compiler(&args, &mut call_ctxt);