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 crate::comment::{CharClasses, FullCodeCharKind};
16 use crate::config::{Config, FileName, Verbosity};
17 use crate::ignore_path::IgnorePathSet;
18 use crate::issues::BadIssueSeeker;
19 use crate::utils::{count_newlines, get_skip_macro_names};
20 use crate::visitor::{FmtVisitor, SnippetProvider};
21 use crate::{modules, source_file, ErrorKind, FormatReport, Input, Session};
23 // A map of the files of a crate, with their new content
24 pub(crate) type SourceFile = Vec<FileRecord>;
25 pub(crate) type FileRecord = (FileName, String);
27 impl<'b, T: Write + 'b> Session<'b, T> {
28 pub(crate) fn format_input_inner(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
29 if !self.config.version_meets_requirement() {
30 return Err(ErrorKind::VersionMismatch);
33 syntax::with_globals(|| {
34 syntax_pos::hygiene::set_default_edition(
35 self.config.edition().to_libsyntax_pos_edition(),
38 if self.config.disable_all_formatting() {
39 // When the input is from stdin, echo back the input.
40 if let Input::Text(ref buf) = input {
41 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
42 return Err(From::from(e));
45 return Ok(FormatReport::new());
48 let config = &self.config.clone();
49 let format_result = format_project(input, config, self);
51 format_result.map(|report| {
52 self.errors.add(&report.internal.borrow().1);
59 // Format an entire crate (or subset of the module tree).
60 fn format_project<T: FormatHandler>(
64 ) -> Result<FormatReport, ErrorKind> {
65 let mut timer = Timer::start();
67 let main_file = input.file_name();
68 let input_is_stdin = main_file == FileName::Stdin;
71 let source_map = Rc::new(SourceMap::new(FilePathMapping::empty()));
72 let mut parse_session = make_parse_sess(source_map.clone(), config);
73 let mut report = FormatReport::new();
74 let directory_ownership = input.to_directory_ownership();
75 let krate = match parse_crate(
83 // Surface parse error via Session (errors are merged there from report)
84 Err(ErrorKind::ParseError) => return Ok(report),
85 Err(e) => return Err(e),
87 timer = timer.done_parsing();
89 // Suppress error output if we have to do any further parsing.
90 let silent_emitter = silent_emitter();
91 parse_session.span_diagnostic = Handler::with_emitter(true, None, silent_emitter);
93 let mut context = FormatContext::new(&krate, report, parse_session, config, handler);
94 let ignore_path_set = match IgnorePathSet::from_ignore_list(&config.ignore()) {
96 Err(e) => return Err(ErrorKind::InvalidGlobPattern(e)),
99 let files = modules::ModResolver::new(
100 context.parse_session.source_map(),
101 directory_ownership.unwrap_or(parse::DirectoryOwnership::UnownedViaMod(false)),
105 .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
106 for (path, (module, _)) in files {
107 let should_ignore = !input_is_stdin && ignore_path_set.is_match(&path);
108 if (config.skip_children() && path != main_file) || should_ignore {
111 should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
112 let is_root = path == main_file;
113 context.format_file(path, module, is_root)?;
115 timer = timer.done_formatting();
117 should_emit_verbose(input_is_stdin, config, || {
119 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
120 timer.get_parse_time(),
121 timer.get_format_time(),
128 // Used for formatting files.
130 struct FormatContext<'a, T: FormatHandler> {
131 krate: &'a ast::Crate,
132 report: FormatReport,
133 parse_session: ParseSess,
138 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
139 // Formats a single file/module.
145 ) -> Result<(), ErrorKind> {
146 let source_file = self
149 .lookup_char_pos(module.inner.lo())
151 let big_snippet = source_file.src.as_ref().unwrap();
152 let snippet_provider = SnippetProvider::new(source_file.start_pos, big_snippet);
153 let mut visitor = FmtVisitor::from_source_map(
162 .append(&mut get_skip_macro_names(&self.krate.attrs));
164 // Format inner attributes if available.
165 if !self.krate.attrs.is_empty() && is_root {
166 visitor.skip_empty_lines(source_file.end_pos);
167 if visitor.visit_attrs(&self.krate.attrs, ast::AttrStyle::Inner) {
168 visitor.push_rewrite(module.inner, None);
170 visitor.format_separate_mod(module, &*source_file);
173 visitor.last_pos = source_file.start_pos;
174 visitor.skip_empty_lines(source_file.end_pos);
175 visitor.format_separate_mod(module, &*source_file);
178 debug_assert_eq!(visitor.line_number, count_newlines(&visitor.buffer));
180 // For some reason, the source_map does not include terminating
181 // newlines so we must add one on for each file. This is sad.
182 source_file::append_newline(&mut visitor.buffer);
187 &visitor.skipped_range,
193 .apply(&mut visitor.buffer, &big_snippet);
195 if visitor.macro_rewrite_failure {
196 self.report.add_macro_format_failure();
199 .add_non_formatted_ranges(visitor.skipped_range.clone());
201 self.handler.handle_formatted_file(
202 self.parse_session.source_map(),
204 visitor.buffer.to_owned(),
210 // Handle the results of formatting.
211 trait FormatHandler {
212 fn handle_formatted_file(
214 source_map: &SourceMap,
217 report: &mut FormatReport,
218 ) -> Result<(), ErrorKind>;
221 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
222 // Called for each formatted file.
223 fn handle_formatted_file(
225 source_map: &SourceMap,
228 report: &mut FormatReport,
229 ) -> Result<(), ErrorKind> {
230 if let Some(ref mut out) = self.out {
231 match source_file::write_file(Some(source_map), &path, &result, out, &self.config) {
232 Ok(has_diff) if has_diff => report.add_diff(),
234 // Create a new error with path_str to help users see which files failed
235 let err_msg = format!("{}: {}", path, e);
236 return Err(io::Error::new(e.kind(), err_msg).into());
242 self.source_file.push((path, result));
247 pub(crate) struct FormattingError {
248 pub(crate) line: usize,
249 pub(crate) kind: ErrorKind,
252 pub(crate) line_buffer: String,
255 impl FormattingError {
256 pub(crate) fn from_span(
258 source_map: &SourceMap,
260 ) -> FormattingError {
262 line: source_map.lookup_char_pos(span.lo()).line,
263 is_comment: kind.is_comment(),
266 line_buffer: source_map
271 .get_line(fl.lines[0].line_index)
272 .map(std::borrow::Cow::into_owned)
274 .unwrap_or_else(String::new),
278 pub(crate) fn is_internal(&self) -> bool {
280 ErrorKind::LineOverflow(..)
281 | ErrorKind::TrailingWhitespace
282 | ErrorKind::IoError(_)
283 | ErrorKind::ParseError
284 | ErrorKind::LostComment => true,
289 pub(crate) fn msg_suffix(&self) -> &str {
290 if self.is_comment || self.is_string {
291 "set `error_on_unformatted = false` to suppress \
292 the warning against comments or string literals\n"
299 pub(crate) fn format_len(&self) -> (usize, usize) {
301 ErrorKind::LineOverflow(found, max) => (max, found - max),
302 ErrorKind::TrailingWhitespace
303 | ErrorKind::DeprecatedAttr
304 | ErrorKind::BadIssue(_)
306 | ErrorKind::LostComment => {
307 let trailing_ws_start = self
309 .rfind(|c: char| !c.is_whitespace())
314 self.line_buffer.len() - trailing_ws_start,
322 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
324 #[derive(Default, Debug, PartialEq)]
325 pub(crate) struct ReportedErrors {
326 // Encountered e.g., an IO error.
327 pub(crate) has_operational_errors: bool,
329 // Failed to reformat code because of parsing errors.
330 pub(crate) has_parsing_errors: bool,
332 // Code is valid, but it is impossible to format it properly.
333 pub(crate) has_formatting_errors: bool,
335 // Code contains macro call that was unable to format.
336 pub(crate) has_macro_format_failure: bool,
338 // Failed a check, such as the license check or other opt-in checking.
339 pub(crate) has_check_errors: bool,
341 /// Formatted code differs from existing code (--check only).
342 pub(crate) has_diff: bool,
345 impl ReportedErrors {
346 /// Combine two summaries together.
347 pub fn add(&mut self, other: &ReportedErrors) {
348 self.has_operational_errors |= other.has_operational_errors;
349 self.has_parsing_errors |= other.has_parsing_errors;
350 self.has_formatting_errors |= other.has_formatting_errors;
351 self.has_macro_format_failure |= other.has_macro_format_failure;
352 self.has_check_errors |= other.has_check_errors;
353 self.has_diff |= other.has_diff;
357 #[derive(Clone, Copy, Debug)]
360 Initialized(Instant),
361 DoneParsing(Instant, Instant),
362 DoneFormatting(Instant, Instant, Instant),
366 fn start() -> Timer {
367 if cfg!(target_arch = "wasm32") {
370 Timer::Initialized(Instant::now())
373 fn done_parsing(self) -> Self {
375 Timer::Disabled => Timer::Disabled,
376 Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
377 _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
381 fn done_formatting(self) -> Self {
383 Timer::Disabled => Timer::Disabled,
384 Timer::DoneParsing(init_time, parse_time) => {
385 Timer::DoneFormatting(init_time, parse_time, Instant::now())
387 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
391 /// Returns the time it took to parse the source files in seconds.
392 fn get_parse_time(&self) -> f32 {
394 Timer::Disabled => panic!("this platform cannot time execution"),
395 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
396 // This should never underflow since `Instant::now()` guarantees monotonicity.
397 Self::duration_to_f32(parse_time.duration_since(init))
399 Timer::Initialized(..) => unreachable!(),
403 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
405 fn get_format_time(&self) -> f32 {
407 Timer::Disabled => panic!("this platform cannot time execution"),
408 Timer::DoneFormatting(_init, parse_time, format_time) => {
409 Self::duration_to_f32(format_time.duration_since(parse_time))
411 Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
415 fn duration_to_f32(d: Duration) -> f32 {
416 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
420 // Formatting done on a char by char or line by line basis.
421 // FIXME(#20): other stuff for parity with make tidy.
425 skipped_range: &[(usize, usize)],
427 report: &FormatReport,
429 let mut formatter = FormatLines::new(name, skipped_range, config);
430 formatter.check_license(text);
431 formatter.iterate(text);
433 if formatter.newline_count > 1 {
434 debug!("track truncate: {} {}", text.len(), formatter.newline_count);
435 let line = text.len() - formatter.newline_count + 1;
439 report.append(name.clone(), formatter.errors);
442 struct FormatLines<'a> {
444 skipped_range: &'a [(usize, usize)],
445 last_was_space: bool,
448 newline_count: usize,
449 errors: Vec<FormattingError>,
450 issue_seeker: BadIssueSeeker,
452 // `true` if the current line contains a string literal.
455 allow_issue_seek: bool,
459 impl<'a> FormatLines<'a> {
462 skipped_range: &'a [(usize, usize)],
464 ) -> FormatLines<'a> {
465 let issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
469 last_was_space: false,
474 allow_issue_seek: !issue_seeker.is_disabled(),
476 line_buffer: String::with_capacity(config.max_width() * 2),
478 format_line: config.file_lines().contains_line(name, 1),
483 fn check_license(&mut self, text: &mut String) {
484 if let Some(ref license_template) = self.config.license_template {
485 if !license_template.is_match(text) {
486 self.errors.push(FormattingError {
488 kind: ErrorKind::LicenseCheck,
491 line_buffer: String::new(),
497 // Iterate over the chars in the file map.
498 fn iterate(&mut self, text: &mut String) {
499 for (kind, c) in CharClasses::new(text.chars()) {
504 if self.allow_issue_seek && self.format_line {
505 // Add warnings for bad todos/ fixmes
506 if let Some(issue) = self.issue_seeker.inspect(c) {
507 self.push_err(ErrorKind::BadIssue(issue), false, false);
519 fn new_line(&mut self, kind: FullCodeCharKind) {
520 if self.format_line {
521 // Check for (and record) trailing whitespace.
522 if self.last_was_space {
523 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
524 && !self.is_skipped_line()
527 ErrorKind::TrailingWhitespace,
535 // Check for any line width errors we couldn't correct.
536 let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
537 if self.line_len > self.config.max_width()
538 && !self.is_skipped_line()
539 && self.should_report_error(kind, &error_kind)
541 let is_string = self.is_string;
542 self.push_err(error_kind, kind.is_comment(), is_string);
548 self.format_line = self
551 .contains_line(self.name, self.cur_line);
552 self.newline_count += 1;
553 self.last_was_space = false;
554 self.line_buffer.clear();
555 self.is_string = false;
558 fn char(&mut self, c: char, kind: FullCodeCharKind) {
559 self.newline_count = 0;
560 self.line_len += if c == '\t' {
561 self.config.tab_spaces()
565 self.last_was_space = c.is_whitespace();
566 self.line_buffer.push(c);
567 if kind.is_string() {
568 self.is_string = true;
572 fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
573 self.errors.push(FormattingError {
578 line_buffer: self.line_buffer.clone(),
582 fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
583 let allow_error_report =
584 if char_kind.is_comment() || self.is_string || error_kind.is_comment() {
585 self.config.error_on_unformatted()
591 ErrorKind::LineOverflow(..) => {
592 self.config.error_on_line_overflow() && allow_error_report
594 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
599 /// Returns `true` if the line with the given line number was skipped by `#[rustfmt::skip]`.
600 fn is_skipped_line(&self) -> bool {
603 .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
609 parse_session: &ParseSess,
611 report: &mut FormatReport,
612 directory_ownership: Option<parse::DirectoryOwnership>,
613 ) -> Result<ast::Crate, ErrorKind> {
614 let input_is_stdin = input.is_text();
616 let parser = match input {
617 Input::File(ref file) => {
618 // Use `new_sub_parser_from_file` when we the input is a submodule.
619 Ok(if let Some(dir_own) = directory_ownership {
620 parse::new_sub_parser_from_file(parse_session, file, dir_own, None, DUMMY_SP)
622 parse::new_parser_from_file(parse_session, file)
625 Input::Text(text) => parse::maybe_new_parser_from_source_str(
627 syntax::source_map::FileName::Custom("stdin".to_owned()),
631 parser.recurse_into_file_modules = false;
637 .map(|d| DiagnosticBuilder::new_diagnostic(&parse_session.span_diagnostic, d))
642 let result = match parser {
644 parser.cfg_mods = false;
645 if config.skip_children() {
646 parser.recurse_into_file_modules = false;
649 let mut parser = AssertUnwindSafe(parser);
650 catch_unwind(move || parser.0.parse_crate_mod().map_err(|d| vec![d]))
652 Err(db) => Ok(Err(db)),
657 if !parse_session.span_diagnostic.has_errors() {
661 Ok(Err(mut diagnostics)) => diagnostics.iter_mut().for_each(DiagnosticBuilder::emit),
663 // Note that if you see this message and want more information,
664 // then run the `parse_crate_mod` function above without
665 // `catch_unwind` so rustfmt panics and you can get a backtrace.
666 should_emit_verbose(input_is_stdin, config, || {
667 println!("The Rust parser panicked")
672 report.add_parsing_error();
673 Err(ErrorKind::ParseError)
676 /// Emitter which discards every error.
677 struct SilentEmitter;
679 impl Emitter for SilentEmitter {
680 fn emit(&mut self, _db: &DiagnosticBuilder<'_>) {}
683 fn silent_emitter() -> Box<SilentEmitter> {
684 Box::new(SilentEmitter {})
687 fn make_parse_sess(source_map: Rc<SourceMap>, config: &Config) -> ParseSess {
688 let tty_handler = if config.hide_parse_errors() {
689 let silent_emitter = silent_emitter();
690 Handler::with_emitter(true, None, silent_emitter)
692 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
693 let color_cfg = if supports_color {
698 Handler::with_tty_emitter(color_cfg, true, None, Some(source_map.clone()))
701 ParseSess::with_span_handler(tty_handler, source_map)
704 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
708 if config.verbose() == Verbosity::Verbose && !is_stdin {