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 // TODO we're going to allocate a whole bunch of temp Strings, is it worth
12 // keeping some scratch mem for this and running our own StrPool?
13 // TODO for lint violations of names, emit a refactor script
18 extern crate syntex_syntax as syntax;
19 extern crate rustc_serialize;
23 extern crate unicode_segmentation;
29 use syntax::codemap::Span;
30 use syntax::diagnostic::{EmitterWriter, Handler};
31 use syntax::parse::{self, ParseSess};
33 use std::ops::{Add, Sub};
35 use std::collections::HashMap;
37 use std::str::FromStr;
39 use issues::{BadIssueSeeker, Issue};
41 use visitor::FmtVisitor;
65 const MIN_STRING: usize = 10;
66 // When we get scoped annotations, we should have rustfmt::skip.
67 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
70 fn span(&self) -> Span;
73 impl Spanned for ast::Expr {
74 fn span(&self) -> Span {
79 impl Spanned for ast::Pat {
80 fn span(&self) -> Span {
85 impl Spanned for ast::Ty {
86 fn span(&self) -> Span {
91 #[derive(Copy, Clone, Debug)]
93 // Width of the block indent, in characters. Must be a multiple of
94 // Config::tab_spaces.
95 pub block_indent: usize,
96 // Alignment in characters.
101 pub fn new(block_indent: usize, alignment: usize) -> Indent {
103 block_indent: block_indent,
104 alignment: alignment,
108 pub fn empty() -> Indent {
112 pub fn block_indent(mut self, config: &Config) -> Indent {
113 self.block_indent += config.tab_spaces;
117 pub fn block_unindent(mut self, config: &Config) -> Indent {
118 self.block_indent -= config.tab_spaces;
122 pub fn width(&self) -> usize {
123 self.block_indent + self.alignment
126 pub fn to_string(&self, config: &Config) -> String {
127 let (num_tabs, num_spaces) = if config.hard_tabs {
128 (self.block_indent / config.tab_spaces, self.alignment)
130 (0, self.block_indent + self.alignment)
132 let num_chars = num_tabs + num_spaces;
133 let mut indent = String::with_capacity(num_chars);
134 for _ in 0..num_tabs {
137 for _ in 0..num_spaces {
144 impl Add for Indent {
145 type Output = Indent;
147 fn add(self, rhs: Indent) -> Indent {
149 block_indent: self.block_indent + rhs.block_indent,
150 alignment: self.alignment + rhs.alignment,
155 impl Sub for Indent {
156 type Output = Indent;
158 fn sub(self, rhs: Indent) -> Indent {
159 Indent::new(self.block_indent - rhs.block_indent,
160 self.alignment - rhs.alignment)
164 impl Add<usize> for Indent {
165 type Output = Indent;
167 fn add(self, rhs: usize) -> Indent {
168 Indent::new(self.block_indent, self.alignment + rhs)
172 impl Sub<usize> for Indent {
173 type Output = Indent;
175 fn sub(self, rhs: usize) -> Indent {
176 Indent::new(self.block_indent, self.alignment - rhs)
180 #[derive(Copy, Clone)]
182 // Backups the original file and overwrites the orignal.
184 // Overwrites original file without backup.
186 // str is the extension of the new file.
187 NewFile(&'static str),
188 // Write the output to stdout.
190 // Write the diff to stdout.
192 // Return the result as a mapping from filenames to Strings.
194 // Display how much of the input file was processed
200 impl FromStr for WriteMode {
203 fn from_str(s: &str) -> Result<Self, Self::Err> {
205 "replace" => Ok(WriteMode::Replace),
206 "display" => Ok(WriteMode::Display),
207 "overwrite" => Ok(WriteMode::Overwrite),
208 "diff" => Ok(WriteMode::Diff),
209 "coverage" => Ok(WriteMode::Coverage),
210 "plain" => Ok(WriteMode::Plain),
217 // Line has exceeded character limit
219 // Line ends in whitespace
221 // TO-DO or FIX-ME item without an issue number
225 impl fmt::Display for ErrorKind {
226 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
228 ErrorKind::LineOverflow => write!(fmt, "line exceeded maximum length"),
229 ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
230 ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
235 // Formatting errors that are identified *after* rustfmt has run.
236 pub struct FormattingError {
241 impl FormattingError {
242 fn msg_prefix(&self) -> &str {
244 ErrorKind::LineOverflow |
245 ErrorKind::TrailingWhitespace => "Rustfmt failed at",
246 ErrorKind::BadIssue(_) => "WARNING:",
250 fn msg_suffix(&self) -> &str {
252 ErrorKind::LineOverflow |
253 ErrorKind::TrailingWhitespace => "(sorry)",
254 ErrorKind::BadIssue(_) => "",
259 pub struct FormatReport {
260 // Maps stringified file paths to their associated formatting errors.
261 file_error_map: HashMap<String, Vec<FormattingError>>,
265 pub fn warning_count(&self) -> usize {
266 self.file_error_map.iter().map(|(_, ref errors)| errors.len()).fold(0, |acc, x| acc + x)
270 impl fmt::Display for FormatReport {
271 // Prints all the formatting errors.
272 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
273 for (file, errors) in &self.file_error_map {
274 for error in errors {
281 error.msg_suffix()));
288 // Formatting which depends on the AST.
289 fn fmt_ast(krate: &ast::Crate,
290 parse_session: &ParseSess,
294 let mut file_map = FileMap::new();
295 for (path, module) in modules::list_files(krate, parse_session.codemap()) {
296 let path = path.to_str().unwrap();
298 println!("Formatting {}", path);
300 let mut visitor = FmtVisitor::from_codemap(parse_session, config, Some(mode));
301 visitor.format_separate_mod(module);
302 file_map.insert(path.to_owned(), visitor.buffer);
307 // Formatting done on a char by char or line by line basis.
308 // TODO(#209) warn on bad license
309 // TODO(#20) other stuff for parity with make tidy
310 pub fn fmt_lines(file_map: &mut FileMap, config: &Config) -> FormatReport {
311 let mut truncate_todo = Vec::new();
312 let mut report = FormatReport { file_error_map: HashMap::new() };
314 // Iterate over the chars in the file map.
315 for (f, text) in file_map.iter() {
316 let mut trims = vec![];
317 let mut last_wspace: Option<usize> = None;
318 let mut line_len = 0;
319 let mut cur_line = 1;
320 let mut newline_count = 0;
321 let mut errors = vec![];
322 let mut issue_seeker = BadIssueSeeker::new(config.report_todo, config.report_fixme);
324 for (c, b) in text.chars() {
329 // Add warnings for bad todos/ fixmes
330 if let Some(issue) = issue_seeker.inspect(c) {
331 errors.push(FormattingError {
333 kind: ErrorKind::BadIssue(issue),
338 // Check for (and record) trailing whitespace.
339 if let Some(lw) = last_wspace {
340 trims.push((cur_line, lw, b));
343 // Check for any line width errors we couldn't correct.
344 if line_len > config.max_width {
345 errors.push(FormattingError {
347 kind: ErrorKind::LineOverflow,
357 if c.is_whitespace() {
358 if last_wspace.is_none() {
359 last_wspace = Some(b);
367 if newline_count > 1 {
368 debug!("track truncate: {} {} {}", f, text.len, newline_count);
369 truncate_todo.push((f.to_owned(), text.len - newline_count + 1))
372 for &(l, _, _) in &trims {
373 errors.push(FormattingError {
375 kind: ErrorKind::TrailingWhitespace,
379 report.file_error_map.insert(f.to_owned(), errors);
382 for (f, l) in truncate_todo {
383 file_map.get_mut(&f).unwrap().truncate(l);
389 pub fn format_string(input: String, config: &Config, mode: WriteMode) -> FileMap {
391 let mut parse_session = ParseSess::new();
392 let krate = parse::parse_crate_from_source_str(path.to_owned(),
397 // Suppress error output after parsing.
398 let emitter = Box::new(EmitterWriter::new(Box::new(Vec::new()), None));
399 parse_session.span_diagnostic.handler = Handler::with_emitter(false, emitter);
401 // FIXME: we still use a FileMap even though we only have
402 // one file, because fmt_lines requires a FileMap
403 let mut file_map = FileMap::new();
405 // do the actual formatting
406 let mut visitor = FmtVisitor::from_codemap(&parse_session, config, Some(mode));
407 visitor.format_separate_mod(&krate.module);
409 // append final newline
410 visitor.buffer.push_str("\n");
411 file_map.insert(path.to_owned(), visitor.buffer);
416 pub fn format(file: &Path, config: &Config, mode: WriteMode) -> FileMap {
417 let mut parse_session = ParseSess::new();
418 let krate = parse::parse_crate_from_file(file, Vec::new(), &parse_session);
420 // Suppress error output after parsing.
421 let emitter = Box::new(EmitterWriter::new(Box::new(Vec::new()), None));
422 parse_session.span_diagnostic.handler = Handler::with_emitter(false, emitter);
424 let mut file_map = fmt_ast(&krate, &parse_session, config, mode);
426 // For some reason, the codemap does not include terminating
427 // newlines so we must add one on for each file. This is sad.
428 filemap::append_newlines(&mut file_map);
433 // args are the arguments passed on the command line, generally passed through
435 // write_mode determines what happens to the result of running rustfmt, see
437 pub fn run(file: &Path, write_mode: WriteMode, config: &Config) {
438 let mut result = format(file, config, write_mode);
440 print!("{}", fmt_lines(&mut result, config));
442 let write_result = filemap::write_all_files(&result, write_mode, config);
444 if let Err(msg) = write_result {
445 println!("Error writing files: {}", msg);
449 // Similar to run, but takes an input String instead of a file to format
450 pub fn run_from_stdin(input: String, mode: WriteMode, config: &Config) {
451 let mut result = format_string(input, config, mode);
452 fmt_lines(&mut result, config);
454 let write_result = filemap::write_file(&result["stdin"], "stdin", mode, config);
456 if let Err(msg) = write_result {
457 panic!("Error writing to stdout: {}", msg);