1 // High level formatting functions.
3 use std::collections::HashMap;
4 use std::io::{self, Write};
6 use std::time::{Duration, Instant};
9 use rustc_ast::AstLike;
12 use self::newline_style::apply_newline_style;
13 use crate::comment::{CharClasses, FullCodeCharKind};
14 use crate::config::{Config, FileName, Verbosity};
15 use crate::formatting::generated::is_generated_file;
16 use crate::issues::BadIssueSeeker;
17 use crate::modules::Module;
18 use crate::parse::parser::{DirectoryOwnership, Parser, ParserError};
19 use crate::parse::session::ParseSess;
20 use crate::utils::{contains_skip, count_newlines};
21 use crate::visitor::FmtVisitor;
22 use crate::{modules, source_file, ErrorKind, FormatReport, Input, Session};
27 // A map of the files of a crate, with their new content
28 pub(crate) type SourceFile = Vec<FileRecord>;
29 pub(crate) type FileRecord = (FileName, String);
31 impl<'b, T: Write + 'b> Session<'b, T> {
32 pub(crate) fn format_input_inner(
36 ) -> Result<FormatReport, ErrorKind> {
37 if !self.config.version_meets_requirement() {
38 return Err(ErrorKind::VersionMismatch);
41 rustc_span::create_session_if_not_set_then(self.config.edition().into(), |_| {
42 if self.config.disable_all_formatting() {
43 // When the input is from stdin, echo back the input.
44 if let Input::Text(ref buf) = input {
45 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
46 return Err(From::from(e));
49 return Ok(FormatReport::new());
52 let config = &self.config.clone();
53 let format_result = format_project(input, config, self, is_macro_def);
55 format_result.map(|report| {
56 self.errors.add(&report.internal.borrow().1);
63 /// Determine if a module should be skipped. True if the module should be skipped, false otherwise.
64 fn should_skip_module<T: FormatHandler>(
66 context: &FormatContext<'_, T>,
72 if contains_skip(module.attrs()) {
76 if config.skip_children() && path != main_file {
80 if !input_is_stdin && context.ignore_file(path) {
84 // FIXME(calebcartwright) - we need to determine how we'll handle the
85 // `format_generated_files` option with stdin based input.
86 if !input_is_stdin && !config.format_generated_files() {
87 let source_file = context.parse_session.span_to_file_contents(module.span);
88 let src = source_file.src.as_ref().expect("SourceFile without src");
90 if is_generated_file(src) {
98 // Format an entire crate (or subset of the module tree).
99 fn format_project<T: FormatHandler>(
104 ) -> Result<FormatReport, ErrorKind> {
105 let mut timer = Timer::start();
107 let main_file = input.file_name();
108 let input_is_stdin = main_file == FileName::Stdin;
110 let parse_session = ParseSess::new(config)?;
111 if config.skip_children() && parse_session.ignore_file(&main_file) {
112 return Ok(FormatReport::new());
116 let mut report = FormatReport::new();
117 let directory_ownership = input.to_directory_ownership();
118 let krate = match Parser::parse_crate(input, &parse_session) {
120 // Surface parse error via Session (errors are merged there from report)
122 let forbid_verbose = input_is_stdin || e != ParserError::ParsePanicError;
123 should_emit_verbose(forbid_verbose, config, || {
124 eprintln!("The Rust parser panicked");
126 report.add_parsing_error();
131 let mut context = FormatContext::new(&krate, report, parse_session, config, handler);
132 let files = modules::ModResolver::new(
133 &context.parse_session,
134 directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaBlock),
135 !input_is_stdin && !config.skip_children(),
137 .visit_crate(&krate)?
139 .filter(|(path, module)| {
140 !should_skip_module(config, &context, input_is_stdin, &main_file, path, module)
142 .collect::<Vec<_>>();
144 timer = timer.done_parsing();
146 // Suppress error output if we have to do any further parsing.
147 context.parse_session.set_silent_emitter();
149 for (path, module) in files {
150 should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
151 context.format_file(path, &module, is_macro_def)?;
153 timer = timer.done_formatting();
155 should_emit_verbose(input_is_stdin, config, || {
157 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
158 timer.get_parse_time(),
159 timer.get_format_time(),
166 // Used for formatting files.
168 struct FormatContext<'a, T: FormatHandler> {
169 krate: &'a ast::Crate,
170 report: FormatReport,
171 parse_session: ParseSess,
176 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
177 fn ignore_file(&self, path: &FileName) -> bool {
178 self.parse_session.ignore_file(path)
181 // Formats a single file/module.
187 ) -> Result<(), ErrorKind> {
188 let snippet_provider = self.parse_session.snippet_provider(module.span);
189 let mut visitor = FmtVisitor::from_parse_sess(
196 visitor.skip_context.update_with_attrs(&self.krate.attrs);
197 visitor.is_macro_def = is_macro_def;
198 visitor.last_pos = snippet_provider.start_pos();
199 visitor.skip_empty_lines(snippet_provider.end_pos());
200 visitor.format_separate_mod(module, snippet_provider.end_pos());
204 count_newlines(&visitor.buffer),
205 "failed in format_file visitor.buffer:\n {:?}",
209 // For some reason, the source_map does not include terminating
210 // newlines so we must add one on for each file. This is sad.
211 source_file::append_newline(&mut visitor.buffer);
216 &visitor.skipped_range.borrow(),
222 self.config.newline_style(),
224 snippet_provider.entire_snippet(),
227 if visitor.macro_rewrite_failure {
228 self.report.add_macro_format_failure();
231 .add_non_formatted_ranges(visitor.skipped_range.borrow().clone());
233 self.handler.handle_formatted_file(
236 visitor.buffer.to_owned(),
242 // Handle the results of formatting.
243 trait FormatHandler {
244 fn handle_formatted_file(
246 parse_session: &ParseSess,
249 report: &mut FormatReport,
250 ) -> Result<(), ErrorKind>;
253 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
254 // Called for each formatted file.
255 fn handle_formatted_file(
257 parse_session: &ParseSess,
260 report: &mut FormatReport,
261 ) -> Result<(), ErrorKind> {
262 if let Some(ref mut out) = self.out {
263 match source_file::write_file(
269 self.config.newline_style(),
271 Ok(ref result) if result.has_diff => report.add_diff(),
273 // Create a new error with path_str to help users see which files failed
274 let err_msg = format!("{}: {}", path, e);
275 return Err(io::Error::new(e.kind(), err_msg).into());
281 self.source_file.push((path, result));
286 pub(crate) struct FormattingError {
287 pub(crate) line: usize,
288 pub(crate) kind: ErrorKind,
291 pub(crate) line_buffer: String,
294 impl FormattingError {
295 pub(crate) fn from_span(
297 parse_sess: &ParseSess,
299 ) -> FormattingError {
301 line: parse_sess.line_of_byte_pos(span.lo()),
302 is_comment: kind.is_comment(),
305 line_buffer: parse_sess.span_to_first_line_string(span),
309 pub(crate) fn is_internal(&self) -> bool {
311 ErrorKind::LineOverflow(..)
312 | ErrorKind::TrailingWhitespace
313 | ErrorKind::IoError(_)
314 | ErrorKind::ParseError
315 | ErrorKind::LostComment => true,
320 pub(crate) fn msg_suffix(&self) -> &str {
321 if self.is_comment || self.is_string {
322 "set `error_on_unformatted = false` to suppress \
323 the warning against comments or string literals\n"
330 pub(crate) fn format_len(&self) -> (usize, usize) {
332 ErrorKind::LineOverflow(found, max) => (max, found - max),
333 ErrorKind::TrailingWhitespace
334 | ErrorKind::DeprecatedAttr
335 | ErrorKind::BadIssue(_)
337 | ErrorKind::LostComment
338 | ErrorKind::LicenseCheck => {
339 let trailing_ws_start = self
341 .rfind(|c: char| !c.is_whitespace())
346 self.line_buffer.len() - trailing_ws_start,
354 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
356 #[derive(Default, Debug, PartialEq)]
357 pub(crate) struct ReportedErrors {
358 // Encountered e.g., an IO error.
359 pub(crate) has_operational_errors: bool,
361 // Failed to reformat code because of parsing errors.
362 pub(crate) has_parsing_errors: bool,
364 // Code is valid, but it is impossible to format it properly.
365 pub(crate) has_formatting_errors: bool,
367 // Code contains macro call that was unable to format.
368 pub(crate) has_macro_format_failure: bool,
370 // Failed a check, such as the license check or other opt-in checking.
371 pub(crate) has_check_errors: bool,
373 /// Formatted code differs from existing code (--check only).
374 pub(crate) has_diff: bool,
376 /// Formatted code missed something, like lost comments or extra trailing space
377 pub(crate) has_unformatted_code_errors: bool,
380 impl ReportedErrors {
381 /// Combine two summaries together.
382 pub(crate) fn add(&mut self, other: &ReportedErrors) {
383 self.has_operational_errors |= other.has_operational_errors;
384 self.has_parsing_errors |= other.has_parsing_errors;
385 self.has_formatting_errors |= other.has_formatting_errors;
386 self.has_macro_format_failure |= other.has_macro_format_failure;
387 self.has_check_errors |= other.has_check_errors;
388 self.has_diff |= other.has_diff;
389 self.has_unformatted_code_errors |= other.has_unformatted_code_errors;
393 #[derive(Clone, Copy, Debug)]
396 Initialized(Instant),
397 DoneParsing(Instant, Instant),
398 DoneFormatting(Instant, Instant, Instant),
402 fn start() -> Timer {
403 if cfg!(target_arch = "wasm32") {
406 Timer::Initialized(Instant::now())
409 fn done_parsing(self) -> Self {
411 Timer::Disabled => Timer::Disabled,
412 Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
413 _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
417 fn done_formatting(self) -> Self {
419 Timer::Disabled => Timer::Disabled,
420 Timer::DoneParsing(init_time, parse_time) => {
421 Timer::DoneFormatting(init_time, parse_time, Instant::now())
423 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
427 /// Returns the time it took to parse the source files in seconds.
428 fn get_parse_time(&self) -> f32 {
430 Timer::Disabled => panic!("this platform cannot time execution"),
431 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
432 // This should never underflow since `Instant::now()` guarantees monotonicity.
433 Self::duration_to_f32(parse_time.duration_since(init))
435 Timer::Initialized(..) => unreachable!(),
439 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
441 fn get_format_time(&self) -> f32 {
443 Timer::Disabled => panic!("this platform cannot time execution"),
444 Timer::DoneFormatting(_init, parse_time, format_time) => {
445 Self::duration_to_f32(format_time.duration_since(parse_time))
447 Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
451 fn duration_to_f32(d: Duration) -> f32 {
452 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
456 // Formatting done on a char by char or line by line basis.
457 // FIXME(#20): other stuff for parity with make tidy.
461 skipped_range: &[(usize, usize)],
463 report: &FormatReport,
465 let mut formatter = FormatLines::new(name, skipped_range, config);
466 formatter.check_license(text);
467 formatter.iterate(text);
469 if formatter.newline_count > 1 {
470 debug!("track truncate: {} {}", text.len(), formatter.newline_count);
471 let line = text.len() - formatter.newline_count + 1;
475 report.append(name.clone(), formatter.errors);
478 struct FormatLines<'a> {
480 skipped_range: &'a [(usize, usize)],
481 last_was_space: bool,
484 newline_count: usize,
485 errors: Vec<FormattingError>,
486 issue_seeker: BadIssueSeeker,
488 current_line_contains_string_literal: bool,
490 allow_issue_seek: bool,
494 impl<'a> FormatLines<'a> {
497 skipped_range: &'a [(usize, usize)],
499 ) -> FormatLines<'a> {
500 let issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
504 last_was_space: false,
509 allow_issue_seek: !issue_seeker.is_disabled(),
511 line_buffer: String::with_capacity(config.max_width() * 2),
512 current_line_contains_string_literal: false,
513 format_line: config.file_lines().contains_line(name, 1),
518 fn check_license(&mut self, text: &mut String) {
519 if let Some(ref license_template) = self.config.license_template {
520 if !license_template.is_match(text) {
521 self.errors.push(FormattingError {
523 kind: ErrorKind::LicenseCheck,
526 line_buffer: String::new(),
532 // Iterate over the chars in the file map.
533 fn iterate(&mut self, text: &mut String) {
534 for (kind, c) in CharClasses::new(text.chars()) {
539 if self.allow_issue_seek && self.format_line {
540 // Add warnings for bad todos/ fixmes
541 if let Some(issue) = self.issue_seeker.inspect(c) {
542 self.push_err(ErrorKind::BadIssue(issue), false, false);
554 fn new_line(&mut self, kind: FullCodeCharKind) {
555 if self.format_line {
556 // Check for (and record) trailing whitespace.
557 if self.last_was_space {
558 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
559 && !self.is_skipped_line()
562 ErrorKind::TrailingWhitespace,
570 // Check for any line width errors we couldn't correct.
571 let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
572 if self.line_len > self.config.max_width()
573 && !self.is_skipped_line()
574 && self.should_report_error(kind, &error_kind)
576 let is_string = self.current_line_contains_string_literal;
577 self.push_err(error_kind, kind.is_comment(), is_string);
583 self.format_line = self
586 .contains_line(self.name, self.cur_line);
587 self.newline_count += 1;
588 self.last_was_space = false;
589 self.line_buffer.clear();
590 self.current_line_contains_string_literal = false;
593 fn char(&mut self, c: char, kind: FullCodeCharKind) {
594 self.newline_count = 0;
595 self.line_len += if c == '\t' {
596 self.config.tab_spaces()
600 self.last_was_space = c.is_whitespace();
601 self.line_buffer.push(c);
602 if kind.is_string() {
603 self.current_line_contains_string_literal = true;
607 fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
608 self.errors.push(FormattingError {
613 line_buffer: self.line_buffer.clone(),
617 fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
618 let allow_error_report = if char_kind.is_comment()
619 || self.current_line_contains_string_literal
620 || error_kind.is_comment()
622 self.config.error_on_unformatted()
628 ErrorKind::LineOverflow(..) => {
629 self.config.error_on_line_overflow() && allow_error_report
631 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
636 /// Returns `true` if the line with the given line number was skipped by `#[rustfmt::skip]`.
637 fn is_skipped_line(&self) -> bool {
640 .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
644 fn should_emit_verbose<F>(forbid_verbose_output: bool, config: &Config, f: F)
648 if config.verbose() == Verbosity::Verbose && !forbid_verbose_output {