1 // High level formatting functions.
3 use std::collections::HashMap;
4 use std::io::{self, Write};
5 use std::time::{Duration, Instant};
8 use rustc_ast::AstLike;
11 use self::newline_style::apply_newline_style;
12 use crate::comment::{CharClasses, FullCodeCharKind};
13 use crate::config::{Config, FileName, Verbosity};
14 use crate::formatting::generated::is_generated_file;
15 use crate::issues::BadIssueSeeker;
16 use crate::modules::Module;
17 use crate::parse::parser::{DirectoryOwnership, Parser, ParserError};
18 use crate::parse::session::ParseSess;
19 use crate::utils::{contains_skip, count_newlines};
20 use crate::visitor::FmtVisitor;
21 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(
35 ) -> Result<FormatReport, ErrorKind> {
36 if !self.config.version_meets_requirement() {
37 return Err(ErrorKind::VersionMismatch);
40 rustc_span::create_session_if_not_set_then(self.config.edition().into(), |_| {
41 if self.config.disable_all_formatting() {
42 // When the input is from stdin, echo back the input.
43 if let Input::Text(ref buf) = input {
44 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
45 return Err(From::from(e));
48 return Ok(FormatReport::new());
51 let config = &self.config.clone();
52 let format_result = format_project(input, config, self, is_macro_def);
54 format_result.map(|report| {
55 self.errors.add(&report.internal.borrow().1);
62 /// Determine if a module should be skipped. True if the module should be skipped, false otherwise.
63 fn should_skip_module<T: FormatHandler>(
65 context: &FormatContext<'_, T>,
71 if contains_skip(module.attrs()) {
75 if config.skip_children() && path != main_file {
79 if !input_is_stdin && context.ignore_file(path) {
83 // FIXME(calebcartwright) - we need to determine how we'll handle the
84 // `format_generated_files` option with stdin based input.
85 if !input_is_stdin && !config.format_generated_files() {
86 let source_file = context.parse_session.span_to_file_contents(module.span);
87 let src = source_file.src.as_ref().expect("SourceFile without src");
89 if is_generated_file(src) {
97 // Format an entire crate (or subset of the module tree).
98 fn format_project<T: FormatHandler>(
103 ) -> Result<FormatReport, ErrorKind> {
104 let mut timer = Timer::start();
106 let main_file = input.file_name();
107 let input_is_stdin = main_file == FileName::Stdin;
109 let parse_session = ParseSess::new(config)?;
110 if config.skip_children() && parse_session.ignore_file(&main_file) {
111 return Ok(FormatReport::new());
115 let mut report = FormatReport::new();
116 let directory_ownership = input.to_directory_ownership();
117 let krate = match Parser::parse_crate(input, &parse_session) {
119 // Surface parse error via Session (errors are merged there from report)
121 let forbid_verbose = input_is_stdin || e != ParserError::ParsePanicError;
122 should_emit_verbose(forbid_verbose, config, || {
123 eprintln!("The Rust parser panicked");
125 report.add_parsing_error();
130 let mut context = FormatContext::new(&krate, report, parse_session, config, handler);
131 let files = modules::ModResolver::new(
132 &context.parse_session,
133 directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaBlock),
134 !input_is_stdin && !config.skip_children(),
136 .visit_crate(&krate)?
138 .filter(|(path, module)| {
139 !should_skip_module(config, &context, input_is_stdin, &main_file, path, module)
141 .collect::<Vec<_>>();
143 timer = timer.done_parsing();
145 // Suppress error output if we have to do any further parsing.
146 context.parse_session.set_silent_emitter();
148 for (path, module) in files {
149 should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
150 context.format_file(path, &module, is_macro_def)?;
152 timer = timer.done_formatting();
154 should_emit_verbose(input_is_stdin, config, || {
156 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
157 timer.get_parse_time(),
158 timer.get_format_time(),
165 // Used for formatting files.
167 struct FormatContext<'a, T: FormatHandler> {
168 krate: &'a ast::Crate,
169 report: FormatReport,
170 parse_session: ParseSess,
175 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
176 fn ignore_file(&self, path: &FileName) -> bool {
177 self.parse_session.ignore_file(path)
180 // Formats a single file/module.
186 ) -> Result<(), ErrorKind> {
187 let snippet_provider = self.parse_session.snippet_provider(module.span);
188 let mut visitor = FmtVisitor::from_parse_sess(
194 visitor.skip_context.update_with_attrs(&self.krate.attrs);
195 visitor.is_macro_def = is_macro_def;
196 visitor.last_pos = snippet_provider.start_pos();
197 visitor.skip_empty_lines(snippet_provider.end_pos());
198 visitor.format_separate_mod(module, snippet_provider.end_pos());
202 count_newlines(&visitor.buffer),
203 "failed in format_file visitor.buffer:\n {:?}",
207 // For some reason, the source_map does not include terminating
208 // newlines so we must add one on for each file. This is sad.
209 source_file::append_newline(&mut visitor.buffer);
214 &visitor.skipped_range.borrow(),
220 self.config.newline_style(),
222 snippet_provider.entire_snippet(),
225 if visitor.macro_rewrite_failure {
226 self.report.add_macro_format_failure();
229 .add_non_formatted_ranges(visitor.skipped_range.borrow().clone());
231 self.handler.handle_formatted_file(
234 visitor.buffer.to_owned(),
240 // Handle the results of formatting.
241 trait FormatHandler {
242 fn handle_formatted_file(
244 parse_session: &ParseSess,
247 report: &mut FormatReport,
248 ) -> Result<(), ErrorKind>;
251 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
252 // Called for each formatted file.
253 fn handle_formatted_file(
255 parse_session: &ParseSess,
258 report: &mut FormatReport,
259 ) -> Result<(), ErrorKind> {
260 if let Some(ref mut out) = self.out {
261 match source_file::write_file(
267 self.config.newline_style(),
269 Ok(ref result) if result.has_diff => report.add_diff(),
271 // Create a new error with path_str to help users see which files failed
272 let err_msg = format!("{}: {}", path, e);
273 return Err(io::Error::new(e.kind(), err_msg).into());
279 self.source_file.push((path, result));
284 pub(crate) struct FormattingError {
285 pub(crate) line: usize,
286 pub(crate) kind: ErrorKind,
289 pub(crate) line_buffer: String,
292 impl FormattingError {
293 pub(crate) fn from_span(
295 parse_sess: &ParseSess,
297 ) -> FormattingError {
299 line: parse_sess.line_of_byte_pos(span.lo()),
300 is_comment: kind.is_comment(),
303 line_buffer: parse_sess.span_to_first_line_string(span),
307 pub(crate) fn is_internal(&self) -> bool {
309 ErrorKind::LineOverflow(..)
310 | ErrorKind::TrailingWhitespace
311 | ErrorKind::IoError(_)
312 | ErrorKind::ParseError
313 | ErrorKind::LostComment => true,
318 pub(crate) fn msg_suffix(&self) -> &str {
319 if self.is_comment || self.is_string {
320 "set `error_on_unformatted = false` to suppress \
321 the warning against comments or string literals\n"
328 pub(crate) fn format_len(&self) -> (usize, usize) {
330 ErrorKind::LineOverflow(found, max) => (max, found - max),
331 ErrorKind::TrailingWhitespace
332 | ErrorKind::DeprecatedAttr
333 | ErrorKind::BadIssue(_)
335 | ErrorKind::LostComment
336 | ErrorKind::LicenseCheck => {
337 let trailing_ws_start = self
339 .rfind(|c: char| !c.is_whitespace())
344 self.line_buffer.len() - trailing_ws_start,
352 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
354 #[derive(Default, Debug, PartialEq)]
355 pub(crate) struct ReportedErrors {
356 // Encountered e.g., an IO error.
357 pub(crate) has_operational_errors: bool,
359 // Failed to reformat code because of parsing errors.
360 pub(crate) has_parsing_errors: bool,
362 // Code is valid, but it is impossible to format it properly.
363 pub(crate) has_formatting_errors: bool,
365 // Code contains macro call that was unable to format.
366 pub(crate) has_macro_format_failure: bool,
368 // Failed a check, such as the license check or other opt-in checking.
369 pub(crate) has_check_errors: bool,
371 /// Formatted code differs from existing code (--check only).
372 pub(crate) has_diff: bool,
374 /// Formatted code missed something, like lost comments or extra trailing space
375 pub(crate) has_unformatted_code_errors: bool,
378 impl ReportedErrors {
379 /// Combine two summaries together.
380 pub(crate) fn add(&mut self, other: &ReportedErrors) {
381 self.has_operational_errors |= other.has_operational_errors;
382 self.has_parsing_errors |= other.has_parsing_errors;
383 self.has_formatting_errors |= other.has_formatting_errors;
384 self.has_macro_format_failure |= other.has_macro_format_failure;
385 self.has_check_errors |= other.has_check_errors;
386 self.has_diff |= other.has_diff;
387 self.has_unformatted_code_errors |= other.has_unformatted_code_errors;
391 #[derive(Clone, Copy, Debug)]
394 Initialized(Instant),
395 DoneParsing(Instant, Instant),
396 DoneFormatting(Instant, Instant, Instant),
400 fn start() -> Timer {
401 if cfg!(target_arch = "wasm32") {
404 Timer::Initialized(Instant::now())
407 fn done_parsing(self) -> Self {
409 Timer::Disabled => Timer::Disabled,
410 Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
411 _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
415 fn done_formatting(self) -> Self {
417 Timer::Disabled => Timer::Disabled,
418 Timer::DoneParsing(init_time, parse_time) => {
419 Timer::DoneFormatting(init_time, parse_time, Instant::now())
421 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
425 /// Returns the time it took to parse the source files in seconds.
426 fn get_parse_time(&self) -> f32 {
428 Timer::Disabled => panic!("this platform cannot time execution"),
429 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
430 // This should never underflow since `Instant::now()` guarantees monotonicity.
431 Self::duration_to_f32(parse_time.duration_since(init))
433 Timer::Initialized(..) => unreachable!(),
437 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
439 fn get_format_time(&self) -> f32 {
441 Timer::Disabled => panic!("this platform cannot time execution"),
442 Timer::DoneFormatting(_init, parse_time, format_time) => {
443 Self::duration_to_f32(format_time.duration_since(parse_time))
445 Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
449 fn duration_to_f32(d: Duration) -> f32 {
450 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
454 // Formatting done on a char by char or line by line basis.
455 // FIXME(#20): other stuff for parity with make tidy.
459 skipped_range: &[(usize, usize)],
461 report: &FormatReport,
463 let mut formatter = FormatLines::new(name, skipped_range, config);
464 formatter.check_license(text);
465 formatter.iterate(text);
467 if formatter.newline_count > 1 {
468 debug!("track truncate: {} {}", text.len(), formatter.newline_count);
469 let line = text.len() - formatter.newline_count + 1;
473 report.append(name.clone(), formatter.errors);
476 struct FormatLines<'a> {
478 skipped_range: &'a [(usize, usize)],
479 last_was_space: bool,
482 newline_count: usize,
483 errors: Vec<FormattingError>,
484 issue_seeker: BadIssueSeeker,
486 current_line_contains_string_literal: bool,
488 allow_issue_seek: bool,
492 impl<'a> FormatLines<'a> {
495 skipped_range: &'a [(usize, usize)],
497 ) -> FormatLines<'a> {
498 let issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
502 last_was_space: false,
507 allow_issue_seek: !issue_seeker.is_disabled(),
509 line_buffer: String::with_capacity(config.max_width() * 2),
510 current_line_contains_string_literal: false,
511 format_line: config.file_lines().contains_line(name, 1),
516 fn check_license(&mut self, text: &mut String) {
517 if let Some(ref license_template) = self.config.license_template {
518 if !license_template.is_match(text) {
519 self.errors.push(FormattingError {
521 kind: ErrorKind::LicenseCheck,
524 line_buffer: String::new(),
530 // Iterate over the chars in the file map.
531 fn iterate(&mut self, text: &mut String) {
532 for (kind, c) in CharClasses::new(text.chars()) {
537 if self.allow_issue_seek && self.format_line {
538 // Add warnings for bad todos/ fixmes
539 if let Some(issue) = self.issue_seeker.inspect(c) {
540 self.push_err(ErrorKind::BadIssue(issue), false, false);
552 fn new_line(&mut self, kind: FullCodeCharKind) {
553 if self.format_line {
554 // Check for (and record) trailing whitespace.
555 if self.last_was_space {
556 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
557 && !self.is_skipped_line()
560 ErrorKind::TrailingWhitespace,
568 // Check for any line width errors we couldn't correct.
569 let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
570 if self.line_len > self.config.max_width()
571 && !self.is_skipped_line()
572 && self.should_report_error(kind, &error_kind)
574 let is_string = self.current_line_contains_string_literal;
575 self.push_err(error_kind, kind.is_comment(), is_string);
581 self.format_line = self
584 .contains_line(self.name, self.cur_line);
585 self.newline_count += 1;
586 self.last_was_space = false;
587 self.line_buffer.clear();
588 self.current_line_contains_string_literal = false;
591 fn char(&mut self, c: char, kind: FullCodeCharKind) {
592 self.newline_count = 0;
593 self.line_len += if c == '\t' {
594 self.config.tab_spaces()
598 self.last_was_space = c.is_whitespace();
599 self.line_buffer.push(c);
600 if kind.is_string() {
601 self.current_line_contains_string_literal = true;
605 fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
606 self.errors.push(FormattingError {
611 line_buffer: self.line_buffer.clone(),
615 fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
616 let allow_error_report = if char_kind.is_comment()
617 || self.current_line_contains_string_literal
618 || error_kind.is_comment()
620 self.config.error_on_unformatted()
626 ErrorKind::LineOverflow(..) => {
627 self.config.error_on_line_overflow() && allow_error_report
629 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
634 /// Returns `true` if the line with the given line number was skipped by `#[rustfmt::skip]`.
635 fn is_skipped_line(&self) -> bool {
638 .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
642 fn should_emit_verbose<F>(forbid_verbose_output: bool, config: &Config, f: F)
646 if config.verbose() == Verbosity::Verbose && !forbid_verbose_output {