]> git.lizzy.rs Git - rust.git/blob - src/formatting.rs
Refactoring: move code around in formatting
[rust.git] / src / formatting.rs
1 // High level formatting functions.
2
3 use std::collections::HashMap;
4 use std::io::{self, Write};
5 use std::panic::{catch_unwind, AssertUnwindSafe};
6 use std::rc::Rc;
7 use std::time::Duration;
8
9 use syntax::ast;
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};
14
15 use comment::{CharClasses, FullCodeCharKind};
16 use issues::BadIssueSeeker;
17 use visitor::{FmtVisitor, SnippetProvider};
18 use {filemap, modules, ErrorKind, FormatReport, Input, Session};
19
20 use config::{Config, FileName, NewlineStyle, Verbosity};
21
22 // A map of the files of a crate, with their new content
23 pub(crate) type FileMap = Vec<FileRecord>;
24
25 pub(crate) type FileRecord = (FileName, String);
26
27 pub(crate) struct FormattingError {
28     pub(crate) line: usize,
29     pub(crate) kind: ErrorKind,
30     is_comment: bool,
31     is_string: bool,
32     pub(crate) line_buffer: String,
33 }
34
35 impl FormattingError {
36     pub(crate) fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
37         FormattingError {
38             line: codemap.lookup_char_pos(span.lo()).line,
39             is_comment: kind.is_comment(),
40             kind,
41             is_string: false,
42             line_buffer: codemap
43                 .span_to_lines(*span)
44                 .ok()
45                 .and_then(|fl| {
46                     fl.file
47                         .get_line(fl.lines[0].line_index)
48                         .map(|l| l.into_owned())
49                 })
50                 .unwrap_or_else(|| String::new()),
51         }
52     }
53
54     pub(crate) fn msg_prefix(&self) -> &str {
55         match self.kind {
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:",
63         }
64     }
65
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"
70         } else {
71             ""
72         }
73     }
74
75     // (space, target)
76     pub(crate) fn format_len(&self) -> (usize, usize) {
77         match self.kind {
78             ErrorKind::LineOverflow(found, max) => (max, found - max),
79             ErrorKind::TrailingWhitespace
80             | ErrorKind::DeprecatedAttr
81             | ErrorKind::BadAttr
82             | ErrorKind::LostComment => {
83                 let trailing_ws_start = self
84                     .line_buffer
85                     .rfind(|c: char| !c.is_whitespace())
86                     .map(|pos| pos + 1)
87                     .unwrap_or(0);
88                 (
89                     trailing_ws_start,
90                     self.line_buffer.len() - trailing_ws_start,
91                 )
92             }
93             _ => unreachable!(),
94         }
95     }
96 }
97
98 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
99
100 #[derive(Default, Debug)]
101 pub(crate) struct ReportedErrors {
102     pub(crate) has_operational_errors: bool,
103     pub(crate) has_check_errors: bool,
104 }
105
106 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
107 where
108     F: Fn(),
109 {
110     if config.verbose() == Verbosity::Verbose && !is_stdin {
111         f();
112     }
113 }
114
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 {
117     skipped_range
118         .iter()
119         .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
120 }
121
122 fn should_report_error(
123     config: &Config,
124     char_kind: FullCodeCharKind,
125     is_string: bool,
126     error_kind: &ErrorKind,
127 ) -> bool {
128     let allow_error_report = if char_kind.is_comment() || is_string || error_kind.is_comment() {
129         config.error_on_unformatted()
130     } else {
131         true
132     };
133
134     match error_kind {
135         ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
136         ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
137         _ => true,
138     }
139 }
140
141 // Formatting done on a char by char or line by line basis.
142 // FIXME(#20) other stuff for parity with make tidy
143 fn format_lines(
144     text: &mut String,
145     name: &FileName,
146     skipped_range: &[(usize, usize)],
147     config: &Config,
148     report: &FormatReport,
149 ) {
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();
160
161     // Check license.
162     if let Some(ref license_template) = config.license_template {
163         if !license_template.is_match(text) {
164             errors.push(FormattingError {
165                 line: cur_line,
166                 kind: ErrorKind::LicenseCheck,
167                 is_comment: false,
168                 is_string: false,
169                 line_buffer: String::new(),
170             });
171         }
172     }
173
174     // Iterate over the chars in the file map.
175     for (kind, c) in CharClasses::new(text.chars()) {
176         if c == '\r' {
177             continue;
178         }
179
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 {
184                     line: cur_line,
185                     kind: ErrorKind::BadIssue(issue),
186                     is_comment: false,
187                     is_string: false,
188                     line_buffer: String::new(),
189                 });
190             }
191         }
192
193         if c == '\n' {
194             if format_line {
195                 // Check for (and record) trailing whitespace.
196                 if last_was_space {
197                     if should_report_error(config, kind, is_string, &ErrorKind::TrailingWhitespace)
198                         && !is_skipped_line(cur_line, skipped_range)
199                     {
200                         errors.push(FormattingError {
201                             line: cur_line,
202                             kind: ErrorKind::TrailingWhitespace,
203                             is_comment: kind.is_comment(),
204                             is_string: kind.is_string(),
205                             line_buffer: line_buffer.clone(),
206                         });
207                     }
208                     line_len -= 1;
209                 }
210
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)
216                 {
217                     errors.push(FormattingError {
218                         line: cur_line,
219                         kind: error_kind,
220                         is_comment: kind.is_comment(),
221                         is_string,
222                         line_buffer: line_buffer.clone(),
223                     });
224                 }
225             }
226
227             line_len = 0;
228             cur_line += 1;
229             format_line = config.file_lines().contains_line(name, cur_line);
230             newline_count += 1;
231             last_was_space = false;
232             line_buffer.clear();
233             is_string = false;
234         } else {
235             newline_count = 0;
236             line_len += if c == '\t' { config.tab_spaces() } else { 1 };
237             last_was_space = c.is_whitespace();
238             line_buffer.push(c);
239             if kind.is_string() {
240                 is_string = true;
241             }
242         }
243     }
244
245     if newline_count > 1 {
246         debug!("track truncate: {} {}", text.len(), newline_count);
247         let line = text.len() - newline_count + 1;
248         text.truncate(line);
249     }
250
251     report.append(name.clone(), errors);
252 }
253
254 fn parse_input<'sess>(
255     input: Input,
256     parse_session: &'sess ParseSess,
257     config: &Config,
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(
262             parse_session,
263             syntax::codemap::FileName::Custom("stdin".to_owned()),
264             text,
265         ),
266     };
267
268     parser.cfg_mods = false;
269     if config.skip_children() {
270         parser.recurse_into_file_modules = false;
271     }
272
273     let mut parser = AssertUnwindSafe(parser);
274     let result = catch_unwind(move || parser.0.parse_crate_mod());
275
276     match result {
277         Ok(Ok(c)) => {
278             if parse_session.span_diagnostic.has_errors() {
279                 // Bail out if the parser recovered from an error.
280                 Err(ParseError::Recovered)
281             } else {
282                 Ok(c)
283             }
284         }
285         Ok(Err(e)) => Err(ParseError::Error(e)),
286         Err(_) => Err(ParseError::Panic),
287     }
288 }
289
290 /// All the ways that parsing can fail.
291 enum ParseError<'sess> {
292     /// There was an error, but the parser recovered.
293     Recovered,
294     /// There was an error (supplied) and parsing failed.
295     Error(DiagnosticBuilder<'sess>),
296     /// The parser panicked.
297     Panic,
298 }
299
300 impl<'b, T: Write + 'b> Session<'b, T> {
301     pub(crate) fn format_input_inner(
302         &mut self,
303         input: Input,
304     ) -> Result<(FileMap, FormatReport), ErrorKind> {
305         syntax_pos::hygiene::set_default_edition(self.config.edition().to_libsyntax_pos_edition());
306
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));
312                 }
313             }
314             return Ok((FileMap::new(), FormatReport::new()));
315         }
316
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(),
326                     Err(e) => {
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());
330                     }
331                     _ => {}
332                 }
333             }
334
335             filemap.push((path, result));
336             Ok(())
337         });
338
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
342             }
343
344             println!(
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()),
348             )
349         });
350
351         format_result.map(|r| (filemap, r))
352     }
353
354     // TODO name, only uses config and summary
355     // TODO move timing from summary to Session
356     // Formatting which depends on the AST.
357     fn format_ast<F>(
358         &mut self,
359         input: Input,
360         mut formatted_file: F,
361     ) -> Result<FormatReport, ErrorKind>
362     where
363         F: FnMut(&mut Session<T>, FileName, String) -> Result<(), ErrorKind>,
364     {
365         let main_file = match input {
366             Input::File(ref file) => FileName::Real(file.clone()),
367             Input::Text(..) => FileName::Stdin,
368         };
369
370         // Parse the crate.
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) {
374             Ok(krate) => krate,
375             Err(err) => {
376                 match err {
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")
384                         });
385                     }
386                     ParseError::Recovered => {}
387                 }
388                 self.summary.add_parsing_error();
389                 return Err(ErrorKind::ParseError);
390             }
391         };
392         self.summary.mark_parse_time();
393
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()),
398             false,
399             false,
400         ));
401         parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
402
403         let report = FormatReport::new();
404
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) {
408                 continue;
409             }
410             should_emit_verbose(main_file != FileName::Stdin, &self.config, || {
411                 println!("Formatting {}", path)
412             });
413             let filemap = parse_session
414                 .codemap()
415                 .lookup_char_pos(module.inner.lo())
416                 .file;
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(
420                 &parse_session,
421                 &self.config,
422                 &snippet_provider,
423                 report.clone(),
424             );
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);
430                 } else {
431                     visitor.format_separate_mod(module, &*filemap);
432                 }
433             } else {
434                 visitor.last_pos = filemap.start_pos;
435                 visitor.skip_empty_lines(filemap.end_pos);
436                 visitor.format_separate_mod(module, &*filemap);
437             };
438
439             debug_assert_eq!(
440                 visitor.line_number,
441                 ::utils::count_newlines(&visitor.buffer)
442             );
443
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);
447
448             format_lines(
449                 &mut visitor.buffer,
450                 &path,
451                 &visitor.skipped_range,
452                 &self.config,
453                 &report,
454             );
455             self.replace_with_system_newlines(&mut visitor.buffer);
456
457             if visitor.macro_rewrite_failure {
458                 self.summary.add_macro_foramt_failure();
459             }
460
461             formatted_file(self, path, visitor.buffer)?;
462         }
463         self.summary.mark_format_time();
464
465         if report.has_warnings() {
466             self.summary.add_formatting_error();
467         }
468         {
469             let report_errs = &report.internal.borrow().1;
470             if report_errs.has_check_errors {
471                 self.summary.add_check_error();
472             }
473             if report_errs.has_operational_errors {
474                 self.summary.add_operational_error();
475             }
476         }
477
478         Ok(report)
479     }
480
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()),
486                 false,
487                 false,
488             ));
489             Handler::with_emitter(true, false, silent_emitter)
490         } else {
491             let supports_color = term::stderr().map_or(false, |term| term.supports_color());
492             let color_cfg = if supports_color {
493                 ColorConfig::Auto
494             } else {
495                 ColorConfig::Never
496             };
497             Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
498         };
499
500         ParseSess::with_span_handler(tty_handler, codemap)
501     }
502
503     fn replace_with_system_newlines(&self, text: &mut String) -> () {
504         let style = if self.config.newline_style() == NewlineStyle::Native {
505             if cfg!(windows) {
506                 NewlineStyle::Windows
507             } else {
508                 NewlineStyle::Unix
509             }
510         } else {
511             self.config.newline_style()
512         };
513
514         match style {
515             NewlineStyle::Unix => return,
516             NewlineStyle::Windows => {
517                 let mut transformed = String::with_capacity(text.capacity());
518                 for c in text.chars() {
519                     match c {
520                         '\n' => transformed.push_str("\r\n"),
521                         '\r' => continue,
522                         c => transformed.push(c),
523                     }
524                 }
525                 *text = transformed;
526             }
527             NewlineStyle::Native => unreachable!(),
528         }
529     }
530 }
531
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,
540     /// The new lines
541     pub lines: Vec<String>,
542 }
543
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>,
549 }