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::{mk_sp, CodeMap, Span};
30 use syntax::errors::{Handler, DiagnosticBuilder};
31 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
32 use syntax::parse::{self, ParseSess};
34 use std::io::{stdout, Write};
35 use std::ops::{Add, Sub};
36 use std::path::{Path, PathBuf};
38 use std::collections::HashMap;
41 use issues::{BadIssueSeeker, Issue};
43 use visitor::FmtVisitor;
44 use config::{Config, WriteMode};
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";
73 fn span(&self) -> Span;
76 impl Spanned for ast::Expr {
77 fn span(&self) -> Span {
82 impl Spanned for ast::Pat {
83 fn span(&self) -> Span {
88 impl Spanned for ast::Ty {
89 fn span(&self) -> Span {
94 impl Spanned for ast::Arg {
95 fn span(&self) -> Span {
96 if items::is_named_arg(self) {
97 mk_sp(self.pat.span.lo, self.ty.span.hi)
104 #[derive(Copy, Clone, Debug)]
106 // Width of the block indent, in characters. Must be a multiple of
107 // Config::tab_spaces.
108 pub block_indent: usize,
109 // Alignment in characters.
110 pub alignment: usize,
114 pub fn new(block_indent: usize, alignment: usize) -> Indent {
116 block_indent: block_indent,
117 alignment: alignment,
121 pub fn empty() -> Indent {
125 pub fn block_indent(mut self, config: &Config) -> Indent {
126 self.block_indent += config.tab_spaces;
130 pub fn block_unindent(mut self, config: &Config) -> Indent {
131 self.block_indent -= config.tab_spaces;
135 pub fn width(&self) -> usize {
136 self.block_indent + self.alignment
139 pub fn to_string(&self, config: &Config) -> String {
140 let (num_tabs, num_spaces) = if config.hard_tabs {
141 (self.block_indent / config.tab_spaces, self.alignment)
143 (0, self.block_indent + self.alignment)
145 let num_chars = num_tabs + num_spaces;
146 let mut indent = String::with_capacity(num_chars);
147 for _ in 0..num_tabs {
150 for _ in 0..num_spaces {
157 impl Add for Indent {
158 type Output = Indent;
160 fn add(self, rhs: Indent) -> Indent {
162 block_indent: self.block_indent + rhs.block_indent,
163 alignment: self.alignment + rhs.alignment,
168 impl Sub for Indent {
169 type Output = Indent;
171 fn sub(self, rhs: Indent) -> Indent {
172 Indent::new(self.block_indent - rhs.block_indent,
173 self.alignment - rhs.alignment)
177 impl Add<usize> for Indent {
178 type Output = Indent;
180 fn add(self, rhs: usize) -> Indent {
181 Indent::new(self.block_indent, self.alignment + rhs)
185 impl Sub<usize> for Indent {
186 type Output = Indent;
188 fn sub(self, rhs: usize) -> Indent {
189 Indent::new(self.block_indent, self.alignment - rhs)
194 // Line has exceeded character limit
196 // Line ends in whitespace
198 // TO-DO or FIX-ME item without an issue number
202 impl fmt::Display for ErrorKind {
203 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
205 ErrorKind::LineOverflow => write!(fmt, "line exceeded maximum length"),
206 ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
207 ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
212 // Formatting errors that are identified *after* rustfmt has run.
213 pub struct FormattingError {
218 impl FormattingError {
219 fn msg_prefix(&self) -> &str {
221 ErrorKind::LineOverflow |
222 ErrorKind::TrailingWhitespace => "Rustfmt failed at",
223 ErrorKind::BadIssue(_) => "WARNING:",
227 fn msg_suffix(&self) -> &str {
229 ErrorKind::LineOverflow |
230 ErrorKind::TrailingWhitespace => "(sorry)",
231 ErrorKind::BadIssue(_) => "",
236 pub struct FormatReport {
237 // Maps stringified file paths to their associated formatting errors.
238 file_error_map: HashMap<String, Vec<FormattingError>>,
242 pub fn warning_count(&self) -> usize {
243 self.file_error_map.iter().map(|(_, ref errors)| errors.len()).fold(0, |acc, x| acc + x)
247 impl fmt::Display for FormatReport {
248 // Prints all the formatting errors.
249 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
250 for (file, errors) in &self.file_error_map {
251 for error in errors {
258 error.msg_suffix()));
265 // Formatting which depends on the AST.
266 fn format_ast(krate: &ast::Crate,
267 parse_session: &ParseSess,
271 let mut file_map = FileMap::new();
272 for (path, module) in modules::list_files(krate, parse_session.codemap()) {
273 if config.skip_children && path.as_path() != main_file {
276 let path = path.to_str().unwrap();
278 println!("Formatting {}", path);
280 let mut visitor = FmtVisitor::from_codemap(parse_session, config);
281 visitor.format_separate_mod(module);
282 file_map.insert(path.to_owned(), visitor.buffer);
287 // Formatting done on a char by char or line by line basis.
288 // TODO(#209) warn on bad license
289 // TODO(#20) other stuff for parity with make tidy
290 fn format_lines(file_map: &mut FileMap, config: &Config) -> FormatReport {
291 let mut truncate_todo = Vec::new();
292 let mut report = FormatReport { file_error_map: HashMap::new() };
294 // Iterate over the chars in the file map.
295 for (f, text) in file_map.iter() {
296 let mut trims = vec![];
297 let mut last_wspace: Option<usize> = None;
298 let mut line_len = 0;
299 let mut cur_line = 1;
300 let mut newline_count = 0;
301 let mut errors = vec![];
302 let mut issue_seeker = BadIssueSeeker::new(config.report_todo, config.report_fixme);
304 for (c, b) in text.chars() {
306 line_len += c.len_utf8();
310 // Add warnings for bad todos/ fixmes
311 if let Some(issue) = issue_seeker.inspect(c) {
312 errors.push(FormattingError {
314 kind: ErrorKind::BadIssue(issue),
319 // Check for (and record) trailing whitespace.
320 if let Some(lw) = last_wspace {
321 trims.push((cur_line, lw, b));
324 // Check for any line width errors we couldn't correct.
325 if line_len > config.max_width {
326 errors.push(FormattingError {
328 kind: ErrorKind::LineOverflow,
337 line_len += c.len_utf8();
338 if c.is_whitespace() {
339 if last_wspace.is_none() {
340 last_wspace = Some(b);
348 if newline_count > 1 {
349 debug!("track truncate: {} {} {}", f, text.len, newline_count);
350 truncate_todo.push((f.to_owned(), text.len - newline_count + 1))
353 for &(l, _, _) in &trims {
354 errors.push(FormattingError {
356 kind: ErrorKind::TrailingWhitespace,
360 report.file_error_map.insert(f.to_owned(), errors);
363 for (f, l) in truncate_todo {
364 file_map.get_mut(&f).unwrap().truncate(l);
370 fn parse_input(input: Input, parse_session: &ParseSess) -> Result<ast::Crate, DiagnosticBuilder> {
371 let krate = match input {
372 Input::File(file) => parse::parse_crate_from_file(&file, Vec::new(), &parse_session),
373 Input::Text(text) => {
374 parse::parse_crate_from_source_str("stdin".to_owned(), text, Vec::new(), &parse_session)
381 pub fn format_input(input: Input, config: &Config) -> (FileMap, FormatReport) {
382 let codemap = Rc::new(CodeMap::new());
384 let tty_handler = Handler::with_tty_emitter(ColorConfig::Auto,
389 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
391 let main_file = match input {
392 Input::File(ref file) => file.clone(),
393 Input::Text(..) => PathBuf::from("stdin"),
396 let krate = match parse_input(input, &parse_session) {
398 Err(mut diagnostic) => {
400 panic!("Unrecoverable parse error");
404 // Suppress error output after parsing.
405 let silent_emitter = Box::new(EmitterWriter::new(Box::new(Vec::new()), None, codemap.clone()));
406 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
408 let mut file_map = format_ast(&krate, &parse_session, &main_file, config);
410 // For some reason, the codemap does not include terminating
411 // newlines so we must add one on for each file. This is sad.
412 filemap::append_newlines(&mut file_map);
414 let report = format_lines(&mut file_map, config);
423 pub fn run(input: Input, config: &Config) {
424 let (file_map, report) = format_input(input, config);
427 let mut out = stdout();
428 let write_result = filemap::write_all_files(&file_map, &mut out, config);
430 if let Err(msg) = write_result {
431 msg!("Error writing files: {}", msg);