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::codemap::{CodeMap, FilePathMapping, Span};
11 use syntax::errors::emitter::{ColorConfig, EmitterWriter};
12 use syntax::errors::{DiagnosticBuilder, Handler};
13 use syntax::parse::{self, ParseSess};
15 use comment::{CharClasses, FullCodeCharKind};
16 use config::{Config, FileName, NewlineStyle, Verbosity};
17 use issues::BadIssueSeeker;
18 use visitor::{FmtVisitor, SnippetProvider};
19 use {filemap, modules, ErrorKind, FormatReport, Input, Session};
21 // A map of the files of a crate, with their new content
22 pub(crate) type FileMap = 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, summary)| {
50 self.summary.add(summary);
57 // Format an entire crate (or subset of the module tree).
58 fn format_project<T: FormatHandler>(
62 ) -> Result<(FormatReport, Summary), ErrorKind> {
63 let mut summary = Summary::default();
64 let mut timer = Timer::Initialized(Instant::now());
66 let input_is_stdin = input.is_text();
67 let main_file = match input {
68 Input::File(ref file) => FileName::Real(file.clone()),
69 Input::Text(..) => FileName::Stdin,
73 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
74 let mut parse_session = make_parse_sess(codemap.clone(), config);
75 let krate = match parse_input(input, &parse_session, config) {
79 ParseError::Error(mut diagnostic) => diagnostic.emit(),
80 ParseError::Panic => {
81 // Note that if you see this message and want more information,
82 // then go to `parse_input` and run the parse function without
83 // `catch_unwind` so rustfmt panics and you can get a backtrace.
84 should_emit_verbose(!input_is_stdin, config, || {
85 println!("The Rust parser panicked")
88 ParseError::Recovered => {}
90 summary.add_parsing_error();
91 return Err(ErrorKind::ParseError);
94 timer = timer.done_parsing();
96 // Suppress error output if we have to do any further parsing.
97 let silent_emitter = Box::new(EmitterWriter::new(
99 Some(codemap.clone()),
103 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
105 let mut context = FormatContext::new(
114 let files = modules::list_files(&krate, context.parse_session.codemap())?;
115 for (path, module) in files {
116 if (config.skip_children() && path != main_file) || config.ignore().skip_file(&path) {
119 should_emit_verbose(!input_is_stdin, config, || println!("Formatting {}", path));
120 let is_root = path == main_file;
121 context.format_file(path, module, is_root)?;
123 timer = timer.done_formatting();
125 should_emit_verbose(!input_is_stdin, config, || {
127 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
128 timer.get_parse_time(),
129 timer.get_format_time(),
133 if context.report.has_warnings() {
134 context.summary.add_formatting_error();
137 let report_errs = &context.report.internal.borrow().1;
138 if report_errs.has_check_errors {
139 context.summary.add_check_error();
141 if report_errs.has_operational_errors {
142 context.summary.add_operational_error();
146 Ok((context.report, context.summary))
149 // Used for formatting files.
151 struct FormatContext<'a, T: FormatHandler + 'a> {
152 krate: &'a ast::Crate,
153 report: FormatReport,
155 parse_session: ParseSess,
160 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
161 // Formats a single file/module.
167 ) -> Result<(), ErrorKind> {
171 .lookup_char_pos(module.inner.lo())
173 let big_snippet = filemap.src.as_ref().unwrap();
174 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
175 let mut visitor = FmtVisitor::from_codemap(
181 // Format inner attributes if available.
182 if !self.krate.attrs.is_empty() && is_root {
183 visitor.skip_empty_lines(filemap.end_pos);
184 if visitor.visit_attrs(&self.krate.attrs, ast::AttrStyle::Inner) {
185 visitor.push_rewrite(module.inner, None);
187 visitor.format_separate_mod(module, &*filemap);
190 visitor.last_pos = filemap.start_pos;
191 visitor.skip_empty_lines(filemap.end_pos);
192 visitor.format_separate_mod(module, &*filemap);
197 ::utils::count_newlines(&visitor.buffer)
200 // For some reason, the codemap does not include terminating
201 // newlines so we must add one on for each file. This is sad.
202 filemap::append_newline(&mut visitor.buffer);
207 &visitor.skipped_range,
211 replace_with_system_newlines(&mut visitor.buffer, &self.config);
213 if visitor.macro_rewrite_failure {
214 self.summary.add_macro_format_failure();
217 self.handler.handle_formatted_file(path, visitor.buffer)
221 // Handle the results of formatting.
222 trait FormatHandler {
223 fn handle_formatted_file(&mut self, path: FileName, result: String) -> Result<(), ErrorKind>;
226 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
227 // Called for each formatted file.
228 fn handle_formatted_file(
232 ) -> Result<(), ErrorKind> {
233 if let Some(ref mut out) = self.out {
234 match filemap::write_file(&mut result, &path, out, &self.config) {
235 Ok(b) if b => self.summary.add_diff(),
237 // Create a new error with path_str to help users see which files failed
238 let err_msg = format!("{}: {}", path, e);
239 return Err(io::Error::new(e.kind(), err_msg).into());
245 self.filemap.push((path, result));
250 pub(crate) struct FormattingError {
251 pub(crate) line: usize,
252 pub(crate) kind: ErrorKind,
255 pub(crate) line_buffer: String,
258 impl FormattingError {
259 pub(crate) fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
261 line: codemap.lookup_char_pos(span.lo()).line,
262 is_comment: kind.is_comment(),
266 .span_to_lines(*span)
270 .get_line(fl.lines[0].line_index)
271 .map(|l| l.into_owned())
273 .unwrap_or_else(|| String::new()),
277 pub(crate) fn msg_prefix(&self) -> &str {
279 ErrorKind::LineOverflow(..)
280 | ErrorKind::TrailingWhitespace
281 | ErrorKind::IoError(_)
282 | ErrorKind::ParseError
283 | ErrorKind::LostComment => "internal error:",
284 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
285 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
289 pub(crate) fn msg_suffix(&self) -> &str {
290 if self.is_comment || self.is_string {
291 "set `error_on_unformatted = false` to suppress \
292 the warning against comments or string literals\n"
299 pub(crate) fn format_len(&self) -> (usize, usize) {
301 ErrorKind::LineOverflow(found, max) => (max, found - max),
302 ErrorKind::TrailingWhitespace
303 | ErrorKind::DeprecatedAttr
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)]
324 pub(crate) struct ReportedErrors {
325 pub(crate) has_operational_errors: bool,
326 pub(crate) has_check_errors: bool,
329 /// A single span of changed lines, with 0 or more removed lines
330 /// and a vector of 0 or more inserted lines.
331 #[derive(Debug, PartialEq, Eq)]
332 pub(crate) struct ModifiedChunk {
333 /// The first to be removed from the original text
334 pub line_number_orig: u32,
335 /// The number of lines which have been replaced
336 pub lines_removed: u32,
338 pub lines: Vec<String>,
341 /// Set of changed sections of a file.
342 #[derive(Debug, PartialEq, Eq)]
343 pub(crate) struct ModifiedLines {
344 /// The set of changed chunks.
345 pub chunks: Vec<ModifiedChunk>,
348 /// A summary of a Rustfmt run.
349 #[derive(Debug, Default, Clone, Copy)]
351 // Encountered e.g. an IO error.
352 has_operational_errors: bool,
354 // Failed to reformat code because of parsing errors.
355 has_parsing_errors: bool,
357 // Code is valid, but it is impossible to format it properly.
358 has_formatting_errors: bool,
360 // Code contains macro call that was unable to format.
361 pub(crate) has_macro_format_failure: bool,
363 // Failed a check, such as the license check or other opt-in checking.
364 has_check_errors: bool,
366 /// Formatted code differs from existing code (--check only).
371 pub fn has_operational_errors(&self) -> bool {
372 self.has_operational_errors
375 pub fn has_parsing_errors(&self) -> bool {
376 self.has_parsing_errors
379 pub fn has_formatting_errors(&self) -> bool {
380 self.has_formatting_errors
383 pub fn has_check_errors(&self) -> bool {
384 self.has_check_errors
387 pub(crate) fn has_macro_formatting_failure(&self) -> bool {
388 self.has_macro_format_failure
391 pub fn add_operational_error(&mut self) {
392 self.has_operational_errors = true;
395 pub(crate) fn add_parsing_error(&mut self) {
396 self.has_parsing_errors = true;
399 pub(crate) fn add_formatting_error(&mut self) {
400 self.has_formatting_errors = true;
403 pub(crate) fn add_check_error(&mut self) {
404 self.has_check_errors = true;
407 pub(crate) fn add_diff(&mut self) {
408 self.has_diff = true;
411 pub(crate) fn add_macro_format_failure(&mut self) {
412 self.has_macro_format_failure = true;
415 pub fn has_no_errors(&self) -> bool {
416 !(self.has_operational_errors
417 || self.has_parsing_errors
418 || self.has_formatting_errors
422 /// Combine two summaries together.
423 pub fn add(&mut self, other: Summary) {
424 self.has_operational_errors |= other.has_operational_errors;
425 self.has_formatting_errors |= other.has_formatting_errors;
426 self.has_macro_format_failure |= other.has_macro_format_failure;
427 self.has_parsing_errors |= other.has_parsing_errors;
428 self.has_check_errors |= other.has_check_errors;
429 self.has_diff |= other.has_diff;
433 #[derive(Clone, Copy, Debug)]
435 Initialized(Instant),
436 DoneParsing(Instant, Instant),
437 DoneFormatting(Instant, Instant, Instant),
441 fn done_parsing(self) -> Self {
443 Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
444 _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
448 fn done_formatting(self) -> Self {
450 Timer::DoneParsing(init_time, parse_time) => {
451 Timer::DoneFormatting(init_time, parse_time, Instant::now())
453 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
457 /// Returns the time it took to parse the source files in seconds.
458 fn get_parse_time(&self) -> f32 {
460 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
461 // This should never underflow since `Instant::now()` guarantees monotonicity.
462 Self::duration_to_f32(parse_time.duration_since(init))
464 Timer::Initialized(..) => unreachable!(),
468 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
470 fn get_format_time(&self) -> f32 {
472 Timer::DoneFormatting(_init, parse_time, format_time) => {
473 Self::duration_to_f32(format_time.duration_since(parse_time))
475 Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
479 fn duration_to_f32(d: Duration) -> f32 {
480 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
484 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
488 if config.verbose() == Verbosity::Verbose && !is_stdin {
493 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
494 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
497 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
500 fn should_report_error(
502 char_kind: FullCodeCharKind,
504 error_kind: &ErrorKind,
506 let allow_error_report = if char_kind.is_comment() || is_string || error_kind.is_comment() {
507 config.error_on_unformatted()
513 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
514 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
519 // Formatting done on a char by char or line by line basis.
520 // FIXME(#20) other stuff for parity with make tidy
524 skipped_range: &[(usize, usize)],
526 report: &FormatReport,
528 let mut last_was_space = false;
529 let mut line_len = 0;
530 let mut cur_line = 1;
531 let mut newline_count = 0;
532 let mut errors = vec![];
533 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
534 let mut line_buffer = String::with_capacity(config.max_width() * 2);
535 let mut is_string = false; // true if the current line contains a string literal.
536 let mut format_line = config.file_lines().contains_line(name, cur_line);
537 let allow_issue_seek = !issue_seeker.is_disabled();
540 if let Some(ref license_template) = config.license_template {
541 if !license_template.is_match(text) {
542 errors.push(FormattingError {
544 kind: ErrorKind::LicenseCheck,
547 line_buffer: String::new(),
552 // Iterate over the chars in the file map.
553 for (kind, c) in CharClasses::new(text.chars()) {
558 if allow_issue_seek && format_line {
559 // Add warnings for bad todos/ fixmes
560 if let Some(issue) = issue_seeker.inspect(c) {
561 errors.push(FormattingError {
563 kind: ErrorKind::BadIssue(issue),
566 line_buffer: String::new(),
573 // Check for (and record) trailing whitespace.
575 if should_report_error(config, kind, is_string, &ErrorKind::TrailingWhitespace)
576 && !is_skipped_line(cur_line, skipped_range)
578 errors.push(FormattingError {
580 kind: ErrorKind::TrailingWhitespace,
581 is_comment: kind.is_comment(),
582 is_string: kind.is_string(),
583 line_buffer: line_buffer.clone(),
589 // Check for any line width errors we couldn't correct.
590 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
591 if line_len > config.max_width()
592 && !is_skipped_line(cur_line, skipped_range)
593 && should_report_error(config, kind, is_string, &error_kind)
595 errors.push(FormattingError {
598 is_comment: kind.is_comment(),
600 line_buffer: line_buffer.clone(),
607 format_line = config.file_lines().contains_line(name, cur_line);
609 last_was_space = false;
614 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
615 last_was_space = c.is_whitespace();
617 if kind.is_string() {
623 if newline_count > 1 {
624 debug!("track truncate: {} {}", text.len(), newline_count);
625 let line = text.len() - newline_count + 1;
629 report.append(name.clone(), errors);
632 fn parse_input<'sess>(
634 parse_session: &'sess ParseSess,
636 ) -> Result<ast::Crate, ParseError<'sess>> {
637 let mut parser = match input {
638 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
639 Input::Text(text) => parse::new_parser_from_source_str(
641 syntax::codemap::FileName::Custom("stdin".to_owned()),
646 parser.cfg_mods = false;
647 if config.skip_children() {
648 parser.recurse_into_file_modules = false;
651 let mut parser = AssertUnwindSafe(parser);
652 let result = catch_unwind(move || parser.0.parse_crate_mod());
656 if parse_session.span_diagnostic.has_errors() {
657 // Bail out if the parser recovered from an error.
658 Err(ParseError::Recovered)
663 Ok(Err(e)) => Err(ParseError::Error(e)),
664 Err(_) => Err(ParseError::Panic),
668 /// All the ways that parsing can fail.
669 enum ParseError<'sess> {
670 /// There was an error, but the parser recovered.
672 /// There was an error (supplied) and parsing failed.
673 Error(DiagnosticBuilder<'sess>),
674 /// The parser panicked.
678 fn make_parse_sess(codemap: Rc<CodeMap>, config: &Config) -> ParseSess {
679 let tty_handler = if config.hide_parse_errors() {
680 let silent_emitter = Box::new(EmitterWriter::new(
681 Box::new(Vec::new()),
682 Some(codemap.clone()),
686 Handler::with_emitter(true, false, silent_emitter)
688 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
689 let color_cfg = if supports_color {
694 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
697 ParseSess::with_span_handler(tty_handler, codemap)
700 fn replace_with_system_newlines(text: &mut String, config: &Config) -> () {
701 let style = if config.newline_style() == NewlineStyle::Native {
703 NewlineStyle::Windows
708 config.newline_style()
712 NewlineStyle::Unix => return,
713 NewlineStyle::Windows => {
714 let mut transformed = String::with_capacity(text.capacity());
715 for c in text.chars() {
717 '\n' => transformed.push_str("\r\n"),
719 c => transformed.push(c),
724 NewlineStyle::Native => unreachable!(),