1 // High level formatting functions.
3 use std::collections::HashMap;
4 use std::io::{self, Write};
6 use std::time::{Duration, Instant};
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::modules::Module;
16 use crate::parse::parser::{DirectoryOwnership, Parser, ParserError};
17 use crate::parse::session::ParseSess;
18 use crate::utils::{contains_skip, 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.
43 Input::Text(ref buf) => echo_back_stdin(buf),
44 _ => Ok(FormatReport::new()),
48 let config = &self.config.clone();
49 let format_result = format_project(input, config, self, is_macro_def);
51 format_result.map(|report| {
52 self.errors.add(&report.internal.borrow().1);
59 /// Determine if a module should be skipped. True if the module should be skipped, false otherwise.
60 fn should_skip_module<T: FormatHandler>(
62 context: &FormatContext<'_, T>,
68 if contains_skip(module.attrs()) {
72 if config.skip_children() && path != main_file {
76 if !input_is_stdin && context.ignore_file(path) {
80 // FIXME(calebcartwright) - we need to determine how we'll handle the
81 // `format_generated_files` option with stdin based input.
82 if !input_is_stdin && !config.format_generated_files() {
83 let source_file = context.parse_session.span_to_file_contents(module.span);
84 let src = source_file.src.as_ref().expect("SourceFile without src");
86 if is_generated_file(src) {
94 fn echo_back_stdin(input: &str) -> Result<FormatReport, ErrorKind> {
95 if let Err(e) = io::stdout().write_all(input.as_bytes()) {
96 return Err(From::from(e));
98 Ok(FormatReport::new())
101 // Format an entire crate (or subset of the module tree).
102 fn format_project<T: FormatHandler>(
107 ) -> Result<FormatReport, ErrorKind> {
108 let mut timer = Timer::start();
110 let main_file = input.file_name();
111 let input_is_stdin = main_file == FileName::Stdin;
113 let parse_session = ParseSess::new(config)?;
114 if config.skip_children() && parse_session.ignore_file(&main_file) {
115 return Ok(FormatReport::new());
119 let mut report = FormatReport::new();
120 let directory_ownership = input.to_directory_ownership();
121 let krate = match Parser::parse_crate(input, &parse_session) {
123 // Surface parse error via Session (errors are merged there from report)
125 let forbid_verbose = input_is_stdin || e != ParserError::ParsePanicError;
126 should_emit_verbose(forbid_verbose, config, || {
127 eprintln!("The Rust parser panicked");
129 report.add_parsing_error();
134 let mut context = FormatContext::new(&krate, report, parse_session, config, handler);
135 let files = modules::ModResolver::new(
136 &context.parse_session,
137 directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaBlock),
138 !input_is_stdin && !config.skip_children(),
140 .visit_crate(&krate)?
142 .filter(|(path, module)| {
144 || !should_skip_module(config, &context, input_is_stdin, &main_file, path, module)
146 .collect::<Vec<_>>();
148 timer = timer.done_parsing();
150 // Suppress error output if we have to do any further parsing.
151 context.parse_session.set_silent_emitter();
153 for (path, module) in files {
154 if input_is_stdin && contains_skip(module.attrs()) {
155 return echo_back_stdin(
158 .snippet_provider(module.span)
162 should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
163 context.format_file(path, &module, is_macro_def)?;
165 timer = timer.done_formatting();
167 should_emit_verbose(input_is_stdin, config, || {
169 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
170 timer.get_parse_time(),
171 timer.get_format_time(),
178 // Used for formatting files.
180 struct FormatContext<'a, T: FormatHandler> {
181 krate: &'a ast::Crate,
182 report: FormatReport,
183 parse_session: ParseSess,
188 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
189 fn ignore_file(&self, path: &FileName) -> bool {
190 self.parse_session.ignore_file(path)
193 // Formats a single file/module.
199 ) -> Result<(), ErrorKind> {
200 let snippet_provider = self.parse_session.snippet_provider(module.span);
201 let mut visitor = FmtVisitor::from_parse_sess(
208 visitor.skip_context.update_with_attrs(&self.krate.attrs);
209 visitor.is_macro_def = is_macro_def;
210 visitor.last_pos = snippet_provider.start_pos();
211 visitor.skip_empty_lines(snippet_provider.end_pos());
212 visitor.format_separate_mod(module, snippet_provider.end_pos());
216 count_newlines(&visitor.buffer),
217 "failed in format_file visitor.buffer:\n {:?}",
221 // For some reason, the source_map does not include terminating
222 // newlines so we must add one on for each file. This is sad.
223 source_file::append_newline(&mut visitor.buffer);
228 &visitor.skipped_range.borrow(),
234 self.config.newline_style(),
236 snippet_provider.entire_snippet(),
239 if visitor.macro_rewrite_failure {
240 self.report.add_macro_format_failure();
243 .add_non_formatted_ranges(visitor.skipped_range.borrow().clone());
245 self.handler.handle_formatted_file(
248 visitor.buffer.to_owned(),
254 // Handle the results of formatting.
255 trait FormatHandler {
256 fn handle_formatted_file(
258 parse_session: &ParseSess,
261 report: &mut FormatReport,
262 ) -> Result<(), ErrorKind>;
265 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
266 // Called for each formatted file.
267 fn handle_formatted_file(
269 parse_session: &ParseSess,
272 report: &mut FormatReport,
273 ) -> Result<(), ErrorKind> {
274 if let Some(ref mut out) = self.out {
275 match source_file::write_file(
281 self.config.newline_style(),
283 Ok(ref result) if result.has_diff => report.add_diff(),
285 // Create a new error with path_str to help users see which files failed
286 let err_msg = format!("{}: {}", path, e);
287 return Err(io::Error::new(e.kind(), err_msg).into());
293 self.source_file.push((path, result));
298 pub(crate) struct FormattingError {
299 pub(crate) line: usize,
300 pub(crate) kind: ErrorKind,
303 pub(crate) line_buffer: String,
306 impl FormattingError {
307 pub(crate) fn from_span(
309 parse_sess: &ParseSess,
311 ) -> FormattingError {
313 line: parse_sess.line_of_byte_pos(span.lo()),
314 is_comment: kind.is_comment(),
317 line_buffer: parse_sess.span_to_first_line_string(span),
321 pub(crate) fn is_internal(&self) -> bool {
323 ErrorKind::LineOverflow(..)
324 | ErrorKind::TrailingWhitespace
325 | ErrorKind::IoError(_)
326 | ErrorKind::ParseError
327 | ErrorKind::LostComment => true,
332 pub(crate) fn msg_suffix(&self) -> &str {
333 if self.is_comment || self.is_string {
334 "set `error_on_unformatted = false` to suppress \
335 the warning against comments or string literals\n"
342 pub(crate) fn format_len(&self) -> (usize, usize) {
344 ErrorKind::LineOverflow(found, max) => (max, found - max),
345 ErrorKind::TrailingWhitespace
346 | ErrorKind::DeprecatedAttr
348 | ErrorKind::LostComment => {
349 let trailing_ws_start = self
351 .rfind(|c: char| !c.is_whitespace())
356 self.line_buffer.len() - trailing_ws_start,
364 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
366 #[derive(Default, Debug, PartialEq)]
367 pub(crate) struct ReportedErrors {
368 // Encountered e.g., an IO error.
369 pub(crate) has_operational_errors: bool,
371 // Failed to reformat code because of parsing errors.
372 pub(crate) has_parsing_errors: bool,
374 // Code is valid, but it is impossible to format it properly.
375 pub(crate) has_formatting_errors: bool,
377 // Code contains macro call that was unable to format.
378 pub(crate) has_macro_format_failure: bool,
380 // Failed an opt-in checking.
381 pub(crate) has_check_errors: bool,
383 /// Formatted code differs from existing code (--check only).
384 pub(crate) has_diff: bool,
386 /// Formatted code missed something, like lost comments or extra trailing space
387 pub(crate) has_unformatted_code_errors: bool,
390 impl ReportedErrors {
391 /// Combine two summaries together.
392 pub(crate) fn add(&mut self, other: &ReportedErrors) {
393 self.has_operational_errors |= other.has_operational_errors;
394 self.has_parsing_errors |= other.has_parsing_errors;
395 self.has_formatting_errors |= other.has_formatting_errors;
396 self.has_macro_format_failure |= other.has_macro_format_failure;
397 self.has_check_errors |= other.has_check_errors;
398 self.has_diff |= other.has_diff;
399 self.has_unformatted_code_errors |= other.has_unformatted_code_errors;
403 #[derive(Clone, Copy, Debug)]
406 Initialized(Instant),
407 DoneParsing(Instant, Instant),
408 DoneFormatting(Instant, Instant, Instant),
412 fn start() -> Timer {
413 if cfg!(target_arch = "wasm32") {
416 Timer::Initialized(Instant::now())
419 fn done_parsing(self) -> Self {
421 Timer::Disabled => Timer::Disabled,
422 Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
423 _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
427 fn done_formatting(self) -> Self {
429 Timer::Disabled => Timer::Disabled,
430 Timer::DoneParsing(init_time, parse_time) => {
431 Timer::DoneFormatting(init_time, parse_time, Instant::now())
433 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
437 /// Returns the time it took to parse the source files in seconds.
438 fn get_parse_time(&self) -> f32 {
440 Timer::Disabled => panic!("this platform cannot time execution"),
441 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
442 // This should never underflow since `Instant::now()` guarantees monotonicity.
443 Self::duration_to_f32(parse_time.duration_since(init))
445 Timer::Initialized(..) => unreachable!(),
449 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
451 fn get_format_time(&self) -> f32 {
453 Timer::Disabled => panic!("this platform cannot time execution"),
454 Timer::DoneFormatting(_init, parse_time, format_time) => {
455 Self::duration_to_f32(format_time.duration_since(parse_time))
457 Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
461 fn duration_to_f32(d: Duration) -> f32 {
462 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
466 // Formatting done on a char by char or line by line basis.
467 // FIXME(#20): other stuff for parity with make tidy.
471 skipped_range: &[(usize, usize)],
473 report: &FormatReport,
475 let mut formatter = FormatLines::new(name, skipped_range, config);
476 formatter.iterate(text);
478 if formatter.newline_count > 1 {
479 debug!("track truncate: {} {}", text.len(), formatter.newline_count);
480 let line = text.len() - formatter.newline_count + 1;
484 report.append(name.clone(), formatter.errors);
487 struct FormatLines<'a> {
489 skipped_range: &'a [(usize, usize)],
490 last_was_space: bool,
493 newline_count: usize,
494 errors: Vec<FormattingError>,
496 current_line_contains_string_literal: bool,
501 impl<'a> FormatLines<'a> {
504 skipped_range: &'a [(usize, usize)],
506 ) -> FormatLines<'a> {
510 last_was_space: false,
515 line_buffer: String::with_capacity(config.max_width() * 2),
516 current_line_contains_string_literal: false,
517 format_line: config.file_lines().contains_line(name, 1),
522 // Iterate over the chars in the file map.
523 fn iterate(&mut self, text: &mut String) {
524 for (kind, c) in CharClasses::new(text.chars()) {
537 fn new_line(&mut self, kind: FullCodeCharKind) {
538 if self.format_line {
539 // Check for (and record) trailing whitespace.
540 if self.last_was_space {
541 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
542 && !self.is_skipped_line()
545 ErrorKind::TrailingWhitespace,
553 // Check for any line width errors we couldn't correct.
554 let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
555 if self.line_len > self.config.max_width()
556 && !self.is_skipped_line()
557 && self.should_report_error(kind, &error_kind)
559 let is_string = self.current_line_contains_string_literal;
560 self.push_err(error_kind, kind.is_comment(), is_string);
566 self.format_line = self
569 .contains_line(self.name, self.cur_line);
570 self.newline_count += 1;
571 self.last_was_space = false;
572 self.line_buffer.clear();
573 self.current_line_contains_string_literal = false;
576 fn char(&mut self, c: char, kind: FullCodeCharKind) {
577 self.newline_count = 0;
578 self.line_len += if c == '\t' {
579 self.config.tab_spaces()
583 self.last_was_space = c.is_whitespace();
584 self.line_buffer.push(c);
585 if kind.is_string() {
586 self.current_line_contains_string_literal = true;
590 fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
591 self.errors.push(FormattingError {
596 line_buffer: self.line_buffer.clone(),
600 fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
601 let allow_error_report = if char_kind.is_comment()
602 || self.current_line_contains_string_literal
603 || error_kind.is_comment()
605 self.config.error_on_unformatted()
611 ErrorKind::LineOverflow(..) => {
612 self.config.error_on_line_overflow() && allow_error_report
614 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
619 /// Returns `true` if the line with the given line number was skipped by `#[rustfmt::skip]`.
620 fn is_skipped_line(&self) -> bool {
623 .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
627 fn should_emit_verbose<F>(forbid_verbose_output: bool, config: &Config, f: F)
631 if config.verbose() == Verbosity::Verbose && !forbid_verbose_output {