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::modules::Module;
15 use crate::parse::parser::{DirectoryOwnership, Parser, ParserError};
16 use crate::parse::session::ParseSess;
17 use crate::utils::{contains_skip, count_newlines};
18 use crate::visitor::FmtVisitor;
19 use crate::{modules, source_file, ErrorKind, FormatReport, Input, Session};
24 // A map of the files of a crate, with their new content
25 pub(crate) type SourceFile = Vec<FileRecord>;
26 pub(crate) type FileRecord = (FileName, String);
28 impl<'b, T: Write + 'b> Session<'b, T> {
29 pub(crate) fn format_input_inner(
33 ) -> Result<FormatReport, ErrorKind> {
34 if !self.config.version_meets_requirement() {
35 return Err(ErrorKind::VersionMismatch);
38 rustc_span::create_session_if_not_set_then(self.config.edition().into(), |_| {
39 if self.config.disable_all_formatting() {
40 // When the input is from stdin, echo back the input.
42 Input::Text(ref buf) => echo_back_stdin(buf),
43 _ => Ok(FormatReport::new()),
47 let config = &self.config.clone();
48 let format_result = format_project(input, config, self, is_macro_def);
50 format_result.map(|report| {
51 self.errors.add(&report.internal.borrow().1);
58 /// Determine if a module should be skipped. True if the module should be skipped, false otherwise.
59 fn should_skip_module<T: FormatHandler>(
61 context: &FormatContext<'_, T>,
67 if contains_skip(module.attrs()) {
71 if config.skip_children() && path != main_file {
75 if !input_is_stdin && context.ignore_file(path) {
79 // FIXME(calebcartwright) - we need to determine how we'll handle the
80 // `format_generated_files` option with stdin based input.
81 if !input_is_stdin && !config.format_generated_files() {
82 let source_file = context.parse_session.span_to_file_contents(module.span);
83 let src = source_file.src.as_ref().expect("SourceFile without src");
85 if is_generated_file(src) {
93 fn echo_back_stdin(input: &str) -> Result<FormatReport, ErrorKind> {
94 if let Err(e) = io::stdout().write_all(input.as_bytes()) {
95 return Err(From::from(e));
97 Ok(FormatReport::new())
100 // Format an entire crate (or subset of the module tree).
101 fn format_project<T: FormatHandler>(
106 ) -> Result<FormatReport, ErrorKind> {
107 let mut timer = Timer::start();
109 let main_file = input.file_name();
110 let input_is_stdin = main_file == FileName::Stdin;
112 let parse_session = ParseSess::new(config)?;
113 if config.skip_children() && parse_session.ignore_file(&main_file) {
114 return Ok(FormatReport::new());
118 let mut report = FormatReport::new();
119 let directory_ownership = input.to_directory_ownership();
120 let krate = match Parser::parse_crate(input, &parse_session) {
122 // Surface parse error via Session (errors are merged there from report)
124 let forbid_verbose = input_is_stdin || e != ParserError::ParsePanicError;
125 should_emit_verbose(forbid_verbose, config, || {
126 eprintln!("The Rust parser panicked");
128 report.add_parsing_error();
133 let mut context = FormatContext::new(&krate, report, parse_session, config, handler);
134 let files = modules::ModResolver::new(
135 &context.parse_session,
136 directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaBlock),
137 !input_is_stdin && !config.skip_children(),
139 .visit_crate(&krate)?
141 .filter(|(path, module)| {
143 || !should_skip_module(config, &context, input_is_stdin, &main_file, path, module)
145 .collect::<Vec<_>>();
147 timer = timer.done_parsing();
149 // Suppress error output if we have to do any further parsing.
150 context.parse_session.set_silent_emitter();
152 for (path, module) in files {
153 if input_is_stdin && contains_skip(module.attrs()) {
154 return echo_back_stdin(
157 .snippet_provider(module.span)
161 should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
162 context.format_file(path, &module, is_macro_def)?;
164 timer = timer.done_formatting();
166 should_emit_verbose(input_is_stdin, config, || {
168 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
169 timer.get_parse_time(),
170 timer.get_format_time(),
177 // Used for formatting files.
179 struct FormatContext<'a, T: FormatHandler> {
180 krate: &'a ast::Crate,
181 report: FormatReport,
182 parse_session: ParseSess,
187 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
188 fn ignore_file(&self, path: &FileName) -> bool {
189 self.parse_session.ignore_file(path)
192 // Formats a single file/module.
198 ) -> Result<(), ErrorKind> {
199 let snippet_provider = self.parse_session.snippet_provider(module.span);
200 let mut visitor = FmtVisitor::from_parse_sess(
206 visitor.skip_context.update_with_attrs(&self.krate.attrs);
207 visitor.is_macro_def = is_macro_def;
208 visitor.last_pos = snippet_provider.start_pos();
209 visitor.skip_empty_lines(snippet_provider.end_pos());
210 visitor.format_separate_mod(module, snippet_provider.end_pos());
214 count_newlines(&visitor.buffer),
215 "failed in format_file visitor.buffer:\n {:?}",
219 // For some reason, the source_map does not include terminating
220 // newlines so we must add one on for each file. This is sad.
221 source_file::append_newline(&mut visitor.buffer);
226 &visitor.skipped_range.borrow(),
232 self.config.newline_style(),
234 snippet_provider.entire_snippet(),
237 if visitor.macro_rewrite_failure {
238 self.report.add_macro_format_failure();
241 .add_non_formatted_ranges(visitor.skipped_range.borrow().clone());
243 self.handler.handle_formatted_file(
246 visitor.buffer.to_owned(),
252 // Handle the results of formatting.
253 trait FormatHandler {
254 fn handle_formatted_file(
256 parse_session: &ParseSess,
259 report: &mut FormatReport,
260 ) -> Result<(), ErrorKind>;
263 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
264 // Called for each formatted file.
265 fn handle_formatted_file(
267 parse_session: &ParseSess,
270 report: &mut FormatReport,
271 ) -> Result<(), ErrorKind> {
272 if let Some(ref mut out) = self.out {
273 match source_file::write_file(
279 self.config.newline_style(),
281 Ok(ref result) if result.has_diff => report.add_diff(),
283 // Create a new error with path_str to help users see which files failed
284 let err_msg = format!("{}: {}", path, e);
285 return Err(io::Error::new(e.kind(), err_msg).into());
291 self.source_file.push((path, result));
296 pub(crate) struct FormattingError {
297 pub(crate) line: usize,
298 pub(crate) kind: ErrorKind,
301 pub(crate) line_buffer: String,
304 impl FormattingError {
305 pub(crate) fn from_span(
307 parse_sess: &ParseSess,
309 ) -> FormattingError {
311 line: parse_sess.line_of_byte_pos(span.lo()),
312 is_comment: kind.is_comment(),
315 line_buffer: parse_sess.span_to_first_line_string(span),
319 pub(crate) fn is_internal(&self) -> bool {
321 ErrorKind::LineOverflow(..)
322 | ErrorKind::TrailingWhitespace
323 | ErrorKind::IoError(_)
324 | ErrorKind::ParseError
325 | ErrorKind::LostComment => true,
330 pub(crate) fn msg_suffix(&self) -> &str {
331 if self.is_comment || self.is_string {
332 "set `error_on_unformatted = false` to suppress \
333 the warning against comments or string literals\n"
340 pub(crate) fn format_len(&self) -> (usize, usize) {
342 ErrorKind::LineOverflow(found, max) => (max, found - max),
343 ErrorKind::TrailingWhitespace
344 | ErrorKind::DeprecatedAttr
346 | ErrorKind::LostComment => {
347 let trailing_ws_start = self
349 .rfind(|c: char| !c.is_whitespace())
354 self.line_buffer.len() - trailing_ws_start,
362 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
364 #[derive(Default, Debug, PartialEq)]
365 pub(crate) struct ReportedErrors {
366 // Encountered e.g., an IO error.
367 pub(crate) has_operational_errors: bool,
369 // Failed to reformat code because of parsing errors.
370 pub(crate) has_parsing_errors: bool,
372 // Code is valid, but it is impossible to format it properly.
373 pub(crate) has_formatting_errors: bool,
375 // Code contains macro call that was unable to format.
376 pub(crate) has_macro_format_failure: bool,
378 // Failed an opt-in checking.
379 pub(crate) has_check_errors: bool,
381 /// Formatted code differs from existing code (--check only).
382 pub(crate) has_diff: bool,
384 /// Formatted code missed something, like lost comments or extra trailing space
385 pub(crate) has_unformatted_code_errors: bool,
388 impl ReportedErrors {
389 /// Combine two summaries together.
390 pub(crate) fn add(&mut self, other: &ReportedErrors) {
391 self.has_operational_errors |= other.has_operational_errors;
392 self.has_parsing_errors |= other.has_parsing_errors;
393 self.has_formatting_errors |= other.has_formatting_errors;
394 self.has_macro_format_failure |= other.has_macro_format_failure;
395 self.has_check_errors |= other.has_check_errors;
396 self.has_diff |= other.has_diff;
397 self.has_unformatted_code_errors |= other.has_unformatted_code_errors;
401 #[derive(Clone, Copy, Debug)]
404 Initialized(Instant),
405 DoneParsing(Instant, Instant),
406 DoneFormatting(Instant, Instant, Instant),
410 fn start() -> Timer {
411 if cfg!(target_arch = "wasm32") {
414 Timer::Initialized(Instant::now())
417 fn done_parsing(self) -> Self {
419 Timer::Disabled => Timer::Disabled,
420 Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
421 _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
425 fn done_formatting(self) -> Self {
427 Timer::Disabled => Timer::Disabled,
428 Timer::DoneParsing(init_time, parse_time) => {
429 Timer::DoneFormatting(init_time, parse_time, Instant::now())
431 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
435 /// Returns the time it took to parse the source files in seconds.
436 fn get_parse_time(&self) -> f32 {
438 Timer::Disabled => panic!("this platform cannot time execution"),
439 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
440 // This should never underflow since `Instant::now()` guarantees monotonicity.
441 Self::duration_to_f32(parse_time.duration_since(init))
443 Timer::Initialized(..) => unreachable!(),
447 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
449 fn get_format_time(&self) -> f32 {
451 Timer::Disabled => panic!("this platform cannot time execution"),
452 Timer::DoneFormatting(_init, parse_time, format_time) => {
453 Self::duration_to_f32(format_time.duration_since(parse_time))
455 Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
459 fn duration_to_f32(d: Duration) -> f32 {
460 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
464 // Formatting done on a char by char or line by line basis.
465 // FIXME(#20): other stuff for parity with make tidy.
469 skipped_range: &[(usize, usize)],
471 report: &FormatReport,
473 let mut formatter = FormatLines::new(name, skipped_range, config);
474 formatter.iterate(text);
476 if formatter.newline_count > 1 {
477 debug!("track truncate: {} {}", text.len(), formatter.newline_count);
478 let line = text.len() - formatter.newline_count + 1;
482 report.append(name.clone(), formatter.errors);
485 struct FormatLines<'a> {
487 skipped_range: &'a [(usize, usize)],
488 last_was_space: bool,
491 newline_count: usize,
492 errors: Vec<FormattingError>,
494 current_line_contains_string_literal: bool,
499 impl<'a> FormatLines<'a> {
502 skipped_range: &'a [(usize, usize)],
504 ) -> FormatLines<'a> {
508 last_was_space: false,
513 line_buffer: String::with_capacity(config.max_width() * 2),
514 current_line_contains_string_literal: false,
515 format_line: config.file_lines().contains_line(name, 1),
520 // Iterate over the chars in the file map.
521 fn iterate(&mut self, text: &mut String) {
522 for (kind, c) in CharClasses::new(text.chars()) {
535 fn new_line(&mut self, kind: FullCodeCharKind) {
536 if self.format_line {
537 // Check for (and record) trailing whitespace.
538 if self.last_was_space {
539 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
540 && !self.is_skipped_line()
543 ErrorKind::TrailingWhitespace,
551 // Check for any line width errors we couldn't correct.
552 let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
553 if self.line_len > self.config.max_width()
554 && !self.is_skipped_line()
555 && self.should_report_error(kind, &error_kind)
557 let is_string = self.current_line_contains_string_literal;
558 self.push_err(error_kind, kind.is_comment(), is_string);
564 self.format_line = self
567 .contains_line(self.name, self.cur_line);
568 self.newline_count += 1;
569 self.last_was_space = false;
570 self.line_buffer.clear();
571 self.current_line_contains_string_literal = false;
574 fn char(&mut self, c: char, kind: FullCodeCharKind) {
575 self.newline_count = 0;
576 self.line_len += if c == '\t' {
577 self.config.tab_spaces()
581 self.last_was_space = c.is_whitespace();
582 self.line_buffer.push(c);
583 if kind.is_string() {
584 self.current_line_contains_string_literal = true;
588 fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
589 self.errors.push(FormattingError {
594 line_buffer: self.line_buffer.clone(),
598 fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
599 let allow_error_report = if char_kind.is_comment()
600 || self.current_line_contains_string_literal
601 || error_kind.is_comment()
603 self.config.error_on_unformatted()
609 ErrorKind::LineOverflow(..) => {
610 self.config.error_on_line_overflow() && allow_error_report
612 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
617 /// Returns `true` if the line with the given line number was skipped by `#[rustfmt::skip]`.
618 fn is_skipped_line(&self) -> bool {
621 .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
625 fn should_emit_verbose<F>(forbid_verbose_output: bool, config: &Config, f: F)
629 if config.verbose() == Verbosity::Verbose && !forbid_verbose_output {