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};
37 use syntax::codemap::CodeMap;
38 use syntax::diagnostics;
41 use std::path::PathBuf;
42 use std::collections::HashMap;
45 use issues::{BadIssueSeeker, Issue};
46 use changes::ChangeSet;
47 use visitor::FmtVisitor;
63 const MIN_STRING: usize = 10;
64 // When we get scoped annotations, we should have rustfmt::skip.
65 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
67 static mut CONFIG: Option<config::Config> = None;
69 #[derive(Copy, Clone)]
72 // str is the extension of the new file
73 NewFile(&'static str),
74 // Write the output to stdout.
76 // Return the result as a mapping from filenames to StringBuffers.
77 Return(&'static Fn(HashMap<String, String>)),
80 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
81 pub enum NewlineStyle {
86 impl_enum_decodable!(NewlineStyle, Windows, Unix);
88 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
92 // Prefer same line except where there is a where clause, in which case force
93 // the brace to the next line.
97 impl_enum_decodable!(BraceStyle, AlwaysNextLine, PreferSameLine, SameLineWhere);
99 // How to indent a function's return type.
100 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
101 pub enum ReturnIndent {
102 // Aligned with the arguments
104 // Aligned with the where clause
108 impl_enum_decodable!(ReturnIndent, WithArgs, WithWhereClause);
111 // Line has more than config!(max_width) characters
113 // Line ends in whitespace
115 // TO-DO or FIX-ME item without an issue number
119 impl fmt::Display for ErrorKind {
120 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
122 ErrorKind::LineOverflow => {
123 write!(fmt, "line exceeded maximum length")
125 ErrorKind::TrailingWhitespace => {
126 write!(fmt, "left behind trailing whitespace")
128 ErrorKind::BadIssue(issue) => {
129 write!(fmt, "found {}", issue)
135 // Formatting errors that are identified *after* rustfmt has run
136 struct FormattingError {
141 struct FormatReport {
142 // Maps stringified file paths to their associated formatting errors
143 file_error_map: HashMap<String, Vec<FormattingError>>,
146 impl fmt::Display for FormatReport {
147 // Prints all the formatting errors.
148 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
149 for (file, errors) in self.file_error_map.iter() {
150 for error in errors {
152 "Rustfmt failed at {}:{}: {} (sorry)\n",
162 // Formatting which depends on the AST.
163 fn fmt_ast<'a>(krate: &ast::Crate, codemap: &'a CodeMap) -> ChangeSet<'a> {
164 let mut visitor = FmtVisitor::from_codemap(codemap);
165 visit::walk_crate(&mut visitor, krate);
166 let files = codemap.files.borrow();
167 if let Some(last) = files.last() {
168 visitor.format_missing(last.end_pos);
174 // Formatting done on a char by char or line by line basis.
175 // TODO warn on bad license
176 // TODO other stuff for parity with make tidy
177 fn fmt_lines(changes: &mut ChangeSet) -> FormatReport {
178 let mut truncate_todo = Vec::new();
179 let mut report = FormatReport { file_error_map: HashMap::new() };
181 // Iterate over the chars in the change set.
182 for (f, text) in changes.text() {
183 let mut trims = vec![];
184 let mut last_wspace: Option<usize> = None;
185 let mut line_len = 0;
186 let mut cur_line = 1;
187 let mut newline_count = 0;
188 let mut errors = vec![];
189 let mut issue_seeker = BadIssueSeeker::new(config!(report_todo),
190 config!(report_fixme));
192 for (c, b) in text.chars() {
193 if c == '\r' { continue; }
195 // Add warnings for bad todos/ fixmes
196 if let Some(issue) = issue_seeker.inspect(c) {
197 errors.push(FormattingError {
199 kind: ErrorKind::BadIssue(issue)
204 // Check for (and record) trailing whitespace.
205 if let Some(lw) = last_wspace {
206 trims.push((cur_line, lw, b));
209 // Check for any line width errors we couldn't correct.
210 if line_len > config!(max_width) {
211 errors.push(FormattingError {
213 kind: ErrorKind::LineOverflow
223 if c.is_whitespace() {
224 if last_wspace.is_none() {
225 last_wspace = Some(b);
233 if newline_count > 1 {
234 debug!("track truncate: {} {} {}", f, text.len, newline_count);
235 truncate_todo.push((f.to_owned(), text.len - newline_count + 1))
238 for &(l, _, _) in trims.iter() {
239 errors.push(FormattingError {
241 kind: ErrorKind::TrailingWhitespace
245 report.file_error_map.insert(f.to_owned(), errors);
248 for (f, l) in truncate_todo {
249 changes.get_mut(&f).truncate(l);
255 struct RustFmtCalls {
256 input_path: Option<PathBuf>,
257 write_mode: WriteMode,
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;
304 let mut control = driver::CompileController::basic();
305 control.after_parse.stop = Compilation::Stop;
306 control.after_parse.callback = Box::new(move |state| {
307 let krate = state.krate.unwrap();
308 let codemap = state.session.codemap();
309 let mut changes = fmt_ast(krate, codemap);
310 // For some reason, the codemap does not include terminating newlines
311 // so we must add one on for each file. This is sad.
312 changes.append_newlines();
313 println!("{}", fmt_lines(&mut changes));
315 let result = changes.write_all_files(write_mode);
318 Err(msg) => println!("Error writing files: {}", msg),
320 if let WriteMode::Return(callback) = write_mode {
331 // args are the arguments passed on the command line, generally passed through
333 // write_mode determines what happens to the result of running rustfmt, see
335 // default_config is a string of toml data to be used to configure rustfmt.
336 pub fn run(args: Vec<String>, write_mode: WriteMode, default_config: &str) {
337 config::set_config(default_config);
339 let mut call_ctxt = RustFmtCalls { input_path: None, write_mode: write_mode };
340 rustc_driver::run_compiler(&args, &mut call_ctxt);