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::issues::BadIssueSeeker;
18 use crate::utils::{count_newlines, get_skip_macro_names};
19 use crate::visitor::{FmtVisitor, SnippetProvider};
20 use crate::{modules, source_file, ErrorKind, FormatReport, Input, Session};
22 // A map of the files of a crate, with their new content
23 pub(crate) type SourceFile = Vec<FileRecord>;
24 pub(crate) type FileRecord = (FileName, String);
26 impl<'b, T: Write + 'b> Session<'b, T> {
27 pub(crate) fn format_input_inner(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
28 if !self.config.version_meets_requirement() {
29 return Err(ErrorKind::VersionMismatch);
32 syntax::with_globals(|| {
33 syntax_pos::hygiene::set_default_edition(
34 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;
70 let source_map = Rc::new(SourceMap::new(FilePathMapping::empty()));
71 let mut parse_session = make_parse_sess(source_map.clone(), config);
72 let mut report = FormatReport::new();
73 let directory_ownership = input.to_directory_ownership();
74 let krate = match parse_crate(
82 // Surface parse error via Session (errors are merged there from report)
83 Err(ErrorKind::ParseError) => return Ok(report),
84 Err(e) => return Err(e),
86 timer = timer.done_parsing();
88 // Suppress error output if we have to do any further parsing.
89 let silent_emitter = silent_emitter();
90 parse_session.span_diagnostic = Handler::with_emitter(true, None, silent_emitter);
92 let mut context = FormatContext::new(&krate, report, parse_session, config, handler);
94 let files = modules::ModResolver::new(
95 context.parse_session.source_map(),
96 directory_ownership.unwrap_or(parse::DirectoryOwnership::UnownedViaMod(false)),
100 .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
101 for (path, (module, _)) in files {
102 if (config.skip_children() && path != main_file) || config.ignore().skip_file(&path) {
105 should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
106 let is_root = path == main_file;
107 context.format_file(path, module, is_root)?;
109 timer = timer.done_formatting();
111 should_emit_verbose(input_is_stdin, config, || {
113 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
114 timer.get_parse_time(),
115 timer.get_format_time(),
122 // Used for formatting files.
124 struct FormatContext<'a, T: FormatHandler> {
125 krate: &'a ast::Crate,
126 report: FormatReport,
127 parse_session: ParseSess,
132 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
133 // Formats a single file/module.
139 ) -> Result<(), ErrorKind> {
140 let source_file = self
143 .lookup_char_pos(module.inner.lo())
145 let big_snippet = source_file.src.as_ref().unwrap();
146 let snippet_provider = SnippetProvider::new(source_file.start_pos, big_snippet);
147 let mut visitor = FmtVisitor::from_source_map(
156 .append(&mut get_skip_macro_names(&self.krate.attrs));
158 // Format inner attributes if available.
159 if !self.krate.attrs.is_empty() && is_root {
160 visitor.skip_empty_lines(source_file.end_pos);
161 if visitor.visit_attrs(&self.krate.attrs, ast::AttrStyle::Inner) {
162 visitor.push_rewrite(module.inner, None);
164 visitor.format_separate_mod(module, &*source_file);
167 visitor.last_pos = source_file.start_pos;
168 visitor.skip_empty_lines(source_file.end_pos);
169 visitor.format_separate_mod(module, &*source_file);
172 debug_assert_eq!(visitor.line_number, count_newlines(&visitor.buffer));
174 // For some reason, the source_map does not include terminating
175 // newlines so we must add one on for each file. This is sad.
176 source_file::append_newline(&mut visitor.buffer);
181 &visitor.skipped_range,
187 .apply(&mut visitor.buffer, &big_snippet);
189 if visitor.macro_rewrite_failure {
190 self.report.add_macro_format_failure();
193 .add_non_formatted_ranges(visitor.skipped_range.clone());
195 self.handler.handle_formatted_file(
196 self.parse_session.source_map(),
198 visitor.buffer.to_owned(),
204 // Handle the results of formatting.
205 trait FormatHandler {
206 fn handle_formatted_file(
208 source_map: &SourceMap,
211 report: &mut FormatReport,
212 ) -> Result<(), ErrorKind>;
215 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
216 // Called for each formatted file.
217 fn handle_formatted_file(
219 source_map: &SourceMap,
222 report: &mut FormatReport,
223 ) -> Result<(), ErrorKind> {
224 if let Some(ref mut out) = self.out {
225 match source_file::write_file(Some(source_map), &path, &result, out, &self.config) {
226 Ok(has_diff) if has_diff => report.add_diff(),
228 // Create a new error with path_str to help users see which files failed
229 let err_msg = format!("{}: {}", path, e);
230 return Err(io::Error::new(e.kind(), err_msg).into());
236 self.source_file.push((path, result));
241 pub(crate) struct FormattingError {
242 pub(crate) line: usize,
243 pub(crate) kind: ErrorKind,
246 pub(crate) line_buffer: String,
249 impl FormattingError {
250 pub(crate) fn from_span(
252 source_map: &SourceMap,
254 ) -> FormattingError {
256 line: source_map.lookup_char_pos(span.lo()).line,
257 is_comment: kind.is_comment(),
260 line_buffer: source_map
265 .get_line(fl.lines[0].line_index)
266 .map(std::borrow::Cow::into_owned)
268 .unwrap_or_else(String::new),
272 pub(crate) fn msg_prefix(&self) -> &str {
274 ErrorKind::LineOverflow(..)
275 | ErrorKind::TrailingWhitespace
276 | ErrorKind::IoError(_)
277 | ErrorKind::ParseError
278 | ErrorKind::LostComment => "internal error:",
279 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
280 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
284 pub(crate) fn msg_suffix(&self) -> &str {
285 if self.is_comment || self.is_string {
286 "set `error_on_unformatted = false` to suppress \
287 the warning against comments or string literals\n"
294 pub(crate) fn format_len(&self) -> (usize, usize) {
296 ErrorKind::LineOverflow(found, max) => (max, found - max),
297 ErrorKind::TrailingWhitespace
298 | ErrorKind::DeprecatedAttr
299 | ErrorKind::BadIssue(_)
301 | ErrorKind::LostComment => {
302 let trailing_ws_start = self
304 .rfind(|c: char| !c.is_whitespace())
309 self.line_buffer.len() - trailing_ws_start,
317 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
319 #[derive(Default, Debug, PartialEq)]
320 pub(crate) struct ReportedErrors {
321 // Encountered e.g., an IO error.
322 pub(crate) has_operational_errors: bool,
324 // Failed to reformat code because of parsing errors.
325 pub(crate) has_parsing_errors: bool,
327 // Code is valid, but it is impossible to format it properly.
328 pub(crate) has_formatting_errors: bool,
330 // Code contains macro call that was unable to format.
331 pub(crate) has_macro_format_failure: bool,
333 // Failed a check, such as the license check or other opt-in checking.
334 pub(crate) has_check_errors: bool,
336 /// Formatted code differs from existing code (--check only).
337 pub(crate) has_diff: bool,
340 impl ReportedErrors {
341 /// Combine two summaries together.
342 pub fn add(&mut self, other: &ReportedErrors) {
343 self.has_operational_errors |= other.has_operational_errors;
344 self.has_parsing_errors |= other.has_parsing_errors;
345 self.has_formatting_errors |= other.has_formatting_errors;
346 self.has_macro_format_failure |= other.has_macro_format_failure;
347 self.has_check_errors |= other.has_check_errors;
348 self.has_diff |= other.has_diff;
352 #[derive(Clone, Copy, Debug)]
355 Initialized(Instant),
356 DoneParsing(Instant, Instant),
357 DoneFormatting(Instant, Instant, Instant),
361 fn start() -> Timer {
362 if cfg!(target_arch = "wasm32") {
365 Timer::Initialized(Instant::now())
368 fn done_parsing(self) -> Self {
370 Timer::Disabled => Timer::Disabled,
371 Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
372 _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
376 fn done_formatting(self) -> Self {
378 Timer::Disabled => Timer::Disabled,
379 Timer::DoneParsing(init_time, parse_time) => {
380 Timer::DoneFormatting(init_time, parse_time, Instant::now())
382 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
386 /// Returns the time it took to parse the source files in seconds.
387 fn get_parse_time(&self) -> f32 {
389 Timer::Disabled => panic!("this platform cannot time execution"),
390 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
391 // This should never underflow since `Instant::now()` guarantees monotonicity.
392 Self::duration_to_f32(parse_time.duration_since(init))
394 Timer::Initialized(..) => unreachable!(),
398 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
400 fn get_format_time(&self) -> f32 {
402 Timer::Disabled => panic!("this platform cannot time execution"),
403 Timer::DoneFormatting(_init, parse_time, format_time) => {
404 Self::duration_to_f32(format_time.duration_since(parse_time))
406 Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
410 fn duration_to_f32(d: Duration) -> f32 {
411 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
415 // Formatting done on a char by char or line by line basis.
416 // FIXME(#20): other stuff for parity with make tidy.
420 skipped_range: &[(usize, usize)],
422 report: &FormatReport,
424 let mut formatter = FormatLines::new(name, skipped_range, config);
425 formatter.check_license(text);
426 formatter.iterate(text);
428 if formatter.newline_count > 1 {
429 debug!("track truncate: {} {}", text.len(), formatter.newline_count);
430 let line = text.len() - formatter.newline_count + 1;
434 report.append(name.clone(), formatter.errors);
437 struct FormatLines<'a> {
439 skipped_range: &'a [(usize, usize)],
440 last_was_space: bool,
443 newline_count: usize,
444 errors: Vec<FormattingError>,
445 issue_seeker: BadIssueSeeker,
447 // `true` if the current line contains a string literal.
450 allow_issue_seek: bool,
454 impl<'a> FormatLines<'a> {
457 skipped_range: &'a [(usize, usize)],
459 ) -> FormatLines<'a> {
460 let issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
464 last_was_space: false,
469 allow_issue_seek: !issue_seeker.is_disabled(),
471 line_buffer: String::with_capacity(config.max_width() * 2),
473 format_line: config.file_lines().contains_line(name, 1),
478 fn check_license(&mut self, text: &mut String) {
479 if let Some(ref license_template) = self.config.license_template {
480 if !license_template.is_match(text) {
481 self.errors.push(FormattingError {
483 kind: ErrorKind::LicenseCheck,
486 line_buffer: String::new(),
492 // Iterate over the chars in the file map.
493 fn iterate(&mut self, text: &mut String) {
494 for (kind, c) in CharClasses::new(text.chars()) {
499 if self.allow_issue_seek && self.format_line {
500 // Add warnings for bad todos/ fixmes
501 if let Some(issue) = self.issue_seeker.inspect(c) {
502 self.push_err(ErrorKind::BadIssue(issue), false, false);
514 fn new_line(&mut self, kind: FullCodeCharKind) {
515 if self.format_line {
516 // Check for (and record) trailing whitespace.
517 if self.last_was_space {
518 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
519 && !self.is_skipped_line()
522 ErrorKind::TrailingWhitespace,
530 // Check for any line width errors we couldn't correct.
531 let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
532 if self.line_len > self.config.max_width()
533 && !self.is_skipped_line()
534 && self.should_report_error(kind, &error_kind)
536 let is_string = self.is_string;
537 self.push_err(error_kind, kind.is_comment(), is_string);
543 self.format_line = self
546 .contains_line(self.name, self.cur_line);
547 self.newline_count += 1;
548 self.last_was_space = false;
549 self.line_buffer.clear();
550 self.is_string = false;
553 fn char(&mut self, c: char, kind: FullCodeCharKind) {
554 self.newline_count = 0;
555 self.line_len += if c == '\t' {
556 self.config.tab_spaces()
560 self.last_was_space = c.is_whitespace();
561 self.line_buffer.push(c);
562 if kind.is_string() {
563 self.is_string = true;
567 fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
568 self.errors.push(FormattingError {
573 line_buffer: self.line_buffer.clone(),
577 fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
578 let allow_error_report =
579 if char_kind.is_comment() || self.is_string || error_kind.is_comment() {
580 self.config.error_on_unformatted()
586 ErrorKind::LineOverflow(..) => {
587 self.config.error_on_line_overflow() && allow_error_report
589 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
594 /// Returns `true` if the line with the given line number was skipped by `#[rustfmt::skip]`.
595 fn is_skipped_line(&self) -> bool {
598 .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
604 parse_session: &ParseSess,
606 report: &mut FormatReport,
607 directory_ownership: Option<parse::DirectoryOwnership>,
608 ) -> Result<ast::Crate, ErrorKind> {
609 let input_is_stdin = input.is_text();
611 let parser = match input {
612 Input::File(ref file) => {
613 // Use `new_sub_parser_from_file` when we the input is a submodule.
614 Ok(if let Some(dir_own) = directory_ownership {
615 parse::new_sub_parser_from_file(parse_session, file, dir_own, None, DUMMY_SP)
617 parse::new_parser_from_file(parse_session, file)
620 Input::Text(text) => parse::maybe_new_parser_from_source_str(
622 syntax::source_map::FileName::Custom("stdin".to_owned()),
626 parser.recurse_into_file_modules = false;
632 .map(|d| DiagnosticBuilder::new_diagnostic(&parse_session.span_diagnostic, d))
637 let result = match parser {
639 parser.cfg_mods = false;
640 if config.skip_children() {
641 parser.recurse_into_file_modules = false;
644 let mut parser = AssertUnwindSafe(parser);
645 catch_unwind(move || parser.0.parse_crate_mod().map_err(|d| vec![d]))
647 Err(db) => Ok(Err(db)),
652 if !parse_session.span_diagnostic.has_errors() {
656 Ok(Err(mut diagnostics)) => diagnostics.iter_mut().for_each(DiagnosticBuilder::emit),
658 // Note that if you see this message and want more information,
659 // then run the `parse_crate_mod` function above without
660 // `catch_unwind` so rustfmt panics and you can get a backtrace.
661 should_emit_verbose(input_is_stdin, config, || {
662 println!("The Rust parser panicked")
667 report.add_parsing_error();
668 Err(ErrorKind::ParseError)
671 /// Emitter which discards every error.
672 struct SilentEmitter;
674 impl Emitter for SilentEmitter {
675 fn emit(&mut self, _db: &DiagnosticBuilder<'_>) {}
678 fn silent_emitter() -> Box<SilentEmitter> {
679 Box::new(SilentEmitter {})
682 fn make_parse_sess(source_map: Rc<SourceMap>, config: &Config) -> ParseSess {
683 let tty_handler = if config.hide_parse_errors() {
684 let silent_emitter = silent_emitter();
685 Handler::with_emitter(true, None, silent_emitter)
687 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
688 let color_cfg = if supports_color {
693 Handler::with_tty_emitter(color_cfg, true, None, Some(source_map.clone()))
696 ParseSess::with_span_handler(tty_handler, source_map)
699 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
703 if config.verbose() == Verbosity::Verbose && !is_stdin {