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;
46 pub use self::summary::Summary;
71 const MIN_STRING: usize = 10;
72 // When we get scoped annotations, we should have rustfmt::skip.
73 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
76 fn span(&self) -> Span;
79 impl Spanned for ast::Expr {
80 fn span(&self) -> Span {
85 impl Spanned for ast::Pat {
86 fn span(&self) -> Span {
91 impl Spanned for ast::Ty {
92 fn span(&self) -> Span {
97 impl Spanned for ast::Arg {
98 fn span(&self) -> Span {
99 if items::is_named_arg(self) {
100 mk_sp(self.pat.span.lo, self.ty.span.hi)
107 #[derive(Copy, Clone, Debug)]
109 // Width of the block indent, in characters. Must be a multiple of
110 // Config::tab_spaces.
111 pub block_indent: usize,
112 // Alignment in characters.
113 pub alignment: usize,
117 pub fn new(block_indent: usize, alignment: usize) -> Indent {
119 block_indent: block_indent,
120 alignment: alignment,
124 pub fn empty() -> Indent {
128 pub fn block_indent(mut self, config: &Config) -> Indent {
129 self.block_indent += config.tab_spaces;
133 pub fn block_unindent(mut self, config: &Config) -> Indent {
134 self.block_indent -= config.tab_spaces;
138 pub fn width(&self) -> usize {
139 self.block_indent + self.alignment
142 pub fn to_string(&self, config: &Config) -> String {
143 let (num_tabs, num_spaces) = if config.hard_tabs {
144 (self.block_indent / config.tab_spaces, self.alignment)
146 (0, self.block_indent + self.alignment)
148 let num_chars = num_tabs + num_spaces;
149 let mut indent = String::with_capacity(num_chars);
150 for _ in 0..num_tabs {
153 for _ in 0..num_spaces {
160 impl Add for Indent {
161 type Output = Indent;
163 fn add(self, rhs: Indent) -> Indent {
165 block_indent: self.block_indent + rhs.block_indent,
166 alignment: self.alignment + rhs.alignment,
171 impl Sub for Indent {
172 type Output = Indent;
174 fn sub(self, rhs: Indent) -> Indent {
175 Indent::new(self.block_indent - rhs.block_indent,
176 self.alignment - rhs.alignment)
180 impl Add<usize> for Indent {
181 type Output = Indent;
183 fn add(self, rhs: usize) -> Indent {
184 Indent::new(self.block_indent, self.alignment + rhs)
188 impl Sub<usize> for Indent {
189 type Output = Indent;
191 fn sub(self, rhs: usize) -> Indent {
192 Indent::new(self.block_indent, self.alignment - rhs)
197 // Line has exceeded character limit
199 // Line ends in whitespace
201 // TO-DO or FIX-ME item without an issue number
205 impl fmt::Display for ErrorKind {
206 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
208 ErrorKind::LineOverflow => write!(fmt, "line exceeded maximum length"),
209 ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
210 ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
215 // Formatting errors that are identified *after* rustfmt has run.
216 pub struct FormattingError {
221 impl FormattingError {
222 fn msg_prefix(&self) -> &str {
224 ErrorKind::LineOverflow |
225 ErrorKind::TrailingWhitespace => "Rustfmt failed at",
226 ErrorKind::BadIssue(_) => "WARNING:",
230 fn msg_suffix(&self) -> &str {
232 ErrorKind::LineOverflow |
233 ErrorKind::TrailingWhitespace => "(sorry)",
234 ErrorKind::BadIssue(_) => "",
239 pub struct FormatReport {
240 // Maps stringified file paths to their associated formatting errors.
241 file_error_map: HashMap<String, Vec<FormattingError>>,
245 fn new() -> FormatReport {
246 FormatReport { file_error_map: HashMap::new() }
249 pub fn warning_count(&self) -> usize {
250 self.file_error_map.iter().map(|(_, ref errors)| errors.len()).fold(0, |acc, x| acc + x)
253 pub fn has_warnings(&self) -> bool {
254 self.warning_count() > 0
258 impl fmt::Display for FormatReport {
259 // Prints all the formatting errors.
260 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
261 for (file, errors) in &self.file_error_map {
262 for error in errors {
269 error.msg_suffix()));
276 // Formatting which depends on the AST.
277 fn format_ast(krate: &ast::Crate,
278 parse_session: &ParseSess,
282 let mut file_map = FileMap::new();
283 // We always skip children for the "Plain" write mode, since there is
284 // nothing to distinguish the nested module contents.
285 let skip_children = config.skip_children || config.write_mode == config::WriteMode::Plain;
286 for (path, module) in modules::list_files(krate, parse_session.codemap()) {
287 if skip_children && path.as_path() != main_file {
290 let path = path.to_str().unwrap();
292 println!("Formatting {}", path);
294 let mut visitor = FmtVisitor::from_codemap(parse_session, config);
295 visitor.format_separate_mod(module);
296 file_map.insert(path.to_owned(), visitor.buffer);
301 // Formatting done on a char by char or line by line basis.
302 // TODO(#209) warn on bad license
303 // TODO(#20) other stuff for parity with make tidy
304 fn format_lines(file_map: &mut FileMap, config: &Config) -> FormatReport {
305 let mut truncate_todo = Vec::new();
306 let mut report = FormatReport::new();
308 // Iterate over the chars in the file map.
309 for (f, text) in file_map.iter() {
310 let mut trims = vec![];
311 let mut last_wspace: Option<usize> = None;
312 let mut line_len = 0;
313 let mut cur_line = 1;
314 let mut newline_count = 0;
315 let mut errors = vec![];
316 let mut issue_seeker = BadIssueSeeker::new(config.report_todo, config.report_fixme);
318 for (c, b) in text.chars() {
320 line_len += c.len_utf8();
324 // Add warnings for bad todos/ fixmes
325 if let Some(issue) = issue_seeker.inspect(c) {
326 errors.push(FormattingError {
328 kind: ErrorKind::BadIssue(issue),
333 // Check for (and record) trailing whitespace.
334 if let Some(lw) = last_wspace {
335 trims.push((cur_line, lw, b));
338 // Check for any line width errors we couldn't correct.
339 if line_len > config.max_width {
340 errors.push(FormattingError {
342 kind: ErrorKind::LineOverflow,
351 line_len += c.len_utf8();
352 if c.is_whitespace() {
353 if last_wspace.is_none() {
354 last_wspace = Some(b);
362 if newline_count > 1 {
363 debug!("track truncate: {} {} {}", f, text.len, newline_count);
364 truncate_todo.push((f.to_owned(), text.len - newline_count + 1))
367 for &(l, _, _) in &trims {
368 errors.push(FormattingError {
370 kind: ErrorKind::TrailingWhitespace,
374 report.file_error_map.insert(f.to_owned(), errors);
377 for (f, l) in truncate_todo {
378 file_map.get_mut(&f).unwrap().truncate(l);
384 fn parse_input(input: Input,
385 parse_session: &ParseSess)
386 -> Result<ast::Crate, Option<DiagnosticBuilder>> {
387 let result = match input {
388 Input::File(file) => parse::parse_crate_from_file(&file, Vec::new(), &parse_session),
389 Input::Text(text) => {
390 parse::parse_crate_from_source_str("stdin".to_owned(), text, Vec::new(), &parse_session)
394 // Bail out if the parser recovered from an error.
395 if parse_session.span_diagnostic.has_errors() {
399 result.map_err(|e| Some(e))
402 pub fn format_input(input: Input, config: &Config) -> (Summary, FileMap, FormatReport) {
403 let mut summary = Summary::new();
404 let codemap = Rc::new(CodeMap::new());
406 let tty_handler = Handler::with_tty_emitter(ColorConfig::Auto,
411 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
413 let main_file = match input {
414 Input::File(ref file) => file.clone(),
415 Input::Text(..) => PathBuf::from("stdin"),
418 let krate = match parse_input(input, &parse_session) {
421 if let Some(mut diagnostic) = diagnostic {
424 summary.add_parsing_error();
425 return (summary, FileMap::new(), FormatReport::new());
429 if parse_session.span_diagnostic.has_errors() {
430 summary.add_parsing_error();
433 // Suppress error output after parsing.
434 let silent_emitter = Box::new(EmitterWriter::new(Box::new(Vec::new()), None, codemap.clone()));
435 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
437 let mut file_map = format_ast(&krate, &parse_session, &main_file, config);
439 // For some reason, the codemap does not include terminating
440 // newlines so we must add one on for each file. This is sad.
441 filemap::append_newlines(&mut file_map);
443 let report = format_lines(&mut file_map, config);
444 if report.has_warnings() {
445 summary.add_formatting_error();
447 (summary, file_map, report)
455 pub fn run(input: Input, config: &Config) -> Summary {
456 let (mut summary, file_map, report) = format_input(input, config);
457 if report.has_warnings() {
461 let mut out = stdout();
462 let write_result = filemap::write_all_files(&file_map, &mut out, config);
464 if let Err(msg) = write_result {
465 msg!("Error writing files: {}", msg);
466 summary.add_operational_error();