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())
249 }).unwrap_or_else(|| String::new()),
253 pub(crate) fn msg_prefix(&self) -> &str {
255 ErrorKind::LineOverflow(..)
256 | ErrorKind::TrailingWhitespace
257 | ErrorKind::IoError(_)
258 | ErrorKind::ParseError
259 | ErrorKind::LostComment => "internal error:",
260 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
261 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
265 pub(crate) fn msg_suffix(&self) -> &str {
266 if self.is_comment || self.is_string {
267 "set `error_on_unformatted = false` to suppress \
268 the warning against comments or string literals\n"
275 pub(crate) fn format_len(&self) -> (usize, usize) {
277 ErrorKind::LineOverflow(found, max) => (max, found - max),
278 ErrorKind::TrailingWhitespace
279 | ErrorKind::DeprecatedAttr
281 | ErrorKind::LostComment => {
282 let trailing_ws_start = self
284 .rfind(|c: char| !c.is_whitespace())
289 self.line_buffer.len() - trailing_ws_start,
297 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
299 #[derive(Default, Debug)]
300 pub(crate) struct ReportedErrors {
301 pub(crate) has_operational_errors: bool,
302 pub(crate) has_check_errors: bool,
305 /// A single span of changed lines, with 0 or more removed lines
306 /// and a vector of 0 or more inserted lines.
307 #[derive(Debug, PartialEq, Eq)]
308 pub(crate) struct ModifiedChunk {
309 /// The first to be removed from the original text
310 pub line_number_orig: u32,
311 /// The number of lines which have been replaced
312 pub lines_removed: u32,
314 pub lines: Vec<String>,
317 /// Set of changed sections of a file.
318 #[derive(Debug, PartialEq, Eq)]
319 pub(crate) struct ModifiedLines {
320 /// The set of changed chunks.
321 pub chunks: Vec<ModifiedChunk>,
324 /// A summary of a Rustfmt run.
325 #[derive(Debug, Default, Clone, Copy)]
327 // Encountered e.g. an IO error.
328 has_operational_errors: bool,
330 // Failed to reformat code because of parsing errors.
331 has_parsing_errors: bool,
333 // Code is valid, but it is impossible to format it properly.
334 has_formatting_errors: bool,
336 // Code contains macro call that was unable to format.
337 pub(crate) has_macro_format_failure: bool,
339 // Failed a check, such as the license check or other opt-in checking.
340 has_check_errors: bool,
342 /// Formatted code differs from existing code (--check only).
347 pub fn has_operational_errors(&self) -> bool {
348 self.has_operational_errors
351 pub fn has_parsing_errors(&self) -> bool {
352 self.has_parsing_errors
355 pub fn has_formatting_errors(&self) -> bool {
356 self.has_formatting_errors
359 pub fn has_check_errors(&self) -> bool {
360 self.has_check_errors
363 pub(crate) fn has_macro_formatting_failure(&self) -> bool {
364 self.has_macro_format_failure
367 pub fn add_operational_error(&mut self) {
368 self.has_operational_errors = true;
371 pub(crate) fn add_parsing_error(&mut self) {
372 self.has_parsing_errors = true;
375 pub(crate) fn add_formatting_error(&mut self) {
376 self.has_formatting_errors = true;
379 pub(crate) fn add_check_error(&mut self) {
380 self.has_check_errors = true;
383 pub(crate) fn add_diff(&mut self) {
384 self.has_diff = true;
387 pub(crate) fn add_macro_format_failure(&mut self) {
388 self.has_macro_format_failure = true;
391 pub fn has_no_errors(&self) -> bool {
392 !(self.has_operational_errors
393 || self.has_parsing_errors
394 || self.has_formatting_errors
398 /// Combine two summaries together.
399 pub fn add(&mut self, other: Summary) {
400 self.has_operational_errors |= other.has_operational_errors;
401 self.has_formatting_errors |= other.has_formatting_errors;
402 self.has_macro_format_failure |= other.has_macro_format_failure;
403 self.has_parsing_errors |= other.has_parsing_errors;
404 self.has_check_errors |= other.has_check_errors;
405 self.has_diff |= other.has_diff;
409 #[derive(Clone, Copy, Debug)]
411 Initialized(Instant),
412 DoneParsing(Instant, Instant),
413 DoneFormatting(Instant, Instant, Instant),
417 fn done_parsing(self) -> Self {
419 Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
420 _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
424 fn done_formatting(self) -> Self {
426 Timer::DoneParsing(init_time, parse_time) => {
427 Timer::DoneFormatting(init_time, parse_time, Instant::now())
429 _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
433 /// Returns the time it took to parse the source files in seconds.
434 fn get_parse_time(&self) -> f32 {
436 Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
437 // This should never underflow since `Instant::now()` guarantees monotonicity.
438 Self::duration_to_f32(parse_time.duration_since(init))
440 Timer::Initialized(..) => unreachable!(),
444 /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
446 fn get_format_time(&self) -> f32 {
448 Timer::DoneFormatting(_init, parse_time, format_time) => {
449 Self::duration_to_f32(format_time.duration_since(parse_time))
451 Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
455 fn duration_to_f32(d: Duration) -> f32 {
456 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
460 // Formatting done on a char by char or line by line basis.
461 // FIXME(#20) other stuff for parity with make tidy
465 skipped_range: &[(usize, usize)],
467 report: &FormatReport,
469 let mut formatter = FormatLines::new(name, skipped_range, config);
470 formatter.check_license(text);
471 formatter.iterate(text);
473 if formatter.newline_count > 1 {
474 debug!("track truncate: {} {}", text.len(), formatter.newline_count);
475 let line = text.len() - formatter.newline_count + 1;
479 report.append(name.clone(), formatter.errors);
482 struct FormatLines<'a> {
484 skipped_range: &'a [(usize, usize)],
485 last_was_space: bool,
488 newline_count: usize,
489 errors: Vec<FormattingError>,
490 issue_seeker: BadIssueSeeker,
492 // true if the current line contains a string literal.
495 allow_issue_seek: bool,
499 impl<'a> FormatLines<'a> {
502 skipped_range: &'a [(usize, usize)],
504 ) -> FormatLines<'a> {
505 let issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
509 last_was_space: false,
514 allow_issue_seek: !issue_seeker.is_disabled(),
516 line_buffer: String::with_capacity(config.max_width() * 2),
518 format_line: config.file_lines().contains_line(name, 1),
523 fn check_license(&mut self, text: &mut String) {
524 if let Some(ref license_template) = self.config.license_template {
525 if !license_template.is_match(text) {
526 self.errors.push(FormattingError {
528 kind: ErrorKind::LicenseCheck,
531 line_buffer: String::new(),
537 // Iterate over the chars in the file map.
538 fn iterate(&mut self, text: &mut String) {
539 for (kind, c) in CharClasses::new(text.chars()) {
544 if self.allow_issue_seek && self.format_line {
545 // Add warnings for bad todos/ fixmes
546 if let Some(issue) = self.issue_seeker.inspect(c) {
547 self.push_err(ErrorKind::BadIssue(issue), false, false);
559 fn new_line(&mut self, kind: FullCodeCharKind) {
560 if self.format_line {
561 // Check for (and record) trailing whitespace.
562 if self.last_was_space {
563 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
564 && !self.is_skipped_line()
567 ErrorKind::TrailingWhitespace,
575 // Check for any line width errors we couldn't correct.
576 let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
577 if self.line_len > self.config.max_width()
578 && !self.is_skipped_line()
579 && self.should_report_error(kind, &error_kind)
581 self.push_err(error_kind, kind.is_comment(), self.is_string);
587 self.format_line = self
590 .contains_line(self.name, self.cur_line);
591 self.newline_count += 1;
592 self.last_was_space = false;
593 self.line_buffer.clear();
594 self.is_string = false;
597 fn char(&mut self, c: char, kind: FullCodeCharKind) {
598 self.newline_count = 0;
599 self.line_len += if c == '\t' {
600 self.config.tab_spaces()
604 self.last_was_space = c.is_whitespace();
605 self.line_buffer.push(c);
606 if kind.is_string() {
607 self.is_string = true;
611 fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
612 self.errors.push(FormattingError {
617 line_buffer: self.line_buffer.clone(),
621 fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
622 let allow_error_report =
623 if char_kind.is_comment() || self.is_string || error_kind.is_comment() {
624 self.config.error_on_unformatted()
630 ErrorKind::LineOverflow(..) => {
631 self.config.error_on_line_overflow() && allow_error_report
633 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
638 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
639 fn is_skipped_line(&self) -> bool {
642 .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
648 parse_session: &ParseSess,
650 summary: &mut Summary,
651 ) -> Result<ast::Crate, ErrorKind> {
652 let input_is_stdin = input.is_text();
654 let mut parser = match input {
655 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
656 Input::Text(text) => parse::new_parser_from_source_str(
658 syntax::codemap::FileName::Custom("stdin".to_owned()),
663 parser.cfg_mods = false;
664 if config.skip_children() {
665 parser.recurse_into_file_modules = false;
668 let mut parser = AssertUnwindSafe(parser);
669 let result = catch_unwind(move || parser.0.parse_crate_mod());
673 if !parse_session.span_diagnostic.has_errors() {
677 Ok(Err(mut e)) => e.emit(),
679 // Note that if you see this message and want more information,
680 // then run the `parse_crate_mod` function above without
681 // `catch_unwind` so rustfmt panics and you can get a backtrace.
682 should_emit_verbose(!input_is_stdin, config, || {
683 println!("The Rust parser panicked")
688 summary.add_parsing_error();
689 Err(ErrorKind::ParseError)
692 fn silent_emitter(codemap: Rc<CodeMap>) -> Box<EmitterWriter> {
693 Box::new(EmitterWriter::new(
694 Box::new(Vec::new()),
701 fn make_parse_sess(codemap: Rc<CodeMap>, config: &Config) -> ParseSess {
702 let tty_handler = if config.hide_parse_errors() {
703 let silent_emitter = silent_emitter(codemap.clone());
704 Handler::with_emitter(true, false, silent_emitter)
706 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
707 let color_cfg = if supports_color {
712 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
715 ParseSess::with_span_handler(tty_handler, codemap)
718 fn replace_with_system_newlines(text: &mut String, config: &Config) -> () {
719 let style = if config.newline_style() == NewlineStyle::Native {
721 NewlineStyle::Windows
726 config.newline_style()
730 NewlineStyle::Unix => return,
731 NewlineStyle::Windows => {
732 let mut transformed = String::with_capacity(text.capacity());
733 for c in text.chars() {
735 '\n' => transformed.push_str("\r\n"),
737 c => transformed.push(c),
742 NewlineStyle::Native => unreachable!(),
746 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
750 if config.verbose() == Verbosity::Verbose && !is_stdin {