]> git.lizzy.rs Git - rust.git/blob - src/formatting.rs
Refactoring: move `format_project` and `Timer` out of Session
[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, Instant};
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 config::{Config, FileName, NewlineStyle, Verbosity};
17 use issues::BadIssueSeeker;
18 use visitor::{FmtVisitor, SnippetProvider};
19 use {filemap, modules, ErrorKind, FormatReport, Input, Session};
20
21 // A map of the files of a crate, with their new content
22 pub(crate) type FileMap = Vec<FileRecord>;
23
24 pub(crate) type FileRecord = (FileName, String);
25
26 pub(crate) struct FormattingError {
27     pub(crate) line: usize,
28     pub(crate) kind: ErrorKind,
29     is_comment: bool,
30     is_string: bool,
31     pub(crate) line_buffer: String,
32 }
33
34 impl FormattingError {
35     pub(crate) fn from_span(span: &Span, codemap: &CodeMap, kind: ErrorKind) -> FormattingError {
36         FormattingError {
37             line: codemap.lookup_char_pos(span.lo()).line,
38             is_comment: kind.is_comment(),
39             kind,
40             is_string: false,
41             line_buffer: codemap
42                 .span_to_lines(*span)
43                 .ok()
44                 .and_then(|fl| {
45                     fl.file
46                         .get_line(fl.lines[0].line_index)
47                         .map(|l| l.into_owned())
48                 })
49                 .unwrap_or_else(|| String::new()),
50         }
51     }
52
53     pub(crate) fn msg_prefix(&self) -> &str {
54         match self.kind {
55             ErrorKind::LineOverflow(..)
56             | ErrorKind::TrailingWhitespace
57             | ErrorKind::IoError(_)
58             | ErrorKind::ParseError
59             | ErrorKind::LostComment => "internal error:",
60             ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
61             ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
62         }
63     }
64
65     pub(crate) fn msg_suffix(&self) -> &str {
66         if self.is_comment || self.is_string {
67             "set `error_on_unformatted = false` to suppress \
68              the warning against comments or string literals\n"
69         } else {
70             ""
71         }
72     }
73
74     // (space, target)
75     pub(crate) fn format_len(&self) -> (usize, usize) {
76         match self.kind {
77             ErrorKind::LineOverflow(found, max) => (max, found - max),
78             ErrorKind::TrailingWhitespace
79             | ErrorKind::DeprecatedAttr
80             | ErrorKind::BadAttr
81             | ErrorKind::LostComment => {
82                 let trailing_ws_start = self
83                     .line_buffer
84                     .rfind(|c: char| !c.is_whitespace())
85                     .map(|pos| pos + 1)
86                     .unwrap_or(0);
87                 (
88                     trailing_ws_start,
89                     self.line_buffer.len() - trailing_ws_start,
90                 )
91             }
92             _ => unreachable!(),
93         }
94     }
95 }
96
97 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
98
99 #[derive(Default, Debug)]
100 pub(crate) struct ReportedErrors {
101     pub(crate) has_operational_errors: bool,
102     pub(crate) has_check_errors: bool,
103 }
104
105 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
106 where
107     F: Fn(),
108 {
109     if config.verbose() == Verbosity::Verbose && !is_stdin {
110         f();
111     }
112 }
113
114 /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
115 fn is_skipped_line(line_number: usize, skipped_range: &[(usize, usize)]) -> bool {
116     skipped_range
117         .iter()
118         .any(|&(lo, hi)| lo <= line_number && line_number <= hi)
119 }
120
121 fn should_report_error(
122     config: &Config,
123     char_kind: FullCodeCharKind,
124     is_string: bool,
125     error_kind: &ErrorKind,
126 ) -> bool {
127     let allow_error_report = if char_kind.is_comment() || is_string || error_kind.is_comment() {
128         config.error_on_unformatted()
129     } else {
130         true
131     };
132
133     match error_kind {
134         ErrorKind::LineOverflow(..) => config.error_on_line_overflow() && allow_error_report,
135         ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
136         _ => true,
137     }
138 }
139
140 // Formatting done on a char by char or line by line basis.
141 // FIXME(#20) other stuff for parity with make tidy
142 fn format_lines(
143     text: &mut String,
144     name: &FileName,
145     skipped_range: &[(usize, usize)],
146     config: &Config,
147     report: &FormatReport,
148 ) {
149     let mut last_was_space = false;
150     let mut line_len = 0;
151     let mut cur_line = 1;
152     let mut newline_count = 0;
153     let mut errors = vec![];
154     let mut issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
155     let mut line_buffer = String::with_capacity(config.max_width() * 2);
156     let mut is_string = false; // true if the current line contains a string literal.
157     let mut format_line = config.file_lines().contains_line(name, cur_line);
158     let allow_issue_seek = !issue_seeker.is_disabled();
159
160     // Check license.
161     if let Some(ref license_template) = config.license_template {
162         if !license_template.is_match(text) {
163             errors.push(FormattingError {
164                 line: cur_line,
165                 kind: ErrorKind::LicenseCheck,
166                 is_comment: false,
167                 is_string: false,
168                 line_buffer: String::new(),
169             });
170         }
171     }
172
173     // Iterate over the chars in the file map.
174     for (kind, c) in CharClasses::new(text.chars()) {
175         if c == '\r' {
176             continue;
177         }
178
179         if allow_issue_seek && format_line {
180             // Add warnings for bad todos/ fixmes
181             if let Some(issue) = issue_seeker.inspect(c) {
182                 errors.push(FormattingError {
183                     line: cur_line,
184                     kind: ErrorKind::BadIssue(issue),
185                     is_comment: false,
186                     is_string: false,
187                     line_buffer: String::new(),
188                 });
189             }
190         }
191
192         if c == '\n' {
193             if format_line {
194                 // Check for (and record) trailing whitespace.
195                 if last_was_space {
196                     if should_report_error(config, kind, is_string, &ErrorKind::TrailingWhitespace)
197                         && !is_skipped_line(cur_line, skipped_range)
198                     {
199                         errors.push(FormattingError {
200                             line: cur_line,
201                             kind: ErrorKind::TrailingWhitespace,
202                             is_comment: kind.is_comment(),
203                             is_string: kind.is_string(),
204                             line_buffer: line_buffer.clone(),
205                         });
206                     }
207                     line_len -= 1;
208                 }
209
210                 // Check for any line width errors we couldn't correct.
211                 let error_kind = ErrorKind::LineOverflow(line_len, config.max_width());
212                 if line_len > config.max_width()
213                     && !is_skipped_line(cur_line, skipped_range)
214                     && should_report_error(config, kind, is_string, &error_kind)
215                 {
216                     errors.push(FormattingError {
217                         line: cur_line,
218                         kind: error_kind,
219                         is_comment: kind.is_comment(),
220                         is_string,
221                         line_buffer: line_buffer.clone(),
222                     });
223                 }
224             }
225
226             line_len = 0;
227             cur_line += 1;
228             format_line = config.file_lines().contains_line(name, cur_line);
229             newline_count += 1;
230             last_was_space = false;
231             line_buffer.clear();
232             is_string = false;
233         } else {
234             newline_count = 0;
235             line_len += if c == '\t' { config.tab_spaces() } else { 1 };
236             last_was_space = c.is_whitespace();
237             line_buffer.push(c);
238             if kind.is_string() {
239                 is_string = true;
240             }
241         }
242     }
243
244     if newline_count > 1 {
245         debug!("track truncate: {} {}", text.len(), newline_count);
246         let line = text.len() - newline_count + 1;
247         text.truncate(line);
248     }
249
250     report.append(name.clone(), errors);
251 }
252
253 fn parse_input<'sess>(
254     input: Input,
255     parse_session: &'sess ParseSess,
256     config: &Config,
257 ) -> Result<ast::Crate, ParseError<'sess>> {
258     let mut parser = match input {
259         Input::File(file) => parse::new_parser_from_file(parse_session, &file),
260         Input::Text(text) => parse::new_parser_from_source_str(
261             parse_session,
262             syntax::codemap::FileName::Custom("stdin".to_owned()),
263             text,
264         ),
265     };
266
267     parser.cfg_mods = false;
268     if config.skip_children() {
269         parser.recurse_into_file_modules = false;
270     }
271
272     let mut parser = AssertUnwindSafe(parser);
273     let result = catch_unwind(move || parser.0.parse_crate_mod());
274
275     match result {
276         Ok(Ok(c)) => {
277             if parse_session.span_diagnostic.has_errors() {
278                 // Bail out if the parser recovered from an error.
279                 Err(ParseError::Recovered)
280             } else {
281                 Ok(c)
282             }
283         }
284         Ok(Err(e)) => Err(ParseError::Error(e)),
285         Err(_) => Err(ParseError::Panic),
286     }
287 }
288
289 /// All the ways that parsing can fail.
290 enum ParseError<'sess> {
291     /// There was an error, but the parser recovered.
292     Recovered,
293     /// There was an error (supplied) and parsing failed.
294     Error(DiagnosticBuilder<'sess>),
295     /// The parser panicked.
296     Panic,
297 }
298
299 impl<'b, T: Write + 'b> Session<'b, T> {
300     pub(crate) fn format_input_inner(
301         &mut self,
302         input: Input,
303     ) -> Result<(FileMap, FormatReport), ErrorKind> {
304         syntax_pos::hygiene::set_default_edition(self.config.edition().to_libsyntax_pos_edition());
305
306         if self.config.disable_all_formatting() {
307             // When the input is from stdin, echo back the input.
308             if let Input::Text(ref buf) = input {
309                 if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
310                     return Err(From::from(e));
311                 }
312             }
313             return Ok((FileMap::new(), FormatReport::new()));
314         }
315
316         let mut filemap = FileMap::new();
317         let config = &self.config.clone();
318         let format_result = format_project(input, config, |path, mut result| {
319             if let Some(ref mut out) = self.out {
320                 match filemap::write_file(&mut result, &path, out, &self.config) {
321                     Ok(b) if b => self.summary.add_diff(),
322                     Err(e) => {
323                         // Create a new error with path_str to help users see which files failed
324                         let err_msg = format!("{}: {}", path, e);
325                         return Err(io::Error::new(e.kind(), err_msg).into());
326                     }
327                     _ => {}
328                 }
329             }
330
331             filemap.push((path, result));
332             Ok(())
333         });
334
335         format_result.map(|(result, summary)| {
336             self.summary.add(summary);
337             (filemap, result)
338         })
339     }
340 }
341
342 fn format_project<F>(
343     input: Input,
344     config: &Config,
345     mut formatted_file: F,
346 ) -> Result<(FormatReport, Summary), ErrorKind>
347 where
348     F: FnMut(FileName, String) -> Result<(), ErrorKind>,
349 {
350     let mut summary = Summary::default();
351     let mut timer = Timer::Initialized(Instant::now());
352
353     let input_is_stdin = input.is_text();
354     let main_file = match input {
355         Input::File(ref file) => FileName::Real(file.clone()),
356         Input::Text(..) => FileName::Stdin,
357     };
358
359     // Parse the crate.
360     let codemap = Rc::new(CodeMap::new(FilePathMapping::empty()));
361     let mut parse_session = make_parse_sess(codemap.clone(), config);
362     let krate = match parse_input(input, &parse_session, config) {
363         Ok(krate) => krate,
364         Err(err) => {
365             match err {
366                 ParseError::Error(mut diagnostic) => diagnostic.emit(),
367                 ParseError::Panic => {
368                     // Note that if you see this message and want more information,
369                     // then go to `parse_input` and run the parse function without
370                     // `catch_unwind` so rustfmt panics and you can get a backtrace.
371                     should_emit_verbose(main_file != FileName::Stdin, config, || {
372                         println!("The Rust parser panicked")
373                     });
374                 }
375                 ParseError::Recovered => {}
376             }
377             summary.add_parsing_error();
378             return Err(ErrorKind::ParseError);
379         }
380     };
381     timer = timer.done_parsing();
382
383     // Suppress error output if we have to do any further parsing.
384     let silent_emitter = Box::new(EmitterWriter::new(
385         Box::new(Vec::new()),
386         Some(codemap.clone()),
387         false,
388         false,
389     ));
390     parse_session.span_diagnostic = Handler::with_emitter(true, false, silent_emitter);
391
392     let report = FormatReport::new();
393
394     let skip_children = config.skip_children();
395     for (path, module) in modules::list_files(&krate, parse_session.codemap())? {
396         if (skip_children && path != main_file) || config.ignore().skip_file(&path) {
397             continue;
398         }
399         should_emit_verbose(main_file != FileName::Stdin, config, || {
400             println!("Formatting {}", path)
401         });
402         let filemap = parse_session
403             .codemap()
404             .lookup_char_pos(module.inner.lo())
405             .file;
406         let big_snippet = filemap.src.as_ref().unwrap();
407         let snippet_provider = SnippetProvider::new(filemap.start_pos, big_snippet);
408         let mut visitor =
409             FmtVisitor::from_codemap(&parse_session, config, &snippet_provider, report.clone());
410         // Format inner attributes if available.
411         if !krate.attrs.is_empty() && path == main_file {
412             visitor.skip_empty_lines(filemap.end_pos);
413             if visitor.visit_attrs(&krate.attrs, ast::AttrStyle::Inner) {
414                 visitor.push_rewrite(module.inner, None);
415             } else {
416                 visitor.format_separate_mod(module, &*filemap);
417             }
418         } else {
419             visitor.last_pos = filemap.start_pos;
420             visitor.skip_empty_lines(filemap.end_pos);
421             visitor.format_separate_mod(module, &*filemap);
422         };
423
424         debug_assert_eq!(
425             visitor.line_number,
426             ::utils::count_newlines(&visitor.buffer)
427         );
428
429         // For some reason, the codemap does not include terminating
430         // newlines so we must add one on for each file. This is sad.
431         filemap::append_newline(&mut visitor.buffer);
432
433         format_lines(
434             &mut visitor.buffer,
435             &path,
436             &visitor.skipped_range,
437             config,
438             &report,
439         );
440         replace_with_system_newlines(&mut visitor.buffer, config);
441
442         if visitor.macro_rewrite_failure {
443             summary.add_macro_format_failure();
444         }
445
446         formatted_file(path, visitor.buffer)?;
447     }
448     timer = timer.done_formatting();
449
450     should_emit_verbose(input_is_stdin, config, || {
451         println!(
452             "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
453             timer.get_parse_time(),
454             timer.get_format_time(),
455         )
456     });
457
458     if report.has_warnings() {
459         summary.add_formatting_error();
460     }
461     {
462         let report_errs = &report.internal.borrow().1;
463         if report_errs.has_check_errors {
464             summary.add_check_error();
465         }
466         if report_errs.has_operational_errors {
467             summary.add_operational_error();
468         }
469     }
470
471     Ok((report, summary))
472 }
473
474 fn make_parse_sess(codemap: Rc<CodeMap>, config: &Config) -> ParseSess {
475     let tty_handler = if config.hide_parse_errors() {
476         let silent_emitter = Box::new(EmitterWriter::new(
477             Box::new(Vec::new()),
478             Some(codemap.clone()),
479             false,
480             false,
481         ));
482         Handler::with_emitter(true, false, silent_emitter)
483     } else {
484         let supports_color = term::stderr().map_or(false, |term| term.supports_color());
485         let color_cfg = if supports_color {
486             ColorConfig::Auto
487         } else {
488             ColorConfig::Never
489         };
490         Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
491     };
492
493     ParseSess::with_span_handler(tty_handler, codemap)
494 }
495
496 fn replace_with_system_newlines(text: &mut String, config: &Config) -> () {
497     let style = if config.newline_style() == NewlineStyle::Native {
498         if cfg!(windows) {
499             NewlineStyle::Windows
500         } else {
501             NewlineStyle::Unix
502         }
503     } else {
504         config.newline_style()
505     };
506
507     match style {
508         NewlineStyle::Unix => return,
509         NewlineStyle::Windows => {
510             let mut transformed = String::with_capacity(text.capacity());
511             for c in text.chars() {
512                 match c {
513                     '\n' => transformed.push_str("\r\n"),
514                     '\r' => continue,
515                     c => transformed.push(c),
516                 }
517             }
518             *text = transformed;
519         }
520         NewlineStyle::Native => unreachable!(),
521     }
522 }
523
524 /// A single span of changed lines, with 0 or more removed lines
525 /// and a vector of 0 or more inserted lines.
526 #[derive(Debug, PartialEq, Eq)]
527 pub(crate) struct ModifiedChunk {
528     /// The first to be removed from the original text
529     pub line_number_orig: u32,
530     /// The number of lines which have been replaced
531     pub lines_removed: u32,
532     /// The new lines
533     pub lines: Vec<String>,
534 }
535
536 /// Set of changed sections of a file.
537 #[derive(Debug, PartialEq, Eq)]
538 pub(crate) struct ModifiedLines {
539     /// The set of changed chunks.
540     pub chunks: Vec<ModifiedChunk>,
541 }
542
543 #[derive(Clone, Copy, Debug)]
544 enum Timer {
545     Initialized(Instant),
546     DoneParsing(Instant, Instant),
547     DoneFormatting(Instant, Instant, Instant),
548 }
549
550 impl Timer {
551     fn done_parsing(self) -> Self {
552         match self {
553             Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
554             _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
555         }
556     }
557
558     fn done_formatting(self) -> Self {
559         match self {
560             Timer::DoneParsing(init_time, parse_time) => {
561                 Timer::DoneFormatting(init_time, parse_time, Instant::now())
562             }
563             _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
564         }
565     }
566
567     /// Returns the time it took to parse the source files in seconds.
568     fn get_parse_time(&self) -> f32 {
569         match *self {
570             Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
571                 // This should never underflow since `Instant::now()` guarantees monotonicity.
572                 Self::duration_to_f32(parse_time.duration_since(init))
573             }
574             Timer::Initialized(..) => unreachable!(),
575         }
576     }
577
578     /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
579     /// not included.
580     fn get_format_time(&self) -> f32 {
581         match *self {
582             Timer::DoneFormatting(_init, parse_time, format_time) => {
583                 Self::duration_to_f32(format_time.duration_since(parse_time))
584             }
585             Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
586         }
587     }
588
589     fn duration_to_f32(d: Duration) -> f32 {
590         d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
591     }
592 }
593
594 /// A summary of a Rustfmt run.
595 #[derive(Debug, Default, Clone, Copy)]
596 pub struct Summary {
597     // Encountered e.g. an IO error.
598     has_operational_errors: bool,
599
600     // Failed to reformat code because of parsing errors.
601     has_parsing_errors: bool,
602
603     // Code is valid, but it is impossible to format it properly.
604     has_formatting_errors: bool,
605
606     // Code contains macro call that was unable to format.
607     pub(crate) has_macro_format_failure: bool,
608
609     // Failed a check, such as the license check or other opt-in checking.
610     has_check_errors: bool,
611
612     /// Formatted code differs from existing code (--check only).
613     pub has_diff: bool,
614 }
615
616 impl Summary {
617     pub fn has_operational_errors(&self) -> bool {
618         self.has_operational_errors
619     }
620
621     pub fn has_parsing_errors(&self) -> bool {
622         self.has_parsing_errors
623     }
624
625     pub fn has_formatting_errors(&self) -> bool {
626         self.has_formatting_errors
627     }
628
629     pub fn has_check_errors(&self) -> bool {
630         self.has_check_errors
631     }
632
633     pub(crate) fn has_macro_formatting_failure(&self) -> bool {
634         self.has_macro_format_failure
635     }
636
637     pub fn add_operational_error(&mut self) {
638         self.has_operational_errors = true;
639     }
640
641     pub(crate) fn add_parsing_error(&mut self) {
642         self.has_parsing_errors = true;
643     }
644
645     pub(crate) fn add_formatting_error(&mut self) {
646         self.has_formatting_errors = true;
647     }
648
649     pub(crate) fn add_check_error(&mut self) {
650         self.has_check_errors = true;
651     }
652
653     pub(crate) fn add_diff(&mut self) {
654         self.has_diff = true;
655     }
656
657     pub(crate) fn add_macro_format_failure(&mut self) {
658         self.has_macro_format_failure = true;
659     }
660
661     pub fn has_no_errors(&self) -> bool {
662         !(self.has_operational_errors
663             || self.has_parsing_errors
664             || self.has_formatting_errors
665             || self.has_diff)
666     }
667
668     /// Combine two summaries together.
669     pub fn add(&mut self, other: Summary) {
670         self.has_operational_errors |= other.has_operational_errors;
671         self.has_formatting_errors |= other.has_formatting_errors;
672         self.has_macro_format_failure |= other.has_macro_format_failure;
673         self.has_parsing_errors |= other.has_parsing_errors;
674         self.has_check_errors |= other.has_check_errors;
675         self.has_diff |= other.has_diff;
676     }
677 }