1 // High level formatting functions.
3 use std::collections::HashMap;
4 use std::io::{self, Write};
5 use std::time::{Duration, Instant};
10 use self::newline_style::apply_newline_style;
11 use crate::comment::{CharClasses, FullCodeCharKind};
12 use crate::config::{Config, FileName, Verbosity};
13 use crate::formatting::generated::is_generated_file;
14 use crate::issues::BadIssueSeeker;
15 use crate::modules::Module;
16 use crate::syntux::parser::{DirectoryOwnership, Parser, ParserError};
17 use crate::syntux::session::ParseSess;
18 use crate::utils::count_newlines;
19 use crate::visitor::FmtVisitor;
20 use crate::{modules, source_file, ErrorKind, FormatReport, Input, Session};
25 // A map of the files of a crate, with their new content
26 pub(crate) type SourceFile = Vec<FileRecord>;
27 pub(crate) type FileRecord = (FileName, String);
29 impl<'b, T: Write + 'b> Session<'b, T> {
30 pub(crate) fn format_input_inner(
34 ) -> Result<FormatReport, ErrorKind> {
35 if !self.config.version_meets_requirement() {
36 return Err(ErrorKind::VersionMismatch);
39 rustc_span::create_session_if_not_set_then(self.config.edition().into(), |_| {
40 if self.config.disable_all_formatting() {
41 // When the input is from stdin, echo back the input.
42 if let Input::Text(ref buf) = input {
43 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
44 return Err(From::from(e));
47 return Ok(FormatReport::new());
50 let config = &self.config.clone();
51 let format_result = format_project(input, config, self, is_macro_def);
53 format_result.map(|report| {
54 self.errors.add(&report.internal.borrow().1);
61 // Format an entire crate (or subset of the module tree).
62 fn format_project<T: FormatHandler>(
67 ) -> Result<FormatReport, ErrorKind> {
68 let mut timer = Timer::start();
70 let main_file = input.file_name();
71 let input_is_stdin = main_file == FileName::Stdin;
73 let parse_session = ParseSess::new(config)?;
74 if config.skip_children() && parse_session.ignore_file(&main_file) {
75 return Ok(FormatReport::new());
79 let mut report = FormatReport::new();
80 let directory_ownership = input.to_directory_ownership();
81 let krate = match Parser::parse_crate(input, &parse_session) {
83 // Surface parse error via Session (errors are merged there from report)
85 let forbid_verbose = input_is_stdin || e != ParserError::ParsePanicError;
86 should_emit_verbose(forbid_verbose, config, || {
87 eprintln!("The Rust parser panicked");
89 report.add_parsing_error();
94 let mut context = FormatContext::new(&krate, report, parse_session, config, handler);
95 let files = modules::ModResolver::new(
96 &context.parse_session,
97 directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaBlock),
98 !input_is_stdin && !config.skip_children(),
100 .visit_crate(&krate)?;
102 timer = timer.done_parsing();
104 // Suppress error output if we have to do any further parsing.
105 context.parse_session.set_silent_emitter();
107 for (path, module) in files {
108 let source_file = context.parse_session.span_to_file_contents(module.span);
109 let src = source_file.src.as_ref().expect("SourceFile without src");
111 let should_ignore = (!input_is_stdin && context.ignore_file(&path))
112 || (!config.format_generated_files() && is_generated_file(src));
114 if (config.skip_children() && path != main_file) || should_ignore {
117 should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
118 context.format_file(path, &module, is_macro_def)?;
120 timer = timer.done_formatting();
122 should_emit_verbose(input_is_stdin, config, || {
124 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
125 timer.get_parse_time(),
126 timer.get_format_time(),
133 // Used for formatting files.
135 struct FormatContext<'a, T: FormatHandler> {
136 krate: &'a ast::Crate,
137 report: FormatReport,
138 parse_session: ParseSess,
143 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
144 fn ignore_file(&self, path: &FileName) -> bool {
145 self.parse_session.ignore_file(path)
148 // Formats a single file/module.
154 ) -> Result<(), ErrorKind> {
155 let snippet_provider = self.parse_session.snippet_provider(module.span);
156 let mut visitor = FmtVisitor::from_parse_sess(
162 visitor.skip_context.update_with_attrs(&self.krate.attrs);
163 visitor.is_macro_def = is_macro_def;
164 visitor.last_pos = snippet_provider.start_pos();
165 visitor.skip_empty_lines(snippet_provider.end_pos());
166 visitor.format_separate_mod(module, snippet_provider.end_pos());
170 count_newlines(&visitor.buffer),
171 "failed in format_file visitor.buffer:\n {:?}",
175 // For some reason, the source_map does not include terminating
176 // newlines so we must add one on for each file. This is sad.
177 source_file::append_newline(&mut visitor.buffer);
182 &visitor.skipped_range.borrow(),
188 self.config.newline_style(),
190 snippet_provider.entire_snippet(),
193 if visitor.macro_rewrite_failure {
194 self.report.add_macro_format_failure();
197 .add_non_formatted_ranges(visitor.skipped_range.borrow().clone());
199 self.handler.handle_formatted_file(
202 visitor.buffer.to_owned(),
208 // Handle the results of formatting.
209 trait FormatHandler {
210 fn handle_formatted_file(
212 parse_session: &ParseSess,
215 report: &mut FormatReport,
216 ) -> Result<(), ErrorKind>;
219 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
220 // Called for each formatted file.
221 fn handle_formatted_file(
223 parse_session: &ParseSess,
226 report: &mut FormatReport,
227 ) -> Result<(), ErrorKind> {
228 if let Some(ref mut out) = self.out {
229 match source_file::write_file(
235 self.config.newline_style(),
237 Ok(ref result) if result.has_diff => report.add_diff(),
239 // Create a new error with path_str to help users see which files failed
240 let err_msg = format!("{}: {}", path, e);
241 return Err(io::Error::new(e.kind(), err_msg).into());
247 self.source_file.push((path, result));
252 pub(crate) struct FormattingError {
253 pub(crate) line: usize,
254 pub(crate) kind: ErrorKind,
257 pub(crate) line_buffer: String,
260 impl FormattingError {
261 pub(crate) fn from_span(
263 parse_sess: &ParseSess,
265 ) -> FormattingError {
267 line: parse_sess.line_of_byte_pos(span.lo()),
268 is_comment: kind.is_comment(),
271 line_buffer: parse_sess.span_to_first_line_string(span),
275 pub(crate) fn is_internal(&self) -> bool {
277 ErrorKind::LineOverflow(..)
278 | ErrorKind::TrailingWhitespace
279 | ErrorKind::IoError(_)
280 | ErrorKind::ParseError
281 | ErrorKind::LostComment => true,
286 pub(crate) fn msg_suffix(&self) -> &str {
287 if self.is_comment || self.is_string {
288 "set `error_on_unformatted = false` to suppress \
289 the warning against comments or string literals\n"
296 pub(crate) fn format_len(&self) -> (usize, usize) {
298 ErrorKind::LineOverflow(found, max) => (max, found - max),
299 ErrorKind::TrailingWhitespace
300 | ErrorKind::DeprecatedAttr
301 | ErrorKind::BadIssue(_)
303 | ErrorKind::LostComment
304 | ErrorKind::LicenseCheck => {
305 let trailing_ws_start = self
307 .rfind(|c: char| !c.is_whitespace())
312 self.line_buffer.len() - trailing_ws_start,
320 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
322 #[derive(Default, Debug, PartialEq)]
323 pub(crate) struct ReportedErrors {
324 // Encountered e.g., an IO error.
325 pub(crate) has_operational_errors: bool,
327 // Failed to reformat code because of parsing errors.
328 pub(crate) has_parsing_errors: bool,
330 // Code is valid, but it is impossible to format it properly.
331 pub(crate) has_formatting_errors: bool,
333 // Code contains macro call that was unable to format.
334 pub(crate) has_macro_format_failure: bool,
336 // Failed a check, such as the license check or other opt-in checking.
337 pub(crate) has_check_errors: bool,
339 /// Formatted code differs from existing code (--check only).
340 pub(crate) has_diff: bool,
342 /// Formatted code missed something, like lost comments or extra trailing space
343 pub(crate) has_unformatted_code_errors: bool,
346 impl ReportedErrors {
347 /// Combine two summaries together.
348 pub(crate) fn add(&mut self, other: &ReportedErrors) {
349 self.has_operational_errors |= other.has_operational_errors;
350 self.has_parsing_errors |= other.has_parsing_errors;
351 self.has_formatting_errors |= other.has_formatting_errors;
352 self.has_macro_format_failure |= other.has_macro_format_failure;
353 self.has_check_errors |= other.has_check_errors;
354 self.has_diff |= other.has_diff;
355 self.has_unformatted_code_errors |= other.has_unformatted_code_errors;
359 #[derive(Clone, Copy, Debug)]
362 Initialized(Instant),
363 DoneParsing(Instant, Instant),
364 DoneFormatting(Instant, Instant, Instant),
368 fn start() -> Timer {
369 if cfg!(target_arch = "wasm32") {
372 Timer::Initialized(Instant::now())
375 fn done_parsing(self) -> Self {
377 Timer::Disabled => Timer::Disabled,
378 Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
379 _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
383 fn done_formatting(self) -> Self {
385 Timer::Disabled => Timer::Disabled,
386 Timer::DoneParsing(init_time, parse_time) => {
387 Timer::DoneFormatting(init_time, parse_time, Instant::now())
389 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
393 /// Returns the time it took to parse the source files in seconds.
394 fn get_parse_time(&self) -> f32 {
396 Timer::Disabled => panic!("this platform cannot time execution"),
397 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
398 // This should never underflow since `Instant::now()` guarantees monotonicity.
399 Self::duration_to_f32(parse_time.duration_since(init))
401 Timer::Initialized(..) => unreachable!(),
405 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
407 fn get_format_time(&self) -> f32 {
409 Timer::Disabled => panic!("this platform cannot time execution"),
410 Timer::DoneFormatting(_init, parse_time, format_time) => {
411 Self::duration_to_f32(format_time.duration_since(parse_time))
413 Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
417 fn duration_to_f32(d: Duration) -> f32 {
418 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
422 // Formatting done on a char by char or line by line basis.
423 // FIXME(#20): other stuff for parity with make tidy.
427 skipped_range: &[(usize, usize)],
429 report: &FormatReport,
431 let mut formatter = FormatLines::new(name, skipped_range, config);
432 formatter.check_license(text);
433 formatter.iterate(text);
435 if formatter.newline_count > 1 {
436 debug!("track truncate: {} {}", text.len(), formatter.newline_count);
437 let line = text.len() - formatter.newline_count + 1;
441 report.append(name.clone(), formatter.errors);
444 struct FormatLines<'a> {
446 skipped_range: &'a [(usize, usize)],
447 last_was_space: bool,
450 newline_count: usize,
451 errors: Vec<FormattingError>,
452 issue_seeker: BadIssueSeeker,
454 current_line_contains_string_literal: bool,
456 allow_issue_seek: bool,
460 impl<'a> FormatLines<'a> {
463 skipped_range: &'a [(usize, usize)],
465 ) -> FormatLines<'a> {
466 let issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
470 last_was_space: false,
475 allow_issue_seek: !issue_seeker.is_disabled(),
477 line_buffer: String::with_capacity(config.max_width() * 2),
478 current_line_contains_string_literal: false,
479 format_line: config.file_lines().contains_line(name, 1),
484 fn check_license(&mut self, text: &mut String) {
485 if let Some(ref license_template) = self.config.license_template {
486 if !license_template.is_match(text) {
487 self.errors.push(FormattingError {
489 kind: ErrorKind::LicenseCheck,
492 line_buffer: String::new(),
498 // Iterate over the chars in the file map.
499 fn iterate(&mut self, text: &mut String) {
500 for (kind, c) in CharClasses::new(text.chars()) {
505 if self.allow_issue_seek && self.format_line {
506 // Add warnings for bad todos/ fixmes
507 if let Some(issue) = self.issue_seeker.inspect(c) {
508 self.push_err(ErrorKind::BadIssue(issue), false, false);
520 fn new_line(&mut self, kind: FullCodeCharKind) {
521 if self.format_line {
522 // Check for (and record) trailing whitespace.
523 if self.last_was_space {
524 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
525 && !self.is_skipped_line()
528 ErrorKind::TrailingWhitespace,
536 // Check for any line width errors we couldn't correct.
537 let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
538 if self.line_len > self.config.max_width()
539 && !self.is_skipped_line()
540 && self.should_report_error(kind, &error_kind)
542 let is_string = self.current_line_contains_string_literal;
543 self.push_err(error_kind, kind.is_comment(), is_string);
549 self.format_line = self
552 .contains_line(self.name, self.cur_line);
553 self.newline_count += 1;
554 self.last_was_space = false;
555 self.line_buffer.clear();
556 self.current_line_contains_string_literal = false;
559 fn char(&mut self, c: char, kind: FullCodeCharKind) {
560 self.newline_count = 0;
561 self.line_len += if c == '\t' {
562 self.config.tab_spaces()
566 self.last_was_space = c.is_whitespace();
567 self.line_buffer.push(c);
568 if kind.is_string() {
569 self.current_line_contains_string_literal = true;
573 fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
574 self.errors.push(FormattingError {
579 line_buffer: self.line_buffer.clone(),
583 fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
584 let allow_error_report = if char_kind.is_comment()
585 || self.current_line_contains_string_literal
586 || error_kind.is_comment()
588 self.config.error_on_unformatted()
594 ErrorKind::LineOverflow(..) => {
595 self.config.error_on_line_overflow() && allow_error_report
597 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
602 /// Returns `true` if the line with the given line number was skipped by `#[rustfmt::skip]`.
603 fn is_skipped_line(&self) -> bool {
606 .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
610 fn should_emit_verbose<F>(forbid_verbose_output: bool, config: &Config, f: F)
614 if config.verbose() == Verbosity::Verbose && !forbid_verbose_output {