1 // High level formatting functions.
3 use std::collections::HashMap;
4 use std::io::{self, Write};
5 use std::panic::{catch_unwind, AssertUnwindSafe};
7 use std::time::{Duration, Instant};
10 use syntax::errors::emitter::{ColorConfig, Emitter};
11 use syntax::errors::{DiagnosticBuilder, Handler};
12 use syntax::parse::{self, ParseSess};
13 use syntax::source_map::{FilePathMapping, SourceMap, Span, DUMMY_SP};
15 use crate::comment::{CharClasses, FullCodeCharKind};
16 use crate::config::{Config, FileName, Verbosity};
17 use crate::issues::BadIssueSeeker;
18 use crate::utils::{count_newlines, get_skip_macro_names};
19 use crate::visitor::{FmtVisitor, SnippetProvider};
20 use crate::{modules, source_file, ErrorKind, FormatReport, Input, Session};
22 // A map of the files of a crate, with their new content
23 pub(crate) type SourceFile = Vec<FileRecord>;
24 pub(crate) type FileRecord = (FileName, String);
26 impl<'b, T: Write + 'b> Session<'b, T> {
27 pub(crate) fn format_input_inner(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
28 if !self.config.version_meets_requirement() {
29 return Err(ErrorKind::VersionMismatch);
32 syntax::with_globals(|| {
33 syntax_pos::hygiene::set_default_edition(
34 self.config.edition().to_libsyntax_pos_edition(),
37 if self.config.disable_all_formatting() {
38 // When the input is from stdin, echo back the input.
39 if let Input::Text(ref buf) = input {
40 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
41 return Err(From::from(e));
44 return Ok(FormatReport::new());
47 let config = &self.config.clone();
48 let format_result = format_project(input, config, self);
50 format_result.map(|report| {
52 let new_errors = &report.internal.borrow().1;
54 self.errors.add(new_errors);
62 // Format an entire crate (or subset of the module tree).
63 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;
74 let source_map = Rc::new(SourceMap::new(FilePathMapping::empty()));
75 let mut parse_session = make_parse_sess(source_map.clone(), config);
76 let mut report = FormatReport::new();
77 let directory_ownership = input.to_directory_ownership();
78 let krate = match parse_crate(
86 // Surface parse error via Session (errors are merged there from report)
87 Err(ErrorKind::ParseError) => return Ok(report),
88 Err(e) => return Err(e),
90 timer = timer.done_parsing();
92 // Suppress error output if we have to do any further parsing.
93 let silent_emitter = silent_emitter();
94 parse_session.span_diagnostic = Handler::with_emitter(true, None, silent_emitter);
96 let mut context = FormatContext::new(&krate, report, parse_session, config, handler);
98 let files = modules::ModResolver::new(
99 context.parse_session.source_map(),
100 directory_ownership.unwrap_or(parse::DirectoryOwnership::UnownedViaMod(false)),
104 .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
105 for (path, (module, _)) in files {
106 if (config.skip_children() && path != main_file) || config.ignore().skip_file(&path) {
109 should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
110 let is_root = path == main_file;
111 context.format_file(path, module, is_root)?;
113 timer = timer.done_formatting();
115 should_emit_verbose(input_is_stdin, config, || {
117 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
118 timer.get_parse_time(),
119 timer.get_format_time(),
126 // Used for formatting files.
128 struct FormatContext<'a, T: FormatHandler> {
129 krate: &'a ast::Crate,
130 report: FormatReport,
131 parse_session: ParseSess,
136 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
137 // Formats a single file/module.
143 ) -> Result<(), ErrorKind> {
144 let source_file = self
147 .lookup_char_pos(module.inner.lo())
149 let big_snippet = source_file.src.as_ref().unwrap();
150 let snippet_provider = SnippetProvider::new(source_file.start_pos, big_snippet);
151 let mut visitor = FmtVisitor::from_source_map(
160 .append(&mut get_skip_macro_names(&self.krate.attrs));
162 // Format inner attributes if available.
163 if !self.krate.attrs.is_empty() && is_root {
164 visitor.skip_empty_lines(source_file.end_pos);
165 if visitor.visit_attrs(&self.krate.attrs, ast::AttrStyle::Inner) {
166 visitor.push_rewrite(module.inner, None);
168 visitor.format_separate_mod(module, &*source_file);
171 visitor.last_pos = source_file.start_pos;
172 visitor.skip_empty_lines(source_file.end_pos);
173 visitor.format_separate_mod(module, &*source_file);
176 debug_assert_eq!(visitor.line_number, count_newlines(&visitor.buffer));
178 // For some reason, the source_map does not include terminating
179 // newlines so we must add one on for each file. This is sad.
180 source_file::append_newline(&mut visitor.buffer);
185 &visitor.skipped_range,
191 .apply(&mut visitor.buffer, &big_snippet);
193 if visitor.macro_rewrite_failure {
194 self.report.add_macro_format_failure();
197 .add_non_formatted_ranges(visitor.skipped_range.clone());
199 self.handler.handle_formatted_file(
200 self.parse_session.source_map(),
202 visitor.buffer.to_owned(),
208 // Handle the results of formatting.
209 trait FormatHandler {
210 fn handle_formatted_file(
212 source_map: &SourceMap,
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 source_map: &SourceMap,
226 report: &mut FormatReport,
227 ) -> Result<(), ErrorKind> {
228 if let Some(ref mut out) = self.out {
229 match source_file::write_file(Some(source_map), &path, &result, out, &self.config) {
230 Ok(has_diff) if has_diff => report.add_diff(),
232 // Create a new error with path_str to help users see which files failed
233 let err_msg = format!("{}: {}", path, e);
234 return Err(io::Error::new(e.kind(), err_msg).into());
240 self.source_file.push((path, result));
245 pub(crate) struct FormattingError {
246 pub(crate) line: usize,
247 pub(crate) kind: ErrorKind,
250 pub(crate) line_buffer: String,
253 impl FormattingError {
254 pub(crate) fn from_span(
256 source_map: &SourceMap,
258 ) -> FormattingError {
260 line: source_map.lookup_char_pos(span.lo()).line,
261 is_comment: kind.is_comment(),
264 line_buffer: source_map
269 .get_line(fl.lines[0].line_index)
270 .map(|l| l.into_owned())
272 .unwrap_or_else(String::new),
276 pub(crate) fn msg_prefix(&self) -> &str {
278 ErrorKind::LineOverflow(..)
279 | ErrorKind::TrailingWhitespace
280 | ErrorKind::IoError(_)
281 | ErrorKind::ParseError
282 | ErrorKind::LostComment => "internal error:",
283 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
284 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
288 pub(crate) fn msg_suffix(&self) -> &str {
289 if self.is_comment || self.is_string {
290 "set `error_on_unformatted = false` to suppress \
291 the warning against comments or string literals\n"
298 pub(crate) fn format_len(&self) -> (usize, usize) {
300 ErrorKind::LineOverflow(found, max) => (max, found - max),
301 ErrorKind::TrailingWhitespace
302 | ErrorKind::DeprecatedAttr
303 | ErrorKind::BadIssue(_)
305 | ErrorKind::LostComment => {
306 let trailing_ws_start = self
308 .rfind(|c: char| !c.is_whitespace())
313 self.line_buffer.len() - trailing_ws_start,
321 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
323 #[derive(Default, Debug, PartialEq)]
324 pub(crate) struct ReportedErrors {
325 // Encountered e.g., an IO error.
326 pub(crate) has_operational_errors: bool,
328 // Failed to reformat code because of parsing errors.
329 pub(crate) has_parsing_errors: bool,
331 // Code is valid, but it is impossible to format it properly.
332 pub(crate) has_formatting_errors: bool,
334 // Code contains macro call that was unable to format.
335 pub(crate) has_macro_format_failure: bool,
337 // Failed a check, such as the license check or other opt-in checking.
338 pub(crate) has_check_errors: bool,
340 /// Formatted code differs from existing code (--check only).
341 pub(crate) has_diff: bool,
344 impl ReportedErrors {
345 /// Combine two summaries together.
346 pub fn add(&mut self, other: &ReportedErrors) {
347 self.has_operational_errors |= other.has_operational_errors;
348 self.has_parsing_errors |= other.has_parsing_errors;
349 self.has_formatting_errors |= other.has_formatting_errors;
350 self.has_macro_format_failure |= other.has_macro_format_failure;
351 self.has_check_errors |= other.has_check_errors;
352 self.has_diff |= other.has_diff;
356 #[derive(Clone, Copy, Debug)]
359 Initialized(Instant),
360 DoneParsing(Instant, Instant),
361 DoneFormatting(Instant, Instant, Instant),
365 fn start() -> Timer {
366 if cfg!(target_arch = "wasm32") {
369 Timer::Initialized(Instant::now())
372 fn done_parsing(self) -> Self {
374 Timer::Disabled => Timer::Disabled,
375 Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
376 _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
380 fn done_formatting(self) -> Self {
382 Timer::Disabled => Timer::Disabled,
383 Timer::DoneParsing(init_time, parse_time) => {
384 Timer::DoneFormatting(init_time, parse_time, Instant::now())
386 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
390 /// Returns the time it took to parse the source files in seconds.
391 fn get_parse_time(&self) -> f32 {
393 Timer::Disabled => panic!("this platform cannot time execution"),
394 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
395 // This should never underflow since `Instant::now()` guarantees monotonicity.
396 Self::duration_to_f32(parse_time.duration_since(init))
398 Timer::Initialized(..) => unreachable!(),
402 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
404 fn get_format_time(&self) -> f32 {
406 Timer::Disabled => panic!("this platform cannot time execution"),
407 Timer::DoneFormatting(_init, parse_time, format_time) => {
408 Self::duration_to_f32(format_time.duration_since(parse_time))
410 Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
414 fn duration_to_f32(d: Duration) -> f32 {
415 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
419 // Formatting done on a char by char or line by line basis.
420 // FIXME(#20): other stuff for parity with make tidy.
424 skipped_range: &[(usize, usize)],
426 report: &FormatReport,
428 let mut formatter = FormatLines::new(name, skipped_range, config);
429 formatter.check_license(text);
430 formatter.iterate(text);
432 if formatter.newline_count > 1 {
433 debug!("track truncate: {} {}", text.len(), formatter.newline_count);
434 let line = text.len() - formatter.newline_count + 1;
438 report.append(name.clone(), formatter.errors);
441 struct FormatLines<'a> {
443 skipped_range: &'a [(usize, usize)],
444 last_was_space: bool,
447 newline_count: usize,
448 errors: Vec<FormattingError>,
449 issue_seeker: BadIssueSeeker,
451 // `true` if the current line contains a string literal.
454 allow_issue_seek: bool,
458 impl<'a> FormatLines<'a> {
461 skipped_range: &'a [(usize, usize)],
463 ) -> FormatLines<'a> {
464 let issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
468 last_was_space: false,
473 allow_issue_seek: !issue_seeker.is_disabled(),
475 line_buffer: String::with_capacity(config.max_width() * 2),
477 format_line: config.file_lines().contains_line(name, 1),
482 fn check_license(&mut self, text: &mut String) {
483 if let Some(ref license_template) = self.config.license_template {
484 if !license_template.is_match(text) {
485 self.errors.push(FormattingError {
487 kind: ErrorKind::LicenseCheck,
490 line_buffer: String::new(),
496 // Iterate over the chars in the file map.
497 fn iterate(&mut self, text: &mut String) {
498 for (kind, c) in CharClasses::new(text.chars()) {
503 if self.allow_issue_seek && self.format_line {
504 // Add warnings for bad todos/ fixmes
505 if let Some(issue) = self.issue_seeker.inspect(c) {
506 self.push_err(ErrorKind::BadIssue(issue), false, false);
518 fn new_line(&mut self, kind: FullCodeCharKind) {
519 if self.format_line {
520 // Check for (and record) trailing whitespace.
521 if self.last_was_space {
522 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
523 && !self.is_skipped_line()
526 ErrorKind::TrailingWhitespace,
534 // Check for any line width errors we couldn't correct.
535 let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
536 if self.line_len > self.config.max_width()
537 && !self.is_skipped_line()
538 && self.should_report_error(kind, &error_kind)
540 let is_string = self.is_string;
541 self.push_err(error_kind, kind.is_comment(), is_string);
547 self.format_line = self
550 .contains_line(self.name, self.cur_line);
551 self.newline_count += 1;
552 self.last_was_space = false;
553 self.line_buffer.clear();
554 self.is_string = false;
557 fn char(&mut self, c: char, kind: FullCodeCharKind) {
558 self.newline_count = 0;
559 self.line_len += if c == '\t' {
560 self.config.tab_spaces()
564 self.last_was_space = c.is_whitespace();
565 self.line_buffer.push(c);
566 if kind.is_string() {
567 self.is_string = true;
571 fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
572 self.errors.push(FormattingError {
577 line_buffer: self.line_buffer.clone(),
581 fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
582 let allow_error_report =
583 if char_kind.is_comment() || self.is_string || error_kind.is_comment() {
584 self.config.error_on_unformatted()
590 ErrorKind::LineOverflow(..) => {
591 self.config.error_on_line_overflow() && allow_error_report
593 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
598 /// Returns `true` if the line with the given line number was skipped by `#[rustfmt::skip]`.
599 fn is_skipped_line(&self) -> bool {
602 .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
608 parse_session: &ParseSess,
610 report: &mut FormatReport,
611 directory_ownership: Option<parse::DirectoryOwnership>,
612 ) -> Result<ast::Crate, ErrorKind> {
613 let input_is_stdin = input.is_text();
615 let parser = match input {
616 Input::File(ref file) => {
617 // Use `new_sub_parser_from_file` when we the input is a submodule.
618 Ok(if let Some(dir_own) = directory_ownership {
619 parse::new_sub_parser_from_file(parse_session, file, dir_own, None, DUMMY_SP)
621 parse::new_parser_from_file(parse_session, file)
624 Input::Text(text) => parse::maybe_new_parser_from_source_str(
626 syntax::source_map::FileName::Custom("stdin".to_owned()),
630 parser.recurse_into_file_modules = false;
636 .map(|d| DiagnosticBuilder::new_diagnostic(&parse_session.span_diagnostic, d))
641 let result = match parser {
643 parser.cfg_mods = false;
644 if config.skip_children() {
645 parser.recurse_into_file_modules = false;
648 let mut parser = AssertUnwindSafe(parser);
649 catch_unwind(move || parser.0.parse_crate_mod().map_err(|d| vec![d]))
651 Err(db) => Ok(Err(db)),
656 if !parse_session.span_diagnostic.has_errors() {
660 Ok(Err(mut diagnostics)) => diagnostics.iter_mut().for_each(|d| d.emit()),
662 // Note that if you see this message and want more information,
663 // then run the `parse_crate_mod` function above without
664 // `catch_unwind` so rustfmt panics and you can get a backtrace.
665 should_emit_verbose(input_is_stdin, config, || {
666 println!("The Rust parser panicked")
671 report.add_parsing_error();
672 Err(ErrorKind::ParseError)
675 /// Emitter which discards every error.
676 struct SilentEmitter;
678 impl Emitter for SilentEmitter {
679 fn emit(&mut self, _db: &DiagnosticBuilder<'_>) {}
682 fn silent_emitter() -> Box<SilentEmitter> {
683 Box::new(SilentEmitter {})
686 fn make_parse_sess(source_map: Rc<SourceMap>, config: &Config) -> ParseSess {
687 let tty_handler = if config.hide_parse_errors() {
688 let silent_emitter = silent_emitter();
689 Handler::with_emitter(true, None, silent_emitter)
691 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
692 let color_cfg = if supports_color {
697 Handler::with_tty_emitter(color_cfg, true, None, Some(source_map.clone()))
700 ParseSess::with_span_handler(tty_handler, source_map)
703 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
707 if config.verbose() == Verbosity::Verbose && !is_stdin {