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)]
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};
37 use syntax::codemap::CodeMap;
38 use syntax::diagnostics;
41 use std::path::PathBuf;
42 use std::collections::HashMap;
46 use issues::{BadIssueSeeker, Issue};
47 use changes::ChangeSet;
48 use visitor::FmtVisitor;
68 const MIN_STRING: usize = 10;
69 // When we get scoped annotations, we should have rustfmt::skip.
70 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
72 #[derive(Copy, Clone)]
75 // str is the extension of the new file
76 NewFile(&'static str),
77 // Write the output to stdout.
79 // Return the result as a mapping from filenames to StringBuffers.
80 Return(&'static Fn(HashMap<String, String>)),
83 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
84 pub enum NewlineStyle {
89 impl_enum_decodable!(NewlineStyle, Windows, Unix);
91 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
95 // Prefer same line except where there is a where clause, in which case force
96 // the brace to the next line.
100 impl_enum_decodable!(BraceStyle, AlwaysNextLine, PreferSameLine, SameLineWhere);
102 // How to indent a function's return type.
103 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
104 pub enum ReturnIndent {
105 // Aligned with the arguments
107 // Aligned with the where clause
111 impl_enum_decodable!(ReturnIndent, WithArgs, WithWhereClause);
114 // Line has exceeded character limit
116 // Line ends in whitespace
118 // TO-DO or FIX-ME item without an issue number
122 impl fmt::Display for ErrorKind {
123 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
125 ErrorKind::LineOverflow => {
126 write!(fmt, "line exceeded maximum length")
128 ErrorKind::TrailingWhitespace => {
129 write!(fmt, "left behind trailing whitespace")
131 ErrorKind::BadIssue(issue) => {
132 write!(fmt, "found {}", issue)
138 // Formatting errors that are identified *after* rustfmt has run
139 struct FormattingError {
144 struct FormatReport {
145 // Maps stringified file paths to their associated formatting errors
146 file_error_map: HashMap<String, Vec<FormattingError>>,
149 impl fmt::Display for FormatReport {
150 // Prints all the formatting errors.
151 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
152 for (file, errors) in self.file_error_map.iter() {
153 for error in errors {
155 "Rustfmt failed at {}:{}: {} (sorry)\n",
165 // Formatting which depends on the AST.
166 fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap, config: &'a Config) -> ChangeSet<'a> {
167 let mut visitor = FmtVisitor::from_codemap(codemap, config);
168 visit::walk_crate(&mut visitor, krate);
169 let files = codemap.files.borrow();
170 if let Some(last) = files.last() {
171 visitor.format_missing(last.end_pos);
177 // Formatting done on a char by char or line by line basis.
178 // TODO warn on bad license
179 // TODO other stuff for parity with make tidy
180 fn fmt_lines(changes: &mut ChangeSet, config: &Config) -> FormatReport {
181 let mut truncate_todo = Vec::new();
182 let mut report = FormatReport { file_error_map: HashMap::new() };
184 // Iterate over the chars in the change set.
185 for (f, text) in changes.text() {
186 let mut trims = vec![];
187 let mut last_wspace: Option<usize> = None;
188 let mut line_len = 0;
189 let mut cur_line = 1;
190 let mut newline_count = 0;
191 let mut errors = vec![];
192 let mut issue_seeker = BadIssueSeeker::new(config.report_todo,
193 config.report_fixme);
195 for (c, b) in text.chars() {
196 if c == '\r' { continue; }
198 // Add warnings for bad todos/ fixmes
199 if let Some(issue) = issue_seeker.inspect(c) {
200 errors.push(FormattingError {
202 kind: ErrorKind::BadIssue(issue)
207 // Check for (and record) trailing whitespace.
208 if let Some(lw) = last_wspace {
209 trims.push((cur_line, lw, b));
212 // Check for any line width errors we couldn't correct.
213 if line_len > config.max_width {
214 errors.push(FormattingError {
216 kind: ErrorKind::LineOverflow
226 if c.is_whitespace() {
227 if last_wspace.is_none() {
228 last_wspace = Some(b);
236 if newline_count > 1 {
237 debug!("track truncate: {} {} {}", f, text.len, newline_count);
238 truncate_todo.push((f.to_owned(), text.len - newline_count + 1))
241 for &(l, _, _) in trims.iter() {
242 errors.push(FormattingError {
244 kind: ErrorKind::TrailingWhitespace
248 report.file_error_map.insert(f.to_owned(), errors);
251 for (f, l) in truncate_todo {
252 changes.get_mut(&f).truncate(l);
258 struct RustFmtCalls {
259 input_path: Option<PathBuf>,
260 write_mode: WriteMode,
261 config: Option<Box<config::Config>>,
264 impl<'a> CompilerCalls<'a> for RustFmtCalls {
265 fn early_callback(&mut self,
266 _: &getopts::Matches,
267 _: &diagnostics::registry::Registry)
269 Compilation::Continue
272 fn some_input(&mut self,
274 input_path: Option<PathBuf>)
275 -> (Input, Option<PathBuf>) {
277 Some(ref ip) => self.input_path = Some(ip.clone()),
279 // FIXME should handle string input and write to stdout or something
280 panic!("No input path");
286 fn no_input(&mut self,
287 _: &getopts::Matches,
288 _: &rustc_config::Options,
291 _: &diagnostics::registry::Registry)
292 -> Option<(Input, Option<PathBuf>)> {
293 panic!("No input supplied to RustFmt");
296 fn late_callback(&mut self,
297 _: &getopts::Matches,
303 Compilation::Continue
306 fn build_controller(&mut self, _: &Session) -> driver::CompileController<'a> {
307 let write_mode = self.write_mode;
309 let mut config_option = None;
310 swap(&mut self.config, &mut config_option);
311 let config = config_option.unwrap();
313 let mut control = driver::CompileController::basic();
314 control.after_parse.stop = Compilation::Stop;
315 control.after_parse.callback = Box::new(move |state| {
316 let krate = state.krate.unwrap();
317 let codemap = state.session.codemap();
318 let mut changes = fmt_ast(krate, codemap, &*config);
319 // For some reason, the codemap does not include terminating newlines
320 // so we must add one on for each file. This is sad.
321 changes.append_newlines();
322 println!("{}", fmt_lines(&mut changes, &*config));
324 let result = changes.write_all_files(write_mode, &*config);
327 Err(msg) => println!("Error writing files: {}", msg),
329 if let WriteMode::Return(callback) = write_mode {
340 // args are the arguments passed on the command line, generally passed through
342 // write_mode determines what happens to the result of running rustfmt, see
344 // default_config is a string of toml data to be used to configure rustfmt.
345 pub fn run(args: Vec<String>, write_mode: WriteMode, default_config: &str) {
346 let config = Some(Box::new(config::Config::from_toml(default_config)));
347 let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode, config: config };
348 rustc_driver::run_compiler(&args, &mut call_ctxt);