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::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 main_file = input.file_name();
67 let input_is_stdin = main_file == FileName::Stdin;
70 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
71 let mut parse_session = make_parse_sess(codemap.clone(), config);
72 let krate = parse_crate(input, &parse_session, config, &mut summary)?;
73 timer = timer.done_parsing();
75 // Suppress error output if we have to do any further parsing.
76 let silent_emitter = silent_emitter(codemap);
77 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
79 let mut context = FormatContext::new(
88 let files = modules::list_files(&krate, context.parse_session.codemap())?;
89 for (path, module) in files {
90 if (config.skip_children() && path != main_file) || config.ignore().skip_file(&path) {
93 should_emit_verbose(!input_is_stdin, config, || println!("Formatting {}", path));
94 let is_root = path == main_file;
95 context.format_file(path, module, is_root)?;
97 timer = timer.done_formatting();
99 should_emit_verbose(!input_is_stdin, config, || {
101 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
102 timer.get_parse_time(),
103 timer.get_format_time(),
107 context.summarise_errors();
108 Ok((context.report, context.summary))
111 // Used for formatting files.
113 struct FormatContext<'a, T: FormatHandler + 'a> {
114 krate: &'a ast::Crate,
115 report: FormatReport,
117 parse_session: ParseSess,
122 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
123 // Moves errors from the report to the summary.
124 fn summarise_errors(&mut self) {
125 if self.report.has_warnings() {
126 self.summary.add_formatting_error();
128 let report_errs = &self.report.internal.borrow().1;
129 if report_errs.has_check_errors {
130 self.summary.add_check_error();
132 if report_errs.has_operational_errors {
133 self.summary.add_operational_error();
137 // Formats a single file/module.
143 ) -> Result<(), ErrorKind> {
147 .lookup_char_pos(module.inner.lo())
149 let big_snippet = filemap.src.as_ref().unwrap();
150 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
151 let mut visitor = FmtVisitor::from_codemap(
158 // Format inner attributes if available.
159 if !self.krate.attrs.is_empty() && is_root {
160 visitor.skip_empty_lines(filemap.end_pos);
161 if visitor.visit_attrs(&self.krate.attrs, ast::AttrStyle::Inner) {
162 visitor.push_rewrite(module.inner, None);
164 visitor.format_separate_mod(module, &*filemap);
167 visitor.last_pos = filemap.start_pos;
168 visitor.skip_empty_lines(filemap.end_pos);
169 visitor.format_separate_mod(module, &*filemap);
174 ::utils::count_newlines(&visitor.buffer)
177 // For some reason, the codemap does not include terminating
178 // newlines so we must add one on for each file. This is sad.
179 filemap::append_newline(&mut visitor.buffer);
184 &visitor.skipped_range,
188 replace_with_system_newlines(&mut visitor.buffer, &self.config);
190 if visitor.macro_rewrite_failure {
191 self.summary.add_macro_format_failure();
194 self.handler.handle_formatted_file(path, visitor.buffer)
198 // Handle the results of formatting.
199 trait FormatHandler {
200 fn handle_formatted_file(&mut self, path: FileName, result: String) -> Result<(), ErrorKind>;
203 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
204 // Called for each formatted file.
205 fn handle_formatted_file(
209 ) -> Result<(), ErrorKind> {
210 if let Some(ref mut out) = self.out {
211 match filemap::write_file(&mut result, &path, out, &self.config) {
212 Ok(b) if b => self.summary.add_diff(),
214 // Create a new error with path_str to help users see which files failed
215 let err_msg = format!("{}: {}", path, e);
216 return Err(io::Error::new(e.kind(), err_msg).into());
222 self.filemap.push((path, result));
227 pub(crate) struct FormattingError {
228 pub(crate) line: usize,
229 pub(crate) kind: ErrorKind,
232 pub(crate) line_buffer: String,
235 impl FormattingError {
236 pub(crate) fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
238 line: codemap.lookup_char_pos(span.lo()).line,
239 is_comment: kind.is_comment(),
243 .span_to_lines(*span)
247 .get_line(fl.lines[0].line_index)
248 .map(|l| l.into_owned())
250 .unwrap_or_else(|| String::new()),
254 pub(crate) fn msg_prefix(&self) -> &str {
256 ErrorKind::LineOverflow(..)
257 | ErrorKind::TrailingWhitespace
258 | ErrorKind::IoError(_)
259 | ErrorKind::ParseError
260 | ErrorKind::LostComment => "internal error:",
261 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
262 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
266 pub(crate) fn msg_suffix(&self) -> &str {
267 if self.is_comment || self.is_string {
268 "set `error_on_unformatted = false` to suppress \
269 the warning against comments or string literals\n"
276 pub(crate) fn format_len(&self) -> (usize, usize) {
278 ErrorKind::LineOverflow(found, max) => (max, found - max),
279 ErrorKind::TrailingWhitespace
280 | ErrorKind::DeprecatedAttr
282 | ErrorKind::LostComment => {
283 let trailing_ws_start = self
285 .rfind(|c: char| !c.is_whitespace())
290 self.line_buffer.len() - trailing_ws_start,
298 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
300 #[derive(Default, Debug)]
301 pub(crate) struct ReportedErrors {
302 pub(crate) has_operational_errors: bool,
303 pub(crate) has_check_errors: bool,
306 /// A single span of changed lines, with 0 or more removed lines
307 /// and a vector of 0 or more inserted lines.
308 #[derive(Debug, PartialEq, Eq)]
309 pub(crate) struct ModifiedChunk {
310 /// The first to be removed from the original text
311 pub line_number_orig: u32,
312 /// The number of lines which have been replaced
313 pub lines_removed: u32,
315 pub lines: Vec<String>,
318 /// Set of changed sections of a file.
319 #[derive(Debug, PartialEq, Eq)]
320 pub(crate) struct ModifiedLines {
321 /// The set of changed chunks.
322 pub chunks: Vec<ModifiedChunk>,
325 /// A summary of a Rustfmt run.
326 #[derive(Debug, Default, Clone, Copy)]
328 // Encountered e.g. an IO error.
329 has_operational_errors: bool,
331 // Failed to reformat code because of parsing errors.
332 has_parsing_errors: bool,
334 // Code is valid, but it is impossible to format it properly.
335 has_formatting_errors: bool,
337 // Code contains macro call that was unable to format.
338 pub(crate) has_macro_format_failure: bool,
340 // Failed a check, such as the license check or other opt-in checking.
341 has_check_errors: bool,
343 /// Formatted code differs from existing code (--check only).
348 pub fn has_operational_errors(&self) -> bool {
349 self.has_operational_errors
352 pub fn has_parsing_errors(&self) -> bool {
353 self.has_parsing_errors
356 pub fn has_formatting_errors(&self) -> bool {
357 self.has_formatting_errors
360 pub fn has_check_errors(&self) -> bool {
361 self.has_check_errors
364 pub(crate) fn has_macro_formatting_failure(&self) -> bool {
365 self.has_macro_format_failure
368 pub fn add_operational_error(&mut self) {
369 self.has_operational_errors = true;
372 pub(crate) fn add_parsing_error(&mut self) {
373 self.has_parsing_errors = true;
376 pub(crate) fn add_formatting_error(&mut self) {
377 self.has_formatting_errors = true;
380 pub(crate) fn add_check_error(&mut self) {
381 self.has_check_errors = true;
384 pub(crate) fn add_diff(&mut self) {
385 self.has_diff = true;
388 pub(crate) fn add_macro_format_failure(&mut self) {
389 self.has_macro_format_failure = true;
392 pub fn has_no_errors(&self) -> bool {
393 !(self.has_operational_errors
394 || self.has_parsing_errors
395 || self.has_formatting_errors
399 /// Combine two summaries together.
400 pub fn add(&mut self, other: Summary) {
401 self.has_operational_errors |= other.has_operational_errors;
402 self.has_formatting_errors |= other.has_formatting_errors;
403 self.has_macro_format_failure |= other.has_macro_format_failure;
404 self.has_parsing_errors |= other.has_parsing_errors;
405 self.has_check_errors |= other.has_check_errors;
406 self.has_diff |= other.has_diff;
410 #[derive(Clone, Copy, Debug)]
412 Initialized(Instant),
413 DoneParsing(Instant, Instant),
414 DoneFormatting(Instant, Instant, Instant),
418 fn done_parsing(self) -> Self {
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::DoneParsing(init_time, parse_time) => {
428 Timer::DoneFormatting(init_time, parse_time, Instant::now())
430 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
434 /// Returns the time it took to parse the source files in seconds.
435 fn get_parse_time(&self) -> f32 {
437 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
438 // This should never underflow since `Instant::now()` guarantees monotonicity.
439 Self::duration_to_f32(parse_time.duration_since(init))
441 Timer::Initialized(..) => unreachable!(),
445 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
447 fn get_format_time(&self) -> f32 {
449 Timer::DoneFormatting(_init, parse_time, format_time) => {
450 Self::duration_to_f32(format_time.duration_since(parse_time))
452 Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
456 fn duration_to_f32(d: Duration) -> f32 {
457 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
461 // Formatting done on a char by char or line by line basis.
462 // FIXME(#20) other stuff for parity with make tidy
466 skipped_range: &[(usize, usize)],
468 report: &FormatReport,
470 let mut formatter = FormatLines::new(name, skipped_range, config);
471 formatter.check_license(text);
472 formatter.iterate(text);
474 if formatter.newline_count > 1 {
475 debug!("track truncate: {} {}", text.len(), formatter.newline_count);
476 let line = text.len() - formatter.newline_count + 1;
480 report.append(name.clone(), formatter.errors);
483 struct FormatLines<'a> {
485 skipped_range: &'a [(usize, usize)],
486 last_was_space: bool,
489 newline_count: usize,
490 errors: Vec<FormattingError>,
491 issue_seeker: BadIssueSeeker,
493 // true if the current line contains a string literal.
496 allow_issue_seek: bool,
500 impl<'a> FormatLines<'a> {
503 skipped_range: &'a [(usize, usize)],
505 ) -> FormatLines<'a> {
506 let issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
510 last_was_space: false,
515 allow_issue_seek: !issue_seeker.is_disabled(),
517 line_buffer: String::with_capacity(config.max_width() * 2),
519 format_line: config.file_lines().contains_line(name, 1),
524 fn check_license(&mut self, text: &mut String) {
525 if let Some(ref license_template) = self.config.license_template {
526 if !license_template.is_match(text) {
527 self.errors.push(FormattingError {
529 kind: ErrorKind::LicenseCheck,
532 line_buffer: String::new(),
538 // Iterate over the chars in the file map.
539 fn iterate(&mut self, text: &mut String) {
540 for (kind, c) in CharClasses::new(text.chars()) {
545 if self.allow_issue_seek && self.format_line {
546 // Add warnings for bad todos/ fixmes
547 if let Some(issue) = self.issue_seeker.inspect(c) {
548 self.push_err(ErrorKind::BadIssue(issue), false, false);
560 fn new_line(&mut self, kind: FullCodeCharKind) {
561 if self.format_line {
562 // Check for (and record) trailing whitespace.
563 if self.last_was_space {
564 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
565 && !self.is_skipped_line()
568 ErrorKind::TrailingWhitespace,
576 // Check for any line width errors we couldn't correct.
577 let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
578 if self.line_len > self.config.max_width()
579 && !self.is_skipped_line()
580 && self.should_report_error(kind, &error_kind)
582 self.push_err(error_kind, kind.is_comment(), self.is_string);
588 self.format_line = self
591 .contains_line(self.name, self.cur_line);
592 self.newline_count += 1;
593 self.last_was_space = false;
594 self.line_buffer.clear();
595 self.is_string = false;
598 fn char(&mut self, c: char, kind: FullCodeCharKind) {
599 self.newline_count = 0;
600 self.line_len += if c == '\t' {
601 self.config.tab_spaces()
605 self.last_was_space = c.is_whitespace();
606 self.line_buffer.push(c);
607 if kind.is_string() {
608 self.is_string = true;
612 fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
613 self.errors.push(FormattingError {
618 line_buffer: self.line_buffer.clone(),
622 fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
623 let allow_error_report =
624 if char_kind.is_comment() || self.is_string || error_kind.is_comment() {
625 self.config.error_on_unformatted()
631 ErrorKind::LineOverflow(..) => {
632 self.config.error_on_line_overflow() && allow_error_report
634 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
639 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
640 fn is_skipped_line(&self) -> bool {
643 .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
649 parse_session: &ParseSess,
651 summary: &mut Summary,
652 ) -> Result<ast::Crate, ErrorKind> {
653 let input_is_stdin = input.is_text();
655 let mut parser = match input {
656 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
657 Input::Text(text) => parse::new_parser_from_source_str(
659 syntax::codemap::FileName::Custom("stdin".to_owned()),
664 parser.cfg_mods = false;
665 if config.skip_children() {
666 parser.recurse_into_file_modules = false;
669 let mut parser = AssertUnwindSafe(parser);
670 let result = catch_unwind(move || parser.0.parse_crate_mod());
674 if !parse_session.span_diagnostic.has_errors() {
678 Ok(Err(mut e)) => e.emit(),
680 // Note that if you see this message and want more information,
681 // then run the `parse_crate_mod` function above without
682 // `catch_unwind` so rustfmt panics and you can get a backtrace.
683 should_emit_verbose(!input_is_stdin, config, || {
684 println!("The Rust parser panicked")
689 summary.add_parsing_error();
690 Err(ErrorKind::ParseError)
693 fn silent_emitter(codemap: Rc<CodeMap>) -> Box<EmitterWriter> {
694 Box::new(EmitterWriter::new(
695 Box::new(Vec::new()),
702 fn make_parse_sess(codemap: Rc<CodeMap>, config: &Config) -> ParseSess {
703 let tty_handler = if config.hide_parse_errors() {
704 let silent_emitter = silent_emitter(codemap.clone());
705 Handler::with_emitter(true, false, silent_emitter)
707 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
708 let color_cfg = if supports_color {
713 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
716 ParseSess::with_span_handler(tty_handler, codemap)
719 fn replace_with_system_newlines(text: &mut String, config: &Config) -> () {
720 let style = if config.newline_style() == NewlineStyle::Native {
722 NewlineStyle::Windows
727 config.newline_style()
731 NewlineStyle::Unix => return,
732 NewlineStyle::Windows => {
733 let mut transformed = String::with_capacity(text.capacity());
734 for c in text.chars() {
736 '\n' => transformed.push_str("\r\n"),
738 c => transformed.push(c),
743 NewlineStyle::Native => unreachable!(),
747 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
751 if config.verbose() == Verbosity::Verbose && !is_stdin {