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;
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 issues::BadIssueSeeker;
17 use visitor::{FmtVisitor, SnippetProvider};
18 use {filemap, modules, ErrorKind, FormatReport, Input, Session};
20 use config::{Config, FileName, NewlineStyle, Verbosity};
22 // A map of the files of a crate, with their new content
23 pub(crate) type FileMap = Vec<FileRecord>;
25 pub(crate) type FileRecord = (FileName, String);
27 pub(crate) struct FormattingError {
28 pub(crate) line: usize,
29 pub(crate) kind: ErrorKind,
32 pub(crate) line_buffer: String,
35 impl FormattingError {
36 pub(crate) fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
38 line: codemap.lookup_char_pos(span.lo()).line,
39 is_comment: kind.is_comment(),
47 .get_line(fl.lines[0].line_index)
48 .map(|l| l.into_owned())
50 .unwrap_or_else(|| String::new()),
54 pub(crate) fn msg_prefix(&self) -> &str {
56 ErrorKind::LineOverflow(..)
57 | ErrorKind::TrailingWhitespace
58 | ErrorKind::IoError(_)
59 | ErrorKind::ParseError
60 | ErrorKind::LostComment => "internal error:",
61 ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
62 ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
66 pub(crate) fn msg_suffix(&self) -> &str {
67 if self.is_comment || self.is_string {
68 "set `error_on_unformatted = false` to suppress \
69 the warning against comments or string literals\n"
76 pub(crate) fn format_len(&self) -> (usize, usize) {
78 ErrorKind::LineOverflow(found, max) => (max, found - max),
79 ErrorKind::TrailingWhitespace
80 | ErrorKind::DeprecatedAttr
82 | ErrorKind::LostComment => {
83 let trailing_ws_start = self
85 .rfind(|c: char| !c.is_whitespace())
90 self.line_buffer.len() - trailing_ws_start,
98 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
100 #[derive(Default, Debug)]
101 pub(crate) struct ReportedErrors {
102 pub(crate) has_operational_errors: bool,
103 pub(crate) has_check_errors: bool,
106 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
110 if config.verbose() == Verbosity::Verbose && !is_stdin {
115 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
116 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
119 .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
122 fn should_report_error(
124 char_kind: FullCodeCharKind,
126 error_kind: &ErrorKind,
128 let allow_error_report = if char_kind.is_comment() || is_string || error_kind.is_comment() {
129 config.error_on_unformatted()
135 ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
136 ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
141 // Formatting done on a char by char or line by line basis.
142 // FIXME(#20) other stuff for parity with make tidy
146 skipped_range: &[(usize, usize)],
148 report: &FormatReport,
150 let mut last_was_space = false;
151 let mut line_len = 0;
152 let mut cur_line = 1;
153 let mut newline_count = 0;
154 let mut errors = vec![];
155 let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
156 let mut line_buffer = String::with_capacity(config.max_width() * 2);
157 let mut is_string = false; // true if the current line contains a string literal.
158 let mut format_line = config.file_lines().contains_line(name, cur_line);
159 let allow_issue_seek = !issue_seeker.is_disabled();
162 if let Some(ref license_template) = config.license_template {
163 if !license_template.is_match(text) {
164 errors.push(FormattingError {
166 kind: ErrorKind::LicenseCheck,
169 line_buffer: String::new(),
174 // Iterate over the chars in the file map.
175 for (kind, c) in CharClasses::new(text.chars()) {
180 if allow_issue_seek && format_line {
181 // Add warnings for bad todos/ fixmes
182 if let Some(issue) = issue_seeker.inspect(c) {
183 errors.push(FormattingError {
185 kind: ErrorKind::BadIssue(issue),
188 line_buffer: String::new(),
195 // Check for (and record) trailing whitespace.
197 if should_report_error(config, kind, is_string, &ErrorKind::TrailingWhitespace)
198 && !is_skipped_line(cur_line, skipped_range)
200 errors.push(FormattingError {
202 kind: ErrorKind::TrailingWhitespace,
203 is_comment: kind.is_comment(),
204 is_string: kind.is_string(),
205 line_buffer: line_buffer.clone(),
211 // Check for any line width errors we couldn't correct.
212 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
213 if line_len > config.max_width()
214 && !is_skipped_line(cur_line, skipped_range)
215 && should_report_error(config, kind, is_string, &error_kind)
217 errors.push(FormattingError {
220 is_comment: kind.is_comment(),
222 line_buffer: line_buffer.clone(),
229 format_line = config.file_lines().contains_line(name, cur_line);
231 last_was_space = false;
236 line_len += if c == '\t' { config.tab_spaces() } else { 1 };
237 last_was_space = c.is_whitespace();
239 if kind.is_string() {
245 if newline_count > 1 {
246 debug!("track truncate: {} {}", text.len(), newline_count);
247 let line = text.len() - newline_count + 1;
251 report.append(name.clone(), errors);
254 fn parse_input<'sess>(
256 parse_session: &'sess ParseSess,
258 ) -> Result<ast::Crate, ParseError<'sess>> {
259 let mut parser = match input {
260 Input::File(file) => parse::new_parser_from_file(parse_session, &file),
261 Input::Text(text) => parse::new_parser_from_source_str(
263 syntax::codemap::FileName::Custom("stdin".to_owned()),
268 parser.cfg_mods = false;
269 if config.skip_children() {
270 parser.recurse_into_file_modules = false;
273 let mut parser = AssertUnwindSafe(parser);
274 let result = catch_unwind(move || parser.0.parse_crate_mod());
278 if parse_session.span_diagnostic.has_errors() {
279 // Bail out if the parser recovered from an error.
280 Err(ParseError::Recovered)
285 Ok(Err(e)) => Err(ParseError::Error(e)),
286 Err(_) => Err(ParseError::Panic),
290 /// All the ways that parsing can fail.
291 enum ParseError<'sess> {
292 /// There was an error, but the parser recovered.
294 /// There was an error (supplied) and parsing failed.
295 Error(DiagnosticBuilder<'sess>),
296 /// The parser panicked.
300 impl<'b, T: Write + 'b> Session<'b, T> {
301 pub(crate) fn format_input_inner(
304 ) -> Result<(FileMap, FormatReport), ErrorKind> {
305 syntax_pos::hygiene::set_default_edition(self.config.edition().to_libsyntax_pos_edition());
307 if self.config.disable_all_formatting() {
308 // When the input is from stdin, echo back the input.
309 if let Input::Text(ref buf) = input {
310 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
311 return Err(From::from(e));
314 return Ok((FileMap::new(), FormatReport::new()));
317 let input_is_stdin = input.is_text();
318 let mut filemap = FileMap::new();
319 // TODO split Session? out vs config - but what about summary?
320 // - look at error handling
321 let format_result = self.format_ast(input, |this, path, mut result| {
322 if let Some(ref mut out) = this.out {
323 // TODO pull out the has_diff return value
324 match filemap::write_file(&mut result, &path, out, &this.config) {
325 Ok(b) if b => this.summary.add_diff(),
327 // Create a new error with path_str to help users see which files failed
328 let err_msg = format!("{}: {}", path, e);
329 return Err(io::Error::new(e.kind(), err_msg).into());
335 filemap.push((path, result));
339 should_emit_verbose(input_is_stdin, &self.config, || {
340 fn duration_to_f32(d: Duration) -> f32 {
341 d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
345 "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
346 duration_to_f32(self.summary.get_parse_time().unwrap()),
347 duration_to_f32(self.summary.get_format_time().unwrap()),
351 format_result.map(|r| (filemap, r))
354 // TODO name, only uses config and summary
355 // TODO move timing from summary to Session
356 // Formatting which depends on the AST.
360 mut formatted_file: F,
361 ) -> Result<FormatReport, ErrorKind>
363 F: FnMut(&mut Session<T>, FileName, String) -> Result<(), ErrorKind>,
365 let main_file = match input {
366 Input::File(ref file) => FileName::Real(file.clone()),
367 Input::Text(..) => FileName::Stdin,
371 let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
372 let mut parse_session = self.make_parse_sess(codemap.clone());
373 let krate = match parse_input(input, &parse_session, &self.config) {
377 ParseError::Error(mut diagnostic) => diagnostic.emit(),
378 ParseError::Panic => {
379 // Note that if you see this message and want more information,
380 // then go to `parse_input` and run the parse function without
381 // `catch_unwind` so rustfmt panics and you can get a backtrace.
382 should_emit_verbose(main_file != FileName::Stdin, &self.config, || {
383 println!("The Rust parser panicked")
386 ParseError::Recovered => {}
388 self.summary.add_parsing_error();
389 return Err(ErrorKind::ParseError);
392 self.summary.mark_parse_time();
394 // Suppress error output if we have to do any further parsing.
395 let silent_emitter = Box::new(EmitterWriter::new(
396 Box::new(Vec::new()),
397 Some(codemap.clone()),
401 parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
403 let report = FormatReport::new();
405 let skip_children = self.config.skip_children();
406 for (path, module) in modules::list_files(&krate, parse_session.codemap())? {
407 if (skip_children && path != main_file) || self.config.ignore().skip_file(&path) {
410 should_emit_verbose(main_file != FileName::Stdin, &self.config, || {
411 println!("Formatting {}", path)
413 let filemap = parse_session
415 .lookup_char_pos(module.inner.lo())
417 let big_snippet = filemap.src.as_ref().unwrap();
418 let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
419 let mut visitor = FmtVisitor::from_codemap(
425 // Format inner attributes if available.
426 if !krate.attrs.is_empty() && path == main_file {
427 visitor.skip_empty_lines(filemap.end_pos);
428 if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
429 visitor.push_rewrite(module.inner, None);
431 visitor.format_separate_mod(module, &*filemap);
434 visitor.last_pos = filemap.start_pos;
435 visitor.skip_empty_lines(filemap.end_pos);
436 visitor.format_separate_mod(module, &*filemap);
441 ::utils::count_newlines(&visitor.buffer)
444 // For some reason, the codemap does not include terminating
445 // newlines so we must add one on for each file. This is sad.
446 filemap::append_newline(&mut visitor.buffer);
451 &visitor.skipped_range,
455 self.replace_with_system_newlines(&mut visitor.buffer);
457 if visitor.macro_rewrite_failure {
458 self.summary.add_macro_foramt_failure();
461 formatted_file(self, path, visitor.buffer)?;
463 self.summary.mark_format_time();
465 if report.has_warnings() {
466 self.summary.add_formatting_error();
469 let report_errs = &report.internal.borrow().1;
470 if report_errs.has_check_errors {
471 self.summary.add_check_error();
473 if report_errs.has_operational_errors {
474 self.summary.add_operational_error();
481 fn make_parse_sess(&self, codemap: Rc<CodeMap>) -> ParseSess {
482 let tty_handler = if self.config.hide_parse_errors() {
483 let silent_emitter = Box::new(EmitterWriter::new(
484 Box::new(Vec::new()),
485 Some(codemap.clone()),
489 Handler::with_emitter(true, false, silent_emitter)
491 let supports_color = term::stderr().map_or(false, |term| term.supports_color());
492 let color_cfg = if supports_color {
497 Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
500 ParseSess::with_span_handler(tty_handler, codemap)
503 fn replace_with_system_newlines(&self, text: &mut String) -> () {
504 let style = if self.config.newline_style() == NewlineStyle::Native {
506 NewlineStyle::Windows
511 self.config.newline_style()
515 NewlineStyle::Unix => return,
516 NewlineStyle::Windows => {
517 let mut transformed = String::with_capacity(text.capacity());
518 for c in text.chars() {
520 '\n' => transformed.push_str("\r\n"),
522 c => transformed.push(c),
527 NewlineStyle::Native => unreachable!(),
532 /// A single span of changed lines, with 0 or more removed lines
533 /// and a vector of 0 or more inserted lines.
534 #[derive(Debug, PartialEq, Eq)]
535 pub(crate) struct ModifiedChunk {
536 /// The first to be removed from the original text
537 pub line_number_orig: u32,
538 /// The number of lines which have been replaced
539 pub lines_removed: u32,
541 pub lines: Vec<String>,
544 /// Set of changed sections of a file.
545 #[derive(Debug, PartialEq, Eq)]
546 pub(crate) struct ModifiedLines {
547 /// The set of changed chunks.
548 pub chunks: Vec<ModifiedChunk>,