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>;
24 pub(crate) type FileRecord = (FileName, String);
26 pub(crate) struct FormattingError {
27 pub(crate) line: usize,
28 pub(crate) kind: ErrorKind,
31 pub(crate) line_buffer: String,
34 impl FormattingError {
35 pub(crate) fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
37 line: codemap.lookup_char_pos(span.lo()).line,
38 is_comment: kind.is_comment(),
46 .get_line(fl.lines[0].line_index)
47 .map(|l| l.into_owned())
49 .unwrap_or_else(|| String::new()),
53 pub(crate) fn msg_prefix(&self) -> &str {
55 ErrorKind::LineOverflow(..)
56 | ErrorKind::TrailingWhitespace
57 | ErrorKind::IoError(_)
58 | ErrorKind::ParseError
59 | ErrorKind::LostComment => "internal error:",
60 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
61 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
65 pub(crate) fn msg_suffix(&self) -> &str {
66 if self.is_comment || self.is_string {
67 "set `error_on_unformatted = false` to suppress \
68 the warning against comments or string literals\n"
75 pub(crate) fn format_len(&self) -> (usize, usize) {
77 ErrorKind::LineOverflow(found, max) => (max, found - max),
78 ErrorKind::TrailingWhitespace
79 | ErrorKind::DeprecatedAttr
81 | ErrorKind::LostComment => {
82 let trailing_ws_start = self
84 .rfind(|c: char| !c.is_whitespace())
89 self.line_buffer.len() - trailing_ws_start,
97 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
99 #[derive(Default, Debug)]
100 pub(crate) struct ReportedErrors {
101 pub(crate) has_operational_errors: bool,
102 pub(crate) has_check_errors: bool,
105 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
109 if config.verbose() == Verbosity::Verbose && !is_stdin {
114 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
115 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
118 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
121 fn should_report_error(
123 char_kind: FullCodeCharKind,
125 error_kind: &ErrorKind,
127 let allow_error_report = if char_kind.is_comment() || is_string || error_kind.is_comment() {
128 config.error_on_unformatted()
134 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
135 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
140 // Formatting done on a char by char or line by line basis.
141 // FIXME(#20) other stuff for parity with make tidy
145 skipped_range: &[(usize, usize)],
147 report: &FormatReport,
149 let mut last_was_space = false;
150 let mut line_len = 0;
151 let mut cur_line = 1;
152 let mut newline_count = 0;
153 let mut errors = vec![];
154 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
155 let mut line_buffer = String::with_capacity(config.max_width() * 2);
156 let mut is_string = false; // true if the current line contains a string literal.
157 let mut format_line = config.file_lines().contains_line(name, cur_line);
158 let allow_issue_seek = !issue_seeker.is_disabled();
161 if let Some(ref license_template) = config.license_template {
162 if !license_template.is_match(text) {
163 errors.push(FormattingError {
165 kind: ErrorKind::LicenseCheck,
168 line_buffer: String::new(),
173 // Iterate over the chars in the file map.
174 for (kind, c) in CharClasses::new(text.chars()) {
179 if allow_issue_seek && format_line {
180 // Add warnings for bad todos/ fixmes
181 if let Some(issue) = issue_seeker.inspect(c) {
182 errors.push(FormattingError {
184 kind: ErrorKind::BadIssue(issue),
187 line_buffer: String::new(),
194 // Check for (and record) trailing whitespace.
196 if should_report_error(config, kind, is_string, &ErrorKind::TrailingWhitespace)
197 && !is_skipped_line(cur_line, skipped_range)
199 errors.push(FormattingError {
201 kind: ErrorKind::TrailingWhitespace,
202 is_comment: kind.is_comment(),
203 is_string: kind.is_string(),
204 line_buffer: line_buffer.clone(),
210 // Check for any line width errors we couldn't correct.
211 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
212 if line_len > config.max_width()
213 && !is_skipped_line(cur_line, skipped_range)
214 && should_report_error(config, kind, is_string, &error_kind)
216 errors.push(FormattingError {
219 is_comment: kind.is_comment(),
221 line_buffer: line_buffer.clone(),
228 format_line = config.file_lines().contains_line(name, cur_line);
230 last_was_space = false;
235 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
236 last_was_space = c.is_whitespace();
238 if kind.is_string() {
244 if newline_count > 1 {
245 debug!("track truncate: {} {}", text.len(), newline_count);
246 let line = text.len() - newline_count + 1;
250 report.append(name.clone(), errors);
253 fn parse_input<'sess>(
255 parse_session: &'sess ParseSess,
257 ) -> Result<ast::Crate, ParseError<'sess>> {
258 let mut parser = match input {
259 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
260 Input::Text(text) => parse::new_parser_from_source_str(
262 syntax::codemap::FileName::Custom("stdin".to_owned()),
267 parser.cfg_mods = false;
268 if config.skip_children() {
269 parser.recurse_into_file_modules = false;
272 let mut parser = AssertUnwindSafe(parser);
273 let result = catch_unwind(move || parser.0.parse_crate_mod());
277 if parse_session.span_diagnostic.has_errors() {
278 // Bail out if the parser recovered from an error.
279 Err(ParseError::Recovered)
284 Ok(Err(e)) => Err(ParseError::Error(e)),
285 Err(_) => Err(ParseError::Panic),
289 /// All the ways that parsing can fail.
290 enum ParseError<'sess> {
291 /// There was an error, but the parser recovered.
293 /// There was an error (supplied) and parsing failed.
294 Error(DiagnosticBuilder<'sess>),
295 /// The parser panicked.
299 impl<'b, T: Write + 'b> Session<'b, T> {
300 pub(crate) fn format_input_inner(
303 ) -> Result<(FileMap, FormatReport), ErrorKind> {
304 syntax_pos::hygiene::set_default_edition(self.config.edition().to_libsyntax_pos_edition());
306 if self.config.disable_all_formatting() {
307 // When the input is from stdin, echo back the input.
308 if let Input::Text(ref buf) = input {
309 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
310 return Err(From::from(e));
313 return Ok((FileMap::new(), FormatReport::new()));
316 let input_is_stdin = input.is_text();
317 let mut filemap = FileMap::new();
318 // TODO split Session? out vs config?
319 let format_result = self.format_project(input, |this, path, mut result| {
320 if let Some(ref mut out) = this.out {
321 match filemap::write_file(&mut result, &path, out, &this.config) {
322 Ok(b) if b => this.summary.add_diff(),
324 // Create a new error with path_str to help users see which files failed
325 let err_msg = format!("{}: {}", path, e);
326 return Err(io::Error::new(e.kind(), err_msg).into());
332 filemap.push((path, result));
336 should_emit_verbose(input_is_stdin, &self.config, || {
337 fn duration_to_f32(d: Duration) -> f32 {
338 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
342 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
343 duration_to_f32(self.timer.get_parse_time().unwrap()),
344 duration_to_f32(self.timer.get_format_time().unwrap()),
348 format_result.map(|(result, summary)| {
349 self.summary.add(summary);
354 // TODO only uses config and timer
355 fn format_project<F>(
358 mut formatted_file: F,
359 ) -> Result<(FormatReport, Summary), ErrorKind>
361 F: FnMut(&mut Session<T>, FileName, String) -> Result<(), ErrorKind>,
363 let mut summary = Summary::default();
364 let main_file = match input {
365 Input::File(ref file) => FileName::Real(file.clone()),
366 Input::Text(..) => FileName::Stdin,
370 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
371 let mut parse_session = self.make_parse_sess(codemap.clone());
372 let krate = match parse_input(input, &parse_session, &self.config) {
376 ParseError::Error(mut diagnostic) => diagnostic.emit(),
377 ParseError::Panic => {
378 // Note that if you see this message and want more information,
379 // then go to `parse_input` and run the parse function without
380 // `catch_unwind` so rustfmt panics and you can get a backtrace.
381 should_emit_verbose(main_file != FileName::Stdin, &self.config, || {
382 println!("The Rust parser panicked")
385 ParseError::Recovered => {}
387 summary.add_parsing_error();
388 return Err(ErrorKind::ParseError);
391 self.timer = self.timer.done_parsing();
393 // Suppress error output if we have to do any further parsing.
394 let silent_emitter = Box::new(EmitterWriter::new(
395 Box::new(Vec::new()),
396 Some(codemap.clone()),
400 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
402 let report = FormatReport::new();
404 let skip_children = self.config.skip_children();
405 for (path, module) in modules::list_files(&krate, parse_session.codemap())? {
406 if (skip_children && path != main_file) || self.config.ignore().skip_file(&path) {
409 should_emit_verbose(main_file != FileName::Stdin, &self.config, || {
410 println!("Formatting {}", path)
412 let filemap = parse_session
414 .lookup_char_pos(module.inner.lo())
416 let big_snippet = filemap.src.as_ref().unwrap();
417 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
418 let mut visitor = FmtVisitor::from_codemap(
424 // Format inner attributes if available.
425 if !krate.attrs.is_empty() && path == main_file {
426 visitor.skip_empty_lines(filemap.end_pos);
427 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
428 visitor.push_rewrite(module.inner, None);
430 visitor.format_separate_mod(module, &*filemap);
433 visitor.last_pos = filemap.start_pos;
434 visitor.skip_empty_lines(filemap.end_pos);
435 visitor.format_separate_mod(module, &*filemap);
440 ::utils::count_newlines(&visitor.buffer)
443 // For some reason, the codemap does not include terminating
444 // newlines so we must add one on for each file. This is sad.
445 filemap::append_newline(&mut visitor.buffer);
450 &visitor.skipped_range,
454 self.replace_with_system_newlines(&mut visitor.buffer);
456 if visitor.macro_rewrite_failure {
457 summary.add_macro_format_failure();
460 formatted_file(self, path, visitor.buffer)?;
462 self.timer = self.timer.done_formatting();
464 if report.has_warnings() {
465 summary.add_formatting_error();
468 let report_errs = &report.internal.borrow().1;
469 if report_errs.has_check_errors {
470 summary.add_check_error();
472 if report_errs.has_operational_errors {
473 summary.add_operational_error();
477 Ok((report, summary))
480 fn make_parse_sess(&self, codemap: Rc<CodeMap>) -> ParseSess {
481 let tty_handler = if self.config.hide_parse_errors() {
482 let silent_emitter = Box::new(EmitterWriter::new(
483 Box::new(Vec::new()),
484 Some(codemap.clone()),
488 Handler::with_emitter(true, false, silent_emitter)
490 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
491 let color_cfg = if supports_color {
496 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
499 ParseSess::with_span_handler(tty_handler, codemap)
502 fn replace_with_system_newlines(&self, text: &mut String) -> () {
503 let style = if self.config.newline_style() == NewlineStyle::Native {
505 NewlineStyle::Windows
510 self.config.newline_style()
514 NewlineStyle::Unix => return,
515 NewlineStyle::Windows => {
516 let mut transformed = String::with_capacity(text.capacity());
517 for c in text.chars() {
519 '\n' => transformed.push_str("\r\n"),
521 c => transformed.push(c),
526 NewlineStyle::Native => unreachable!(),
531 /// A single span of changed lines, with 0 or more removed lines
532 /// and a vector of 0 or more inserted lines.
533 #[derive(Debug, PartialEq, Eq)]
534 pub(crate) struct ModifiedChunk {
535 /// The first to be removed from the original text
536 pub line_number_orig: u32,
537 /// The number of lines which have been replaced
538 pub lines_removed: u32,
540 pub lines: Vec<String>,
543 /// Set of changed sections of a file.
544 #[derive(Debug, PartialEq, Eq)]
545 pub(crate) struct ModifiedLines {
546 /// The set of changed chunks.
547 pub chunks: Vec<ModifiedChunk>,
550 #[derive(Clone, Copy, Debug)]
551 pub(crate) enum Timer {
552 Initialized(Instant),
553 DoneParsing(Instant, Instant),
554 DoneFormatting(Instant, Instant, Instant),
558 fn done_parsing(self) -> Self {
560 Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
561 _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
565 fn done_formatting(self) -> Self {
567 Timer::DoneParsing(init_time, parse_time) => {
568 Timer::DoneFormatting(init_time, parse_time, Instant::now())
570 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
574 /// Returns the time it took to parse the source files in nanoseconds.
575 fn get_parse_time(&self) -> Option<Duration> {
577 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
578 // This should never underflow since `Instant::now()` guarantees monotonicity.
579 Some(parse_time.duration_since(init))
581 Timer::Initialized(..) => None,
585 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
587 fn get_format_time(&self) -> Option<Duration> {
589 Timer::DoneFormatting(_init, parse_time, format_time) => {
590 Some(format_time.duration_since(parse_time))
592 Timer::DoneParsing(..) | Timer::Initialized(..) => None,
597 /// A summary of a Rustfmt run.
598 #[derive(Debug, Default, Clone, Copy)]
600 // Encountered e.g. an IO error.
601 has_operational_errors: bool,
603 // Failed to reformat code because of parsing errors.
604 has_parsing_errors: bool,
606 // Code is valid, but it is impossible to format it properly.
607 has_formatting_errors: bool,
609 // Code contains macro call that was unable to format.
610 pub(crate) has_macro_format_failure: bool,
612 // Failed a check, such as the license check or other opt-in checking.
613 has_check_errors: bool,
615 /// Formatted code differs from existing code (--check only).
620 pub fn has_operational_errors(&self) -> bool {
621 self.has_operational_errors
624 pub fn has_parsing_errors(&self) -> bool {
625 self.has_parsing_errors
628 pub fn has_formatting_errors(&self) -> bool {
629 self.has_formatting_errors
632 pub fn has_check_errors(&self) -> bool {
633 self.has_check_errors
636 pub(crate) fn has_macro_formatting_failure(&self) -> bool {
637 self.has_macro_format_failure
640 pub fn add_operational_error(&mut self) {
641 self.has_operational_errors = true;
644 pub(crate) fn add_parsing_error(&mut self) {
645 self.has_parsing_errors = true;
648 pub(crate) fn add_formatting_error(&mut self) {
649 self.has_formatting_errors = true;
652 pub(crate) fn add_check_error(&mut self) {
653 self.has_check_errors = true;
656 pub(crate) fn add_diff(&mut self) {
657 self.has_diff = true;
660 pub(crate) fn add_macro_format_failure(&mut self) {
661 self.has_macro_format_failure = true;
664 pub fn has_no_errors(&self) -> bool {
665 !(self.has_operational_errors
666 || self.has_parsing_errors
667 || self.has_formatting_errors
671 /// Combine two summaries together.
672 pub fn add(&mut self, other: Summary) {
673 self.has_operational_errors |= other.has_operational_errors;
674 self.has_formatting_errors |= other.has_formatting_errors;
675 self.has_macro_format_failure |= other.has_macro_format_failure;
676 self.has_parsing_errors |= other.has_parsing_errors;
677 self.has_check_errors |= other.has_check_errors;
678 self.has_diff |= other.has_diff;