1 // High level formatting functions.
3 use std::collections::HashMap;
4 use std::io::{self, Write};
5 use std::panic::{catch_unwind, AssertUnwindSafe};
7 use std::time::{Duration, Instant};
10 use syntax::codemap::{CodeMap, FilePathMapping, Span};
11 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
12 use syntax::errors::{DiagnosticBuilder, Handler};
13 use syntax::parse::{self, ParseSess};
15 use comment::{CharClasses, FullCodeCharKind};
16 use config::{Config, FileName, NewlineStyle, Verbosity};
17 use issues::BadIssueSeeker;
18 use visitor::{FmtVisitor, SnippetProvider};
19 use {filemap, modules, ErrorKind, FormatReport, Input, Session};
21 // A map of the files of a crate, with their new content
22 pub(crate) type FileMap = Vec<FileRecord>;
23 pub(crate) type FileRecord = (FileName, String);
25 pub(crate) struct FormattingError {
26 pub(crate) line: usize,
27 pub(crate) kind: ErrorKind,
30 pub(crate) line_buffer: String,
33 impl FormattingError {
34 pub(crate) fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
36 line: codemap.lookup_char_pos(span.lo()).line,
37 is_comment: kind.is_comment(),
45 .get_line(fl.lines[0].line_index)
46 .map(|l| l.into_owned())
48 .unwrap_or_else(|| String::new()),
52 pub(crate) fn msg_prefix(&self) -> &str {
54 ErrorKind::LineOverflow(..)
55 | ErrorKind::TrailingWhitespace
56 | ErrorKind::IoError(_)
57 | ErrorKind::ParseError
58 | ErrorKind::LostComment => "internal error:",
59 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
60 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
64 pub(crate) fn msg_suffix(&self) -> &str {
65 if self.is_comment || self.is_string {
66 "set `error_on_unformatted = false` to suppress \
67 the warning against comments or string literals\n"
74 pub(crate) fn format_len(&self) -> (usize, usize) {
76 ErrorKind::LineOverflow(found, max) => (max, found - max),
77 ErrorKind::TrailingWhitespace
78 | ErrorKind::DeprecatedAttr
80 | ErrorKind::LostComment => {
81 let trailing_ws_start = self
83 .rfind(|c: char| !c.is_whitespace())
88 self.line_buffer.len() - trailing_ws_start,
96 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
98 #[derive(Default, Debug)]
99 pub(crate) struct ReportedErrors {
100 pub(crate) has_operational_errors: bool,
101 pub(crate) has_check_errors: bool,
104 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
108 if config.verbose() == Verbosity::Verbose && !is_stdin {
113 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
114 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
117 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
120 fn should_report_error(
122 char_kind: FullCodeCharKind,
124 error_kind: &ErrorKind,
126 let allow_error_report = if char_kind.is_comment() || is_string || error_kind.is_comment() {
127 config.error_on_unformatted()
133 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
134 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
139 // Formatting done on a char by char or line by line basis.
140 // FIXME(#20) other stuff for parity with make tidy
144 skipped_range: &[(usize, usize)],
146 report: &FormatReport,
148 let mut last_was_space = false;
149 let mut line_len = 0;
150 let mut cur_line = 1;
151 let mut newline_count = 0;
152 let mut errors = vec![];
153 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
154 let mut line_buffer = String::with_capacity(config.max_width() * 2);
155 let mut is_string = false; // true if the current line contains a string literal.
156 let mut format_line = config.file_lines().contains_line(name, cur_line);
157 let allow_issue_seek = !issue_seeker.is_disabled();
160 if let Some(ref license_template) = config.license_template {
161 if !license_template.is_match(text) {
162 errors.push(FormattingError {
164 kind: ErrorKind::LicenseCheck,
167 line_buffer: String::new(),
172 // Iterate over the chars in the file map.
173 for (kind, c) in CharClasses::new(text.chars()) {
178 if allow_issue_seek && format_line {
179 // Add warnings for bad todos/ fixmes
180 if let Some(issue) = issue_seeker.inspect(c) {
181 errors.push(FormattingError {
183 kind: ErrorKind::BadIssue(issue),
186 line_buffer: String::new(),
193 // Check for (and record) trailing whitespace.
195 if should_report_error(config, kind, is_string, &ErrorKind::TrailingWhitespace)
196 && !is_skipped_line(cur_line, skipped_range)
198 errors.push(FormattingError {
200 kind: ErrorKind::TrailingWhitespace,
201 is_comment: kind.is_comment(),
202 is_string: kind.is_string(),
203 line_buffer: line_buffer.clone(),
209 // Check for any line width errors we couldn't correct.
210 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
211 if line_len > config.max_width()
212 && !is_skipped_line(cur_line, skipped_range)
213 && should_report_error(config, kind, is_string, &error_kind)
215 errors.push(FormattingError {
218 is_comment: kind.is_comment(),
220 line_buffer: line_buffer.clone(),
227 format_line = config.file_lines().contains_line(name, cur_line);
229 last_was_space = false;
234 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
235 last_was_space = c.is_whitespace();
237 if kind.is_string() {
243 if newline_count > 1 {
244 debug!("track truncate: {} {}", text.len(), newline_count);
245 let line = text.len() - newline_count + 1;
249 report.append(name.clone(), errors);
252 fn parse_input<'sess>(
254 parse_session: &'sess ParseSess,
256 ) -> Result<ast::Crate, ParseError<'sess>> {
257 let mut parser = match input {
258 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
259 Input::Text(text) => parse::new_parser_from_source_str(
261 syntax::codemap::FileName::Custom("stdin".to_owned()),
266 parser.cfg_mods = false;
267 if config.skip_children() {
268 parser.recurse_into_file_modules = false;
271 let mut parser = AssertUnwindSafe(parser);
272 let result = catch_unwind(move || parser.0.parse_crate_mod());
276 if parse_session.span_diagnostic.has_errors() {
277 // Bail out if the parser recovered from an error.
278 Err(ParseError::Recovered)
283 Ok(Err(e)) => Err(ParseError::Error(e)),
284 Err(_) => Err(ParseError::Panic),
288 /// All the ways that parsing can fail.
289 enum ParseError<'sess> {
290 /// There was an error, but the parser recovered.
292 /// There was an error (supplied) and parsing failed.
293 Error(DiagnosticBuilder<'sess>),
294 /// The parser panicked.
298 impl<'b, T: Write + 'b> Session<'b, T> {
299 pub(crate) fn format_input_inner(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
300 if !self.config.version_meets_requirement() {
301 return Err(ErrorKind::VersionMismatch);
304 syntax::with_globals(|| {
305 syntax_pos::hygiene::set_default_edition(
306 self.config.edition().to_libsyntax_pos_edition(),
309 if self.config.disable_all_formatting() {
310 // When the input is from stdin, echo back the input.
311 if let Input::Text(ref buf) = input {
312 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
313 return Err(From::from(e));
316 return Ok(FormatReport::new());
319 let config = &self.config.clone();
320 let format_result = format_project(input, config, self);
322 format_result.map(|(report, summary)| {
323 self.summary.add(summary);
330 // Handle the results of formatting.
331 trait FormatHandler {
332 fn handle_formatted_file(&mut self, path: FileName, result: String) -> Result<(), ErrorKind>;
335 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
336 // Called for each formatted file.
337 fn handle_formatted_file(
341 ) -> Result<(), ErrorKind> {
342 if let Some(ref mut out) = self.out {
343 match filemap::write_file(&mut result, &path, out, &self.config) {
344 Ok(b) if b => self.summary.add_diff(),
346 // Create a new error with path_str to help users see which files failed
347 let err_msg = format!("{}: {}", path, e);
348 return Err(io::Error::new(e.kind(), err_msg).into());
354 self.filemap.push((path, result));
359 // Format an entire crate (or subset of the module tree).
360 fn format_project<T: FormatHandler>(
364 ) -> Result<(FormatReport, Summary), ErrorKind> {
365 let mut summary = Summary::default();
366 let mut timer = Timer::Initialized(Instant::now());
368 let input_is_stdin = input.is_text();
369 let main_file = match input {
370 Input::File(ref file) => FileName::Real(file.clone()),
371 Input::Text(..) => FileName::Stdin,
375 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
376 let mut parse_session = make_parse_sess(codemap.clone(), config);
377 let krate = match parse_input(input, &parse_session, config) {
381 ParseError::Error(mut diagnostic) => diagnostic.emit(),
382 ParseError::Panic => {
383 // Note that if you see this message and want more information,
384 // then go to `parse_input` and run the parse function without
385 // `catch_unwind` so rustfmt panics and you can get a backtrace.
386 should_emit_verbose(!input_is_stdin, config, || {
387 println!("The Rust parser panicked")
390 ParseError::Recovered => {}
392 summary.add_parsing_error();
393 return Err(ErrorKind::ParseError);
396 timer = timer.done_parsing();
398 // Suppress error output if we have to do any further parsing.
399 let silent_emitter = Box::new(EmitterWriter::new(
400 Box::new(Vec::new()),
401 Some(codemap.clone()),
405 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
407 let mut context = FormatContext::new(
416 let files = modules::list_files(&krate, context.parse_session.codemap())?;
417 for (path, module) in files {
418 if (config.skip_children() && path != main_file) || config.ignore().skip_file(&path) {
421 should_emit_verbose(!input_is_stdin, config, || println!("Formatting {}", path));
422 let is_root = path == main_file;
423 context.format_file(path, module, is_root)?;
425 timer = timer.done_formatting();
427 should_emit_verbose(!input_is_stdin, config, || {
429 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
430 timer.get_parse_time(),
431 timer.get_format_time(),
435 if context.report.has_warnings() {
436 context.summary.add_formatting_error();
439 let report_errs = &context.report.internal.borrow().1;
440 if report_errs.has_check_errors {
441 context.summary.add_check_error();
443 if report_errs.has_operational_errors {
444 context.summary.add_operational_error();
448 Ok((context.report, context.summary))
451 // Used for formatting files.
453 struct FormatContext<'a, T: FormatHandler + 'a> {
454 krate: &'a ast::Crate,
455 report: FormatReport,
457 parse_session: ParseSess,
462 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
463 // Formats a single file/module.
469 ) -> Result<(), ErrorKind> {
473 .lookup_char_pos(module.inner.lo())
475 let big_snippet = filemap.src.as_ref().unwrap();
476 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
477 let mut visitor = FmtVisitor::from_codemap(
483 // Format inner attributes if available.
484 if !self.krate.attrs.is_empty() && is_root {
485 visitor.skip_empty_lines(filemap.end_pos);
486 if visitor.visit_attrs(&self.krate.attrs, ast::AttrStyle::Inner) {
487 visitor.push_rewrite(module.inner, None);
489 visitor.format_separate_mod(module, &*filemap);
492 visitor.last_pos = filemap.start_pos;
493 visitor.skip_empty_lines(filemap.end_pos);
494 visitor.format_separate_mod(module, &*filemap);
499 ::utils::count_newlines(&visitor.buffer)
502 // For some reason, the codemap does not include terminating
503 // newlines so we must add one on for each file. This is sad.
504 filemap::append_newline(&mut visitor.buffer);
509 &visitor.skipped_range,
513 replace_with_system_newlines(&mut visitor.buffer, &self.config);
515 if visitor.macro_rewrite_failure {
516 self.summary.add_macro_format_failure();
519 self.handler.handle_formatted_file(path, visitor.buffer)
523 fn make_parse_sess(codemap: Rc<CodeMap>, config: &Config) -> ParseSess {
524 let tty_handler = if config.hide_parse_errors() {
525 let silent_emitter = Box::new(EmitterWriter::new(
526 Box::new(Vec::new()),
527 Some(codemap.clone()),
531 Handler::with_emitter(true, false, silent_emitter)
533 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
534 let color_cfg = if supports_color {
539 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
542 ParseSess::with_span_handler(tty_handler, codemap)
545 fn replace_with_system_newlines(text: &mut String, config: &Config) -> () {
546 let style = if config.newline_style() == NewlineStyle::Native {
548 NewlineStyle::Windows
553 config.newline_style()
557 NewlineStyle::Unix => return,
558 NewlineStyle::Windows => {
559 let mut transformed = String::with_capacity(text.capacity());
560 for c in text.chars() {
562 '\n' => transformed.push_str("\r\n"),
564 c => transformed.push(c),
569 NewlineStyle::Native => unreachable!(),
573 /// A single span of changed lines, with 0 or more removed lines
574 /// and a vector of 0 or more inserted lines.
575 #[derive(Debug, PartialEq, Eq)]
576 pub(crate) struct ModifiedChunk {
577 /// The first to be removed from the original text
578 pub line_number_orig: u32,
579 /// The number of lines which have been replaced
580 pub lines_removed: u32,
582 pub lines: Vec<String>,
585 /// Set of changed sections of a file.
586 #[derive(Debug, PartialEq, Eq)]
587 pub(crate) struct ModifiedLines {
588 /// The set of changed chunks.
589 pub chunks: Vec<ModifiedChunk>,
592 #[derive(Clone, Copy, Debug)]
594 Initialized(Instant),
595 DoneParsing(Instant, Instant),
596 DoneFormatting(Instant, Instant, Instant),
600 fn done_parsing(self) -> Self {
602 Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
603 _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
607 fn done_formatting(self) -> Self {
609 Timer::DoneParsing(init_time, parse_time) => {
610 Timer::DoneFormatting(init_time, parse_time, Instant::now())
612 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
616 /// Returns the time it took to parse the source files in seconds.
617 fn get_parse_time(&self) -> f32 {
619 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
620 // This should never underflow since `Instant::now()` guarantees monotonicity.
621 Self::duration_to_f32(parse_time.duration_since(init))
623 Timer::Initialized(..) => unreachable!(),
627 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
629 fn get_format_time(&self) -> f32 {
631 Timer::DoneFormatting(_init, parse_time, format_time) => {
632 Self::duration_to_f32(format_time.duration_since(parse_time))
634 Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
638 fn duration_to_f32(d: Duration) -> f32 {
639 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
643 /// A summary of a Rustfmt run.
644 #[derive(Debug, Default, Clone, Copy)]
646 // Encountered e.g. an IO error.
647 has_operational_errors: bool,
649 // Failed to reformat code because of parsing errors.
650 has_parsing_errors: bool,
652 // Code is valid, but it is impossible to format it properly.
653 has_formatting_errors: bool,
655 // Code contains macro call that was unable to format.
656 pub(crate) has_macro_format_failure: bool,
658 // Failed a check, such as the license check or other opt-in checking.
659 has_check_errors: bool,
661 /// Formatted code differs from existing code (--check only).
666 pub fn has_operational_errors(&self) -> bool {
667 self.has_operational_errors
670 pub fn has_parsing_errors(&self) -> bool {
671 self.has_parsing_errors
674 pub fn has_formatting_errors(&self) -> bool {
675 self.has_formatting_errors
678 pub fn has_check_errors(&self) -> bool {
679 self.has_check_errors
682 pub(crate) fn has_macro_formatting_failure(&self) -> bool {
683 self.has_macro_format_failure
686 pub fn add_operational_error(&mut self) {
687 self.has_operational_errors = true;
690 pub(crate) fn add_parsing_error(&mut self) {
691 self.has_parsing_errors = true;
694 pub(crate) fn add_formatting_error(&mut self) {
695 self.has_formatting_errors = true;
698 pub(crate) fn add_check_error(&mut self) {
699 self.has_check_errors = true;
702 pub(crate) fn add_diff(&mut self) {
703 self.has_diff = true;
706 pub(crate) fn add_macro_format_failure(&mut self) {
707 self.has_macro_format_failure = true;
710 pub fn has_no_errors(&self) -> bool {
711 !(self.has_operational_errors
712 || self.has_parsing_errors
713 || self.has_formatting_errors
717 /// Combine two summaries together.
718 pub fn add(&mut self, other: Summary) {
719 self.has_operational_errors |= other.has_operational_errors;
720 self.has_formatting_errors |= other.has_formatting_errors;
721 self.has_macro_format_failure |= other.has_macro_format_failure;
722 self.has_parsing_errors |= other.has_parsing_errors;
723 self.has_check_errors |= other.has_check_errors;
724 self.has_diff |= other.has_diff;