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)]
17 extern crate rustc_errors as errors;
20 extern crate serde_derive;
21 extern crate serde_json;
25 extern crate unicode_segmentation;
27 use std::collections::HashMap;
29 use std::io::{self, stdout, Write};
30 use std::iter::repeat;
31 use std::path::{Path, PathBuf};
34 use errors::{DiagnosticBuilder, Handler};
35 use errors::emitter::{ColorConfig, EmitterWriter};
36 use strings::string_buffer::StringBuffer;
38 use syntax::codemap::{CodeMap, FilePathMapping};
39 use syntax::parse::{self, ParseSess};
41 use checkstyle::{output_footer, output_header};
44 use issues::{BadIssueSeeker, Issue};
46 use visitor::FmtVisitor;
48 pub use self::summary::Summary;
79 // Line has exceeded character limit (found, maximum)
80 LineOverflow(usize, usize),
81 // Line ends in whitespace
83 // TO-DO or FIX-ME item without an issue number
87 impl fmt::Display for ErrorKind {
88 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
90 ErrorKind::LineOverflow(found, maximum) => write!(
92 "line exceeded maximum width (maximum: {}, found: {})",
96 ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
97 ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
102 // Formatting errors that are identified *after* rustfmt has run.
103 pub struct FormattingError {
110 impl FormattingError {
111 fn msg_prefix(&self) -> &str {
113 ErrorKind::LineOverflow(..) | ErrorKind::TrailingWhitespace => "error:",
114 ErrorKind::BadIssue(_) => "WARNING:",
118 fn msg_suffix(&self) -> &str {
120 ErrorKind::LineOverflow(..) if self.is_comment => {
121 "use `error_on_line_overflow_comments = false` to suppress \
122 the warning against line comments\n"
129 pub fn format_len(&self) -> (usize, usize) {
131 ErrorKind::LineOverflow(found, max) => (max, found - max),
132 ErrorKind::TrailingWhitespace => {
133 let trailing_ws_len = self.line_buffer
136 .take_while(|c| c.is_whitespace())
138 (self.line_buffer.len() - trailing_ws_len, trailing_ws_len)
145 pub struct FormatReport {
146 // Maps stringified file paths to their associated formatting errors.
147 file_error_map: HashMap<String, Vec<FormattingError>>,
151 fn new() -> FormatReport {
153 file_error_map: HashMap::new(),
157 pub fn warning_count(&self) -> usize {
160 .map(|(_, errors)| errors.len())
161 .fold(0, |acc, x| acc + x)
164 pub fn has_warnings(&self) -> bool {
165 self.warning_count() > 0
168 pub fn print_warnings_fancy(
170 mut t: Box<term::Terminal<Output = io::Stderr>>,
171 ) -> Result<(), term::Error> {
172 for (file, errors) in &self.file_error_map {
173 for error in errors {
174 let prefix_space_len = error.line.to_string().len();
175 let prefix_spaces: String = repeat(" ").take(1 + prefix_space_len).collect();
177 // First line: the overview of error
178 t.fg(term::color::RED)?;
179 t.attr(term::Attr::Bold)?;
180 write!(t, "{} ", error.msg_prefix())?;
182 t.attr(term::Attr::Bold)?;
183 write!(t, "{}\n", error.kind)?;
185 // Second line: file info
186 write!(t, "{}--> ", &prefix_spaces[1..])?;
188 write!(t, "{}:{}\n", file, error.line)?;
190 // Third to fifth lines: show the line which triggered error, if available.
191 if !error.line_buffer.is_empty() {
192 let (space_len, target_len) = error.format_len();
193 t.attr(term::Attr::Bold)?;
194 write!(t, "{}|\n{} | ", prefix_spaces, error.line)?;
196 write!(t, "{}\n", error.line_buffer)?;
197 t.attr(term::Attr::Bold)?;
198 write!(t, "{}| ", prefix_spaces)?;
199 t.fg(term::color::RED)?;
200 write!(t, "{}\n", target_str(space_len, target_len))?;
204 // The last line: show note if available.
205 let msg_suffix = error.msg_suffix();
206 if !msg_suffix.is_empty() {
207 t.attr(term::Attr::Bold)?;
208 write!(t, "{}= note: ", prefix_spaces)?;
210 write!(t, "{}\n", error.msg_suffix())?;
218 if !self.file_error_map.is_empty() {
219 t.attr(term::Attr::Bold)?;
220 write!(t, "warning: ")?;
224 "rustfmt may have failed to format. See previous {} errors.\n\n",
225 self.warning_count(),
233 fn target_str(space_len: usize, target_len: usize) -> String {
234 let empty_line: String = repeat(" ").take(space_len).collect();
235 let overflowed: String = repeat("^").take(target_len).collect();
236 empty_line + &overflowed
239 impl fmt::Display for FormatReport {
240 // Prints all the formatting errors.
241 fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
242 for (file, errors) in &self.file_error_map {
243 for error in errors {
244 let prefix_space_len = error.line.to_string().len();
245 let prefix_spaces: String = repeat(" ").take(1 + prefix_space_len).collect();
247 let error_line_buffer = if error.line_buffer.is_empty() {
250 let (space_len, target_len) = error.format_len();
252 "{}|\n{} | {}\n{}| {}",
257 target_str(space_len, target_len)
261 let error_info = format!("{} {}", error.msg_prefix(), error.kind);
262 let file_info = format!("{}--> {}:{}", &prefix_spaces[1..], file, error.line);
263 let msg_suffix = error.msg_suffix();
264 let note = if msg_suffix.is_empty() {
267 format!("{}note= ", prefix_spaces)
272 "{}\n{}\n{}\n{}{}\n",
281 if !self.file_error_map.is_empty() {
284 "warning: rustfmt may have failed to format. See previous {} errors.\n",
285 self.warning_count(),
292 // Formatting which depends on the AST.
295 parse_session: &mut ParseSess,
299 ) -> Result<(FileMap, bool), io::Error>
301 F: FnMut(&str, &mut StringBuffer) -> Result<bool, io::Error>,
303 let mut result = FileMap::new();
304 // diff mode: check if any files are differing
305 let mut has_diff = false;
307 // We always skip children for the "Plain" write mode, since there is
308 // nothing to distinguish the nested module contents.
309 let skip_children = config.skip_children() || config.write_mode() == config::WriteMode::Plain;
310 for (path, module) in modules::list_files(krate, parse_session.codemap()) {
311 if skip_children && path.as_path() != main_file {
314 let path_str = path.to_str().unwrap();
315 if config.verbose() {
316 println!("Formatting {}", path_str);
318 let mut visitor = FmtVisitor::from_codemap(parse_session, config);
319 let filemap = visitor.codemap.lookup_char_pos(module.inner.lo()).file;
320 // Format inner attributes if available.
321 if !krate.attrs.is_empty() && path == main_file {
322 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
323 visitor.push_rewrite(module.inner, None);
325 visitor.format_separate_mod(module, &*filemap);
328 visitor.last_pos = filemap.start_pos;
329 visitor.format_separate_mod(module, &*filemap);
332 has_diff |= after_file(path_str, &mut visitor.buffer)?;
334 result.push((path_str.to_owned(), visitor.buffer));
337 Ok((result, has_diff))
340 // Formatting done on a char by char or line by line basis.
341 // FIXME(#209) warn on bad license
342 // FIXME(#20) other stuff for parity with make tidy
343 fn format_lines(text: &mut StringBuffer, name: &str, config: &Config, report: &mut FormatReport) {
344 // Iterate over the chars in the file map.
345 let mut trims = vec![];
346 let mut last_wspace: Option<usize> = None;
347 let mut line_len = 0;
348 let mut cur_line = 1;
349 let mut newline_count = 0;
350 let mut errors = vec![];
351 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
352 let mut prev_char: Option<char> = None;
353 let mut is_comment = false;
354 let mut line_buffer = String::with_capacity(config.max_width() * 2);
356 for (c, b) in text.chars() {
361 let format_line = config.file_lines().contains_line(name, cur_line as usize);
364 // Add warnings for bad todos/ fixmes
365 if let Some(issue) = issue_seeker.inspect(c) {
366 errors.push(FormattingError {
368 kind: ErrorKind::BadIssue(issue),
370 line_buffer: String::new(),
377 // Check for (and record) trailing whitespace.
378 if let Some(lw) = last_wspace {
379 trims.push((cur_line, lw, b, line_buffer.clone()));
383 // Check for any line width errors we couldn't correct.
384 let report_error_on_line_overflow = config.error_on_line_overflow()
385 && (config.error_on_line_overflow_comments() || !is_comment);
386 if report_error_on_line_overflow && line_len > config.max_width() {
387 errors.push(FormattingError {
389 kind: ErrorKind::LineOverflow(line_len, config.max_width()),
390 is_comment: is_comment,
391 line_buffer: line_buffer.clone(),
406 if c.is_whitespace() {
407 if last_wspace.is_none() {
408 last_wspace = Some(b);
411 if let Some('/') = prev_char {
423 if newline_count > 1 {
424 debug!("track truncate: {} {}", text.len, newline_count);
425 let line = text.len - newline_count + 1;
429 for &(l, _, _, ref b) in &trims {
430 errors.push(FormattingError {
432 kind: ErrorKind::TrailingWhitespace,
434 line_buffer: b.clone(),
438 report.file_error_map.insert(name.to_owned(), errors);
443 parse_session: &ParseSess,
444 ) -> Result<ast::Crate, Option<DiagnosticBuilder>> {
445 let result = match input {
446 Input::File(file) => {
447 let mut parser = parse::new_parser_from_file(parse_session, &file);
448 parser.cfg_mods = false;
449 parser.parse_crate_mod()
451 Input::Text(text) => {
453 parse::new_parser_from_source_str(parse_session, "stdin".to_owned(), text);
454 parser.cfg_mods = false;
455 parser.parse_crate_mod()
461 if parse_session.span_diagnostic.has_errors() {
462 // Bail out if the parser recovered from an error.
468 Err(e) => Err(Some(e)),
472 pub fn format_input<T: Write>(
475 mut out: Option<&mut T>,
476 ) -> Result<(Summary, FileMap, FormatReport), (io::Error, Summary)> {
477 let mut summary = Summary::default();
478 if config.disable_all_formatting() {
479 // When the input is from stdin, echo back the input.
480 if let Input::Text(ref buf) = input {
481 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
482 return Err((e, summary));
485 return Ok((summary, FileMap::new(), FormatReport::new()));
487 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
490 Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(codemap.clone()));
491 let mut parse_session = ParseSess::with_span_handler(tty_handler, codemap.clone());
493 let main_file = match input {
494 Input::File(ref file) => file.clone(),
495 Input::Text(..) => PathBuf::from("stdin"),
498 let krate = match parse_input(input, &parse_session) {
501 if let Some(mut diagnostic) = diagnostic {
504 summary.add_parsing_error();
505 return Ok((summary, FileMap::new(), FormatReport::new()));
509 if parse_session.span_diagnostic.has_errors() {
510 summary.add_parsing_error();
513 // Suppress error output after parsing.
514 let silent_emitter = Box::new(EmitterWriter::new(
515 Box::new(Vec::new()),
516 Some(codemap.clone()),
518 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
520 let mut report = FormatReport::new();
528 // For some reason, the codemap does not include terminating
529 // newlines so we must add one on for each file. This is sad.
530 filemap::append_newline(file);
532 format_lines(file, file_name, config, &mut report);
534 if let Some(ref mut out) = out {
535 return filemap::write_file(file, file_name, out, config);
540 Ok((file_map, has_diff)) => {
541 if report.has_warnings() {
542 summary.add_formatting_error();
549 Ok((summary, file_map, report))
551 Err(e) => Err((e, summary)),
561 pub fn run(input: Input, config: &Config) -> Summary {
562 let out = &mut stdout();
563 output_header(out, config.write_mode()).ok();
564 match format_input(input, config, Some(out)) {
565 Ok((summary, _, report)) => {
566 output_footer(out, config.write_mode()).ok();
568 if report.has_warnings() {
569 match term::stderr() {
570 Some(ref t) if isatty() && t.supports_color() => {
571 match report.print_warnings_fancy(term::stderr().unwrap()) {
573 Err(..) => panic!("Unable to write to stderr: {}", report),
576 _ => msg!("{}", report),
582 Err((msg, mut summary)) => {
583 msg!("Error writing files: {}", msg);
584 summary.add_operational_error();