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, EmitterWriter};
11 use syntax::errors::{DiagnosticBuilder, Handler};
12 use syntax::parse::{self, ParseSess};
13 use syntax::source_map::{FilePathMapping, SourceMap, Span};
15 use comment::{CharClasses, FullCodeCharKind};
16 use config::{Config, FileName, Verbosity};
17 use issues::BadIssueSeeker;
18 use visitor::{FmtVisitor, SnippetProvider};
19 use {modules, source_file, ErrorKind, FormatReport, Input, Session};
21 // A map of the files of a crate, with their new content
22 pub(crate) type SourceFile = Vec<FileRecord>;
23 pub(crate) type FileRecord = (FileName, String);
25 impl<'b, T: Write + 'b> Session<'b, T> {
26 pub(crate) fn format_input_inner(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
27 if !self.config.version_meets_requirement() {
28 return Err(ErrorKind::VersionMismatch);
31 syntax::with_globals(|| {
32 syntax_pos::hygiene::set_default_edition(
33 self.config.edition().to_libsyntax_pos_edition(),
36 if self.config.disable_all_formatting() {
37 // When the input is from stdin, echo back the input.
38 if let Input::Text(ref buf) = input {
39 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
40 return Err(From::from(e));
43 return Ok(FormatReport::new());
46 let config = &self.config.clone();
47 let format_result = format_project(input, config, self);
49 format_result.map(|report| {
51 let new_errors = &report.internal.borrow().1;
53 self.errors.add(new_errors);
61 // Format an entire crate (or subset of the module tree).
62 fn format_project<T: FormatHandler>(
66 ) -> Result<FormatReport, ErrorKind> {
67 let mut timer = Timer::start();
69 let main_file = input.file_name();
70 let input_is_stdin = main_file == FileName::Stdin;
73 let source_map = Rc::new(SourceMap::new(FilePathMapping::empty()));
74 let mut parse_session = make_parse_sess(source_map.clone(), config);
75 let mut report = FormatReport::new();
76 let krate = match parse_crate(input, &parse_session, config, &mut report) {
78 // Surface parse error via Session (errors are merged there from report)
79 Err(ErrorKind::ParseError) => return Ok(report),
80 Err(e) => return Err(e),
82 timer = timer.done_parsing();
84 // Suppress error output if we have to do any further parsing.
85 let silent_emitter = silent_emitter(source_map);
86 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
88 let mut context = FormatContext::new(&krate, report, parse_session, config, handler);
90 let files = modules::list_files(&krate, context.parse_session.source_map())?;
91 for (path, module) in files {
92 if (config.skip_children() && path != main_file) || config.ignore().skip_file(&path) {
95 should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
96 let is_root = path == main_file;
97 context.format_file(path, module, is_root)?;
99 timer = timer.done_formatting();
101 should_emit_verbose(input_is_stdin, config, || {
103 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
104 timer.get_parse_time(),
105 timer.get_format_time(),
112 // Used for formatting files.
114 struct FormatContext<'a, T: FormatHandler + 'a> {
115 krate: &'a ast::Crate,
116 report: FormatReport,
117 parse_session: ParseSess,
122 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
123 // Formats a single file/module.
129 ) -> Result<(), ErrorKind> {
130 let source_file = self
133 .lookup_char_pos(module.inner.lo())
135 let big_snippet = source_file.src.as_ref().unwrap();
136 let snippet_provider = SnippetProvider::new(source_file.start_pos, big_snippet);
137 let mut visitor = FmtVisitor::from_source_map(
144 // Format inner attributes if available.
145 if !self.krate.attrs.is_empty() && is_root {
146 visitor.skip_empty_lines(source_file.end_pos);
147 if visitor.visit_attrs(&self.krate.attrs, ast::AttrStyle::Inner) {
148 visitor.push_rewrite(module.inner, None);
150 visitor.format_separate_mod(module, &*source_file);
153 visitor.last_pos = source_file.start_pos;
154 visitor.skip_empty_lines(source_file.end_pos);
155 visitor.format_separate_mod(module, &*source_file);
160 ::utils::count_newlines(&visitor.buffer)
163 // For some reason, the source_map does not include terminating
164 // newlines so we must add one on for each file. This is sad.
165 source_file::append_newline(&mut visitor.buffer);
170 &visitor.skipped_range,
176 .apply(&mut visitor.buffer, &big_snippet);
178 if visitor.macro_rewrite_failure {
179 self.report.add_macro_format_failure();
182 .add_non_formatted_ranges(visitor.skipped_range.clone());
185 .handle_formatted_file(path, visitor.buffer.to_owned(), &mut self.report)
189 // Handle the results of formatting.
190 trait FormatHandler {
191 fn handle_formatted_file(
195 report: &mut FormatReport,
196 ) -> Result<(), ErrorKind>;
199 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
200 // Called for each formatted file.
201 fn handle_formatted_file(
205 report: &mut FormatReport,
206 ) -> Result<(), ErrorKind> {
207 if let Some(ref mut out) = self.out {
208 match source_file::write_file(&result, &path, out, &self.config) {
209 Ok(b) if b => report.add_diff(),
211 // Create a new error with path_str to help users see which files failed
212 let err_msg = format!("{}: {}", path, e);
213 return Err(io::Error::new(e.kind(), err_msg).into());
219 self.source_file.push((path, result));
224 pub(crate) struct FormattingError {
225 pub(crate) line: usize,
226 pub(crate) kind: ErrorKind,
229 pub(crate) line_buffer: String,
232 impl FormattingError {
233 pub(crate) fn from_span(
235 source_map: &SourceMap,
237 ) -> FormattingError {
239 line: source_map.lookup_char_pos(span.lo()).line,
240 is_comment: kind.is_comment(),
243 line_buffer: source_map
248 .get_line(fl.lines[0].line_index)
249 .map(|l| l.into_owned())
251 .unwrap_or_else(String::new),
255 pub(crate) fn msg_prefix(&self) -> &str {
257 ErrorKind::LineOverflow(..)
258 | ErrorKind::TrailingWhitespace
259 | ErrorKind::IoError(_)
260 | ErrorKind::ParseError
261 | ErrorKind::LostComment => "internal error:",
262 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
263 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
267 pub(crate) fn msg_suffix(&self) -> &str {
268 if self.is_comment || self.is_string {
269 "set `error_on_unformatted = false` to suppress \
270 the warning against comments or string literals\n"
277 pub(crate) fn format_len(&self) -> (usize, usize) {
279 ErrorKind::LineOverflow(found, max) => (max, found - max),
280 ErrorKind::TrailingWhitespace
281 | ErrorKind::DeprecatedAttr
282 | ErrorKind::BadIssue(_)
284 | ErrorKind::LostComment => {
285 let trailing_ws_start = self
287 .rfind(|c: char| !c.is_whitespace())
292 self.line_buffer.len() - trailing_ws_start,
300 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
302 #[derive(Default, Debug)]
303 pub(crate) struct ReportedErrors {
304 // Encountered e.g. an IO error.
305 pub(crate) has_operational_errors: bool,
307 // Failed to reformat code because of parsing errors.
308 pub(crate) has_parsing_errors: bool,
310 // Code is valid, but it is impossible to format it properly.
311 pub(crate) has_formatting_errors: bool,
313 // Code contains macro call that was unable to format.
314 pub(crate) has_macro_format_failure: bool,
316 // Failed a check, such as the license check or other opt-in checking.
317 pub(crate) has_check_errors: bool,
319 /// Formatted code differs from existing code (--check only).
320 pub(crate) has_diff: bool,
323 impl ReportedErrors {
324 /// Combine two summaries together.
325 pub fn add(&mut self, other: &ReportedErrors) {
326 self.has_operational_errors |= other.has_operational_errors;
327 self.has_parsing_errors |= other.has_parsing_errors;
328 self.has_formatting_errors |= other.has_formatting_errors;
329 self.has_macro_format_failure |= other.has_macro_format_failure;
330 self.has_check_errors |= other.has_check_errors;
331 self.has_diff |= other.has_diff;
335 /// A single span of changed lines, with 0 or more removed lines
336 /// and a vector of 0 or more inserted lines.
337 #[derive(Debug, PartialEq, Eq)]
338 pub(crate) struct ModifiedChunk {
339 /// The first to be removed from the original text
340 pub line_number_orig: u32,
341 /// The number of lines which have been replaced
342 pub lines_removed: u32,
344 pub lines: Vec<String>,
347 /// Set of changed sections of a file.
348 #[derive(Debug, PartialEq, Eq)]
349 pub(crate) struct ModifiedLines {
350 /// The set of changed chunks.
351 pub chunks: Vec<ModifiedChunk>,
354 #[derive(Clone, Copy, Debug)]
357 Initialized(Instant),
358 DoneParsing(Instant, Instant),
359 DoneFormatting(Instant, Instant, Instant),
363 fn start() -> Timer {
364 if cfg!(target_arch = "wasm32") {
367 Timer::Initialized(Instant::now())
370 fn done_parsing(self) -> Self {
372 Timer::Disabled => Timer::Disabled,
373 Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
374 _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
378 fn done_formatting(self) -> Self {
380 Timer::Disabled => Timer::Disabled,
381 Timer::DoneParsing(init_time, parse_time) => {
382 Timer::DoneFormatting(init_time, parse_time, Instant::now())
384 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
388 /// Returns the time it took to parse the source files in seconds.
389 fn get_parse_time(&self) -> f32 {
391 Timer::Disabled => panic!("this platform cannot time execution"),
392 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
393 // This should never underflow since `Instant::now()` guarantees monotonicity.
394 Self::duration_to_f32(parse_time.duration_since(init))
396 Timer::Initialized(..) => unreachable!(),
400 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
402 fn get_format_time(&self) -> f32 {
404 Timer::Disabled => panic!("this platform cannot time execution"),
405 Timer::DoneFormatting(_init, parse_time, format_time) => {
406 Self::duration_to_f32(format_time.duration_since(parse_time))
408 Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
412 fn duration_to_f32(d: Duration) -> f32 {
413 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
417 // Formatting done on a char by char or line by line basis.
418 // FIXME(#20) other stuff for parity with make tidy
422 skipped_range: &[(usize, usize)],
424 report: &FormatReport,
426 let mut formatter = FormatLines::new(name, skipped_range, config);
427 formatter.check_license(text);
428 formatter.iterate(text);
430 if formatter.newline_count > 1 {
431 debug!("track truncate: {} {}", text.len(), formatter.newline_count);
432 let line = text.len() - formatter.newline_count + 1;
436 report.append(name.clone(), formatter.errors);
439 struct FormatLines<'a> {
441 skipped_range: &'a [(usize, usize)],
442 last_was_space: bool,
445 newline_count: usize,
446 errors: Vec<FormattingError>,
447 issue_seeker: BadIssueSeeker,
449 // true if the current line contains a string literal.
452 allow_issue_seek: bool,
456 impl<'a> FormatLines<'a> {
459 skipped_range: &'a [(usize, usize)],
461 ) -> FormatLines<'a> {
462 let issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
466 last_was_space: false,
471 allow_issue_seek: !issue_seeker.is_disabled(),
473 line_buffer: String::with_capacity(config.max_width() * 2),
475 format_line: config.file_lines().contains_line(name, 1),
480 fn check_license(&mut self, text: &mut String) {
481 if let Some(ref license_template) = self.config.license_template {
482 if !license_template.is_match(text) {
483 self.errors.push(FormattingError {
485 kind: ErrorKind::LicenseCheck,
488 line_buffer: String::new(),
494 // Iterate over the chars in the file map.
495 fn iterate(&mut self, text: &mut String) {
496 for (kind, c) in CharClasses::new(text.chars()) {
501 if self.allow_issue_seek && self.format_line {
502 // Add warnings for bad todos/ fixmes
503 if let Some(issue) = self.issue_seeker.inspect(c) {
504 self.push_err(ErrorKind::BadIssue(issue), false, false);
516 fn new_line(&mut self, kind: FullCodeCharKind) {
517 if self.format_line {
518 // Check for (and record) trailing whitespace.
519 if self.last_was_space {
520 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
521 && !self.is_skipped_line()
524 ErrorKind::TrailingWhitespace,
532 // Check for any line width errors we couldn't correct.
533 let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
534 if self.line_len > self.config.max_width()
535 && !self.is_skipped_line()
536 && self.should_report_error(kind, &error_kind)
538 let is_string = self.is_string;
539 self.push_err(error_kind, kind.is_comment(), is_string);
545 self.format_line = self
548 .contains_line(self.name, self.cur_line);
549 self.newline_count += 1;
550 self.last_was_space = false;
551 self.line_buffer.clear();
552 self.is_string = false;
555 fn char(&mut self, c: char, kind: FullCodeCharKind) {
556 self.newline_count = 0;
557 self.line_len += if c == '\t' {
558 self.config.tab_spaces()
562 self.last_was_space = c.is_whitespace();
563 self.line_buffer.push(c);
564 if kind.is_string() {
565 self.is_string = true;
569 fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
570 self.errors.push(FormattingError {
575 line_buffer: self.line_buffer.clone(),
579 fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
580 let allow_error_report =
581 if char_kind.is_comment() || self.is_string || error_kind.is_comment() {
582 self.config.error_on_unformatted()
588 ErrorKind::LineOverflow(..) => {
589 self.config.error_on_line_overflow() && allow_error_report
591 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
596 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
597 fn is_skipped_line(&self) -> bool {
600 .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
606 parse_session: &ParseSess,
608 report: &mut FormatReport,
609 ) -> Result<ast::Crate, ErrorKind> {
610 let input_is_stdin = input.is_text();
612 let parser = match input {
613 Input::File(file) => Ok(parse::new_parser_from_file(parse_session, &file)),
614 Input::Text(text) => parse::maybe_new_parser_from_source_str(
616 syntax::source_map::FileName::Custom("stdin".to_owned()),
622 .map(|d| DiagnosticBuilder::new_diagnostic(&parse_session.span_diagnostic, d))
627 let result = match parser {
629 parser.cfg_mods = false;
630 if config.skip_children() {
631 parser.recurse_into_file_modules = false;
634 let mut parser = AssertUnwindSafe(parser);
635 catch_unwind(move || parser.0.parse_crate_mod().map_err(|d| vec![d]))
637 Err(db) => Ok(Err(db)),
642 if !parse_session.span_diagnostic.has_errors() {
646 Ok(Err(mut diagnostics)) => diagnostics.iter_mut().for_each(|d| d.emit()),
648 // Note that if you see this message and want more information,
649 // then run the `parse_crate_mod` function above without
650 // `catch_unwind` so rustfmt panics and you can get a backtrace.
651 should_emit_verbose(input_is_stdin, config, || {
652 println!("The Rust parser panicked")
657 report.add_parsing_error();
658 Err(ErrorKind::ParseError)
661 fn silent_emitter(source_map: Rc<SourceMap>) -> Box<EmitterWriter> {
662 Box::new(EmitterWriter::new(
663 Box::new(Vec::new()),
670 fn make_parse_sess(source_map: Rc<SourceMap>, config: &Config) -> ParseSess {
671 let tty_handler = if config.hide_parse_errors() {
672 let silent_emitter = silent_emitter(source_map.clone());
673 Handler::with_emitter(true, false, silent_emitter)
675 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
676 let color_cfg = if supports_color {
681 Handler::with_tty_emitter(color_cfg, true, false, Some(source_map.clone()))
684 ParseSess::with_span_handler(tty_handler, source_map)
687 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
691 if config.verbose() == Verbosity::Verbose && !is_stdin {