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::errors::emitter::{ColorConfig, Emitter};
11 use syntax::errors::{DiagnosticBuilder, Handler};
12 use syntax::parse::{self, ParseSess};
13 use syntax::source_map::{FilePathMapping, SourceMap, Span, DUMMY_SP};
15 use self::newline_style::apply_newline_style;
16 use crate::comment::{CharClasses, FullCodeCharKind};
17 use crate::config::{Config, FileName, Verbosity};
18 use crate::ignore_path::IgnorePathSet;
19 use crate::issues::BadIssueSeeker;
20 use crate::utils::count_newlines;
21 use crate::visitor::{FmtVisitor, SnippetProvider};
22 use crate::{modules, source_file, ErrorKind, FormatReport, Input, Session};
26 // A map of the files of a crate, with their new content
27 pub(crate) type SourceFile = Vec<FileRecord>;
28 pub(crate) type FileRecord = (FileName, String);
30 impl<'b, T: Write + 'b> Session<'b, T> {
31 pub(crate) fn format_input_inner(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
32 if !self.config.version_meets_requirement() {
33 return Err(ErrorKind::VersionMismatch);
36 syntax::with_globals(self.config.edition().to_libsyntax_pos_edition(), || {
37 if self.config.disable_all_formatting() {
38 // When the input is from stdin, echo back the input.
39 if let Input::Text(ref buf) = input {
40 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
41 return Err(From::from(e));
44 return Ok(FormatReport::new());
47 let config = &self.config.clone();
48 let format_result = format_project(input, config, self);
50 format_result.map(|report| {
51 self.errors.add(&report.internal.borrow().1);
58 // Format an entire crate (or subset of the module tree).
59 fn format_project<T: FormatHandler>(
63 ) -> Result<FormatReport, ErrorKind> {
64 let mut timer = Timer::start();
66 let main_file = input.file_name();
67 let input_is_stdin = main_file == FileName::Stdin;
69 let ignore_path_set = match IgnorePathSet::from_ignore_list(&config.ignore()) {
71 Err(e) => return Err(ErrorKind::InvalidGlobPattern(e)),
73 if config.skip_children() && ignore_path_set.is_match(&main_file) {
74 return Ok(FormatReport::new());
78 let source_map = Rc::new(SourceMap::new(FilePathMapping::empty()));
79 let mut parse_session = make_parse_sess(source_map.clone(), config);
80 let mut report = FormatReport::new();
81 let directory_ownership = input.to_directory_ownership();
82 let krate = match parse_crate(
90 // Surface parse error via Session (errors are merged there from report)
91 Err(ErrorKind::ParseError) => return Ok(report),
92 Err(e) => return Err(e),
94 timer = timer.done_parsing();
96 // Suppress error output if we have to do any further parsing.
97 let silent_emitter = silent_emitter();
98 parse_session.span_diagnostic = Handler::with_emitter(true, None, silent_emitter);
100 let mut context = FormatContext::new(&krate, report, parse_session, config, handler);
101 let files = modules::ModResolver::new(
102 &context.parse_session,
103 directory_ownership.unwrap_or(parse::DirectoryOwnership::UnownedViaMod(true)),
104 !(input_is_stdin || config.skip_children()),
107 .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
108 for (path, module) in files {
109 let should_ignore = !input_is_stdin && ignore_path_set.is_match(&path);
110 if (config.skip_children() && path != main_file) || should_ignore {
113 should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
114 let is_root = path == main_file;
115 context.format_file(path, &module, is_root)?;
117 timer = timer.done_formatting();
119 should_emit_verbose(input_is_stdin, config, || {
121 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
122 timer.get_parse_time(),
123 timer.get_format_time(),
130 // Used for formatting files.
132 struct FormatContext<'a, T: FormatHandler> {
133 krate: &'a ast::Crate,
134 report: FormatReport,
135 parse_session: ParseSess,
140 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
141 // Formats a single file/module.
147 ) -> Result<(), ErrorKind> {
148 let source_file = self
151 .lookup_char_pos(module.inner.lo())
153 let big_snippet = source_file.src.as_ref().unwrap();
154 let snippet_provider = SnippetProvider::new(source_file.start_pos, big_snippet);
155 let mut visitor = FmtVisitor::from_source_map(
161 visitor.skip_context.update_with_attrs(&self.krate.attrs);
163 // Format inner attributes if available.
164 if !self.krate.attrs.is_empty() && is_root {
165 visitor.skip_empty_lines(source_file.end_pos);
166 if visitor.visit_attrs(&self.krate.attrs, ast::AttrStyle::Inner) {
167 visitor.push_rewrite(module.inner, None);
169 visitor.format_separate_mod(module, &*source_file);
172 visitor.last_pos = source_file.start_pos;
173 visitor.skip_empty_lines(source_file.end_pos);
174 visitor.format_separate_mod(module, &*source_file);
179 count_newlines(&visitor.buffer),
180 "failed in format_file visitor.buffer:\n {:?}",
184 // For some reason, the source_map does not include terminating
185 // newlines so we must add one on for each file. This is sad.
186 source_file::append_newline(&mut visitor.buffer);
191 &visitor.skipped_range.borrow(),
197 self.config.newline_style(),
202 if visitor.macro_rewrite_failure {
203 self.report.add_macro_format_failure();
206 .add_non_formatted_ranges(visitor.skipped_range.borrow().clone());
208 self.handler.handle_formatted_file(
209 self.parse_session.source_map(),
211 visitor.buffer.to_owned(),
217 // Handle the results of formatting.
218 trait FormatHandler {
219 fn handle_formatted_file(
221 source_map: &SourceMap,
224 report: &mut FormatReport,
225 ) -> Result<(), ErrorKind>;
228 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
229 // Called for each formatted file.
230 fn handle_formatted_file(
232 source_map: &SourceMap,
235 report: &mut FormatReport,
236 ) -> Result<(), ErrorKind> {
237 if let Some(ref mut out) = self.out {
238 match source_file::write_file(Some(source_map), &path, &result, out, &mut *self.emitter)
240 Ok(ref result) if result.has_diff => report.add_diff(),
242 // Create a new error with path_str to help users see which files failed
243 let err_msg = format!("{}: {}", path, e);
244 return Err(io::Error::new(e.kind(), err_msg).into());
250 self.source_file.push((path, result));
255 pub(crate) struct FormattingError {
256 pub(crate) line: usize,
257 pub(crate) kind: ErrorKind,
260 pub(crate) line_buffer: String,
263 impl FormattingError {
264 pub(crate) fn from_span(
266 source_map: &SourceMap,
268 ) -> FormattingError {
270 line: source_map.lookup_char_pos(span.lo()).line,
271 is_comment: kind.is_comment(),
274 line_buffer: source_map
279 .get_line(fl.lines[0].line_index)
280 .map(std::borrow::Cow::into_owned)
282 .unwrap_or_else(String::new),
286 pub(crate) fn is_internal(&self) -> bool {
288 ErrorKind::LineOverflow(..)
289 | ErrorKind::TrailingWhitespace
290 | ErrorKind::IoError(_)
291 | ErrorKind::ParseError
292 | ErrorKind::LostComment => true,
297 pub(crate) fn msg_suffix(&self) -> &str {
298 if self.is_comment || self.is_string {
299 "set `error_on_unformatted = false` to suppress \
300 the warning against comments or string literals\n"
307 pub(crate) fn format_len(&self) -> (usize, usize) {
309 ErrorKind::LineOverflow(found, max) => (max, found - max),
310 ErrorKind::TrailingWhitespace
311 | ErrorKind::DeprecatedAttr
312 | ErrorKind::BadIssue(_)
314 | ErrorKind::LostComment
315 | ErrorKind::LicenseCheck => {
316 let trailing_ws_start = self
318 .rfind(|c: char| !c.is_whitespace())
323 self.line_buffer.len() - trailing_ws_start,
331 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
333 #[derive(Default, Debug, PartialEq)]
334 pub(crate) struct ReportedErrors {
335 // Encountered e.g., an IO error.
336 pub(crate) has_operational_errors: bool,
338 // Failed to reformat code because of parsing errors.
339 pub(crate) has_parsing_errors: bool,
341 // Code is valid, but it is impossible to format it properly.
342 pub(crate) has_formatting_errors: bool,
344 // Code contains macro call that was unable to format.
345 pub(crate) has_macro_format_failure: bool,
347 // Failed a check, such as the license check or other opt-in checking.
348 pub(crate) has_check_errors: bool,
350 /// Formatted code differs from existing code (--check only).
351 pub(crate) has_diff: bool,
354 impl ReportedErrors {
355 /// Combine two summaries together.
356 pub(crate) fn add(&mut self, other: &ReportedErrors) {
357 self.has_operational_errors |= other.has_operational_errors;
358 self.has_parsing_errors |= other.has_parsing_errors;
359 self.has_formatting_errors |= other.has_formatting_errors;
360 self.has_macro_format_failure |= other.has_macro_format_failure;
361 self.has_check_errors |= other.has_check_errors;
362 self.has_diff |= other.has_diff;
366 #[derive(Clone, Copy, Debug)]
369 Initialized(Instant),
370 DoneParsing(Instant, Instant),
371 DoneFormatting(Instant, Instant, Instant),
375 fn start() -> Timer {
376 if cfg!(target_arch = "wasm32") {
379 Timer::Initialized(Instant::now())
382 fn done_parsing(self) -> Self {
384 Timer::Disabled => Timer::Disabled,
385 Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
386 _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
390 fn done_formatting(self) -> Self {
392 Timer::Disabled => Timer::Disabled,
393 Timer::DoneParsing(init_time, parse_time) => {
394 Timer::DoneFormatting(init_time, parse_time, Instant::now())
396 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
400 /// Returns the time it took to parse the source files in seconds.
401 fn get_parse_time(&self) -> f32 {
403 Timer::Disabled => panic!("this platform cannot time execution"),
404 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
405 // This should never underflow since `Instant::now()` guarantees monotonicity.
406 Self::duration_to_f32(parse_time.duration_since(init))
408 Timer::Initialized(..) => unreachable!(),
412 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
414 fn get_format_time(&self) -> f32 {
416 Timer::Disabled => panic!("this platform cannot time execution"),
417 Timer::DoneFormatting(_init, parse_time, format_time) => {
418 Self::duration_to_f32(format_time.duration_since(parse_time))
420 Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
424 fn duration_to_f32(d: Duration) -> f32 {
425 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
429 // Formatting done on a char by char or line by line basis.
430 // FIXME(#20): other stuff for parity with make tidy.
434 skipped_range: &[(usize, usize)],
436 report: &FormatReport,
438 let mut formatter = FormatLines::new(name, skipped_range, config);
439 formatter.check_license(text);
440 formatter.iterate(text);
442 if formatter.newline_count > 1 {
443 debug!("track truncate: {} {}", text.len(), formatter.newline_count);
444 let line = text.len() - formatter.newline_count + 1;
448 report.append(name.clone(), formatter.errors);
451 struct FormatLines<'a> {
453 skipped_range: &'a [(usize, usize)],
454 last_was_space: bool,
457 newline_count: usize,
458 errors: Vec<FormattingError>,
459 issue_seeker: BadIssueSeeker,
461 current_line_contains_string_literal: bool,
463 allow_issue_seek: bool,
467 impl<'a> FormatLines<'a> {
470 skipped_range: &'a [(usize, usize)],
472 ) -> FormatLines<'a> {
473 let issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
477 last_was_space: false,
482 allow_issue_seek: !issue_seeker.is_disabled(),
484 line_buffer: String::with_capacity(config.max_width() * 2),
485 current_line_contains_string_literal: false,
486 format_line: config.file_lines().contains_line(name, 1),
491 fn check_license(&mut self, text: &mut String) {
492 if let Some(ref license_template) = self.config.license_template {
493 if !license_template.is_match(text) {
494 self.errors.push(FormattingError {
496 kind: ErrorKind::LicenseCheck,
499 line_buffer: String::new(),
505 // Iterate over the chars in the file map.
506 fn iterate(&mut self, text: &mut String) {
507 for (kind, c) in CharClasses::new(text.chars()) {
512 if self.allow_issue_seek && self.format_line {
513 // Add warnings for bad todos/ fixmes
514 if let Some(issue) = self.issue_seeker.inspect(c) {
515 self.push_err(ErrorKind::BadIssue(issue), false, false);
527 fn new_line(&mut self, kind: FullCodeCharKind) {
528 if self.format_line {
529 // Check for (and record) trailing whitespace.
530 if self.last_was_space {
531 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
532 && !self.is_skipped_line()
535 ErrorKind::TrailingWhitespace,
543 // Check for any line width errors we couldn't correct.
544 let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
545 if self.line_len > self.config.max_width()
546 && !self.is_skipped_line()
547 && self.should_report_error(kind, &error_kind)
549 let is_string = self.current_line_contains_string_literal;
550 self.push_err(error_kind, kind.is_comment(), is_string);
556 self.format_line = self
559 .contains_line(self.name, self.cur_line);
560 self.newline_count += 1;
561 self.last_was_space = false;
562 self.line_buffer.clear();
563 self.current_line_contains_string_literal = false;
566 fn char(&mut self, c: char, kind: FullCodeCharKind) {
567 self.newline_count = 0;
568 self.line_len += if c == '\t' {
569 self.config.tab_spaces()
573 self.last_was_space = c.is_whitespace();
574 self.line_buffer.push(c);
575 if kind.is_string() {
576 self.current_line_contains_string_literal = true;
580 fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
581 self.errors.push(FormattingError {
586 line_buffer: self.line_buffer.clone(),
590 fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
591 let allow_error_report = if char_kind.is_comment()
592 || self.current_line_contains_string_literal
593 || error_kind.is_comment()
595 self.config.error_on_unformatted()
601 ErrorKind::LineOverflow(..) => {
602 self.config.error_on_line_overflow() && allow_error_report
604 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
609 /// Returns `true` if the line with the given line number was skipped by `#[rustfmt::skip]`.
610 fn is_skipped_line(&self) -> bool {
613 .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
619 parse_session: &ParseSess,
621 report: &mut FormatReport,
622 directory_ownership: Option<parse::DirectoryOwnership>,
623 ) -> Result<ast::Crate, ErrorKind> {
624 let input_is_stdin = input.is_text();
626 let parser = match input {
627 Input::File(ref file) => {
628 // Use `new_sub_parser_from_file` when we the input is a submodule.
629 Ok(if let Some(dir_own) = directory_ownership {
630 parse::new_sub_parser_from_file(parse_session, file, dir_own, None, DUMMY_SP)
632 parse::new_parser_from_file(parse_session, file)
635 Input::Text(text) => parse::maybe_new_parser_from_source_str(
637 syntax::source_map::FileName::Custom("stdin".to_owned()),
641 parser.recurse_into_file_modules = false;
647 .map(|d| DiagnosticBuilder::new_diagnostic(&parse_session.span_diagnostic, d))
652 let result = match parser {
654 parser.cfg_mods = false;
655 if config.skip_children() {
656 parser.recurse_into_file_modules = false;
659 let mut parser = AssertUnwindSafe(parser);
660 catch_unwind(move || parser.0.parse_crate_mod().map_err(|d| vec![d]))
662 Err(db) => Ok(Err(db)),
667 if !parse_session.span_diagnostic.has_errors() {
671 Ok(Err(mut diagnostics)) => diagnostics.iter_mut().for_each(DiagnosticBuilder::emit),
673 // Note that if you see this message and want more information,
674 // then run the `parse_crate_mod` function above without
675 // `catch_unwind` so rustfmt panics and you can get a backtrace.
676 should_emit_verbose(input_is_stdin, config, || {
677 println!("The Rust parser panicked")
682 report.add_parsing_error();
683 Err(ErrorKind::ParseError)
686 /// Emitter which discards every error.
687 struct SilentEmitter;
689 impl Emitter for SilentEmitter {
690 fn emit_diagnostic(&mut self, _db: &DiagnosticBuilder<'_>) {}
693 fn silent_emitter() -> Box<SilentEmitter> {
694 Box::new(SilentEmitter {})
697 fn make_parse_sess(source_map: Rc<SourceMap>, config: &Config) -> ParseSess {
698 let tty_handler = if config.hide_parse_errors() {
699 let silent_emitter = silent_emitter();
700 Handler::with_emitter(true, None, silent_emitter)
702 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
703 let color_cfg = if supports_color {
708 Handler::with_tty_emitter(color_cfg, true, None, Some(source_map.clone()))
711 ParseSess::with_span_handler(tty_handler, source_map)
714 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
718 if config.verbose() == Verbosity::Verbose && !is_stdin {