]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/formatting.rs
Auto merge of #89970 - jackh726:gats_diagnostics, r=nikomatsakis
[rust.git] / src / tools / rustfmt / src / formatting.rs
1 // High level formatting functions.
2
3 use std::collections::HashMap;
4 use std::io::{self, Write};
5 use std::time::{Duration, Instant};
6
7 use rustc_ast::ast;
8 use rustc_span::Span;
9
10 use self::newline_style::apply_newline_style;
11 use crate::comment::{CharClasses, FullCodeCharKind};
12 use crate::config::{Config, FileName, Verbosity};
13 use crate::formatting::generated::is_generated_file;
14 use crate::issues::BadIssueSeeker;
15 use crate::modules::Module;
16 use crate::syntux::parser::{DirectoryOwnership, Parser, ParserError};
17 use crate::syntux::session::ParseSess;
18 use crate::utils::count_newlines;
19 use crate::visitor::FmtVisitor;
20 use crate::{modules, source_file, ErrorKind, FormatReport, Input, Session};
21
22 mod generated;
23 mod newline_style;
24
25 // A map of the files of a crate, with their new content
26 pub(crate) type SourceFile = Vec<FileRecord>;
27 pub(crate) type FileRecord = (FileName, String);
28
29 impl<'b, T: Write + 'b> Session<'b, T> {
30     pub(crate) fn format_input_inner(
31         &mut self,
32         input: Input,
33         is_macro_def: bool,
34     ) -> Result<FormatReport, ErrorKind> {
35         if !self.config.version_meets_requirement() {
36             return Err(ErrorKind::VersionMismatch);
37         }
38
39         rustc_span::create_session_if_not_set_then(self.config.edition().into(), |_| {
40             if self.config.disable_all_formatting() {
41                 // When the input is from stdin, echo back the input.
42                 if let Input::Text(ref buf) = input {
43                     if let Err(e) = io::stdout().write_all(buf.as_bytes()) {
44                         return Err(From::from(e));
45                     }
46                 }
47                 return Ok(FormatReport::new());
48             }
49
50             let config = &self.config.clone();
51             let format_result = format_project(input, config, self, is_macro_def);
52
53             format_result.map(|report| {
54                 self.errors.add(&report.internal.borrow().1);
55                 report
56             })
57         })
58     }
59 }
60
61 // Format an entire crate (or subset of the module tree).
62 fn format_project<T: FormatHandler>(
63     input: Input,
64     config: &Config,
65     handler: &mut T,
66     is_macro_def: bool,
67 ) -> Result<FormatReport, ErrorKind> {
68     let mut timer = Timer::start();
69
70     let main_file = input.file_name();
71     let input_is_stdin = main_file == FileName::Stdin;
72
73     let parse_session = ParseSess::new(config)?;
74     if config.skip_children() && parse_session.ignore_file(&main_file) {
75         return Ok(FormatReport::new());
76     }
77
78     // Parse the crate.
79     let mut report = FormatReport::new();
80     let directory_ownership = input.to_directory_ownership();
81     let krate = match Parser::parse_crate(input, &parse_session) {
82         Ok(krate) => krate,
83         // Surface parse error via Session (errors are merged there from report)
84         Err(e) => {
85             let forbid_verbose = input_is_stdin || e != ParserError::ParsePanicError;
86             should_emit_verbose(forbid_verbose, config, || {
87                 eprintln!("The Rust parser panicked");
88             });
89             report.add_parsing_error();
90             return Ok(report);
91         }
92     };
93
94     let mut context = FormatContext::new(&krate, report, parse_session, config, handler);
95     let files = modules::ModResolver::new(
96         &context.parse_session,
97         directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaBlock),
98         !input_is_stdin && !config.skip_children(),
99     )
100     .visit_crate(&krate)?;
101
102     timer = timer.done_parsing();
103
104     // Suppress error output if we have to do any further parsing.
105     context.parse_session.set_silent_emitter();
106
107     for (path, module) in files {
108         let source_file = context.parse_session.span_to_file_contents(module.span);
109         let src = source_file.src.as_ref().expect("SourceFile without src");
110
111         let should_ignore = (!input_is_stdin && context.ignore_file(&path))
112             || (!config.format_generated_files() && is_generated_file(src));
113
114         if (config.skip_children() && path != main_file) || should_ignore {
115             continue;
116         }
117         should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
118         context.format_file(path, &module, is_macro_def)?;
119     }
120     timer = timer.done_formatting();
121
122     should_emit_verbose(input_is_stdin, config, || {
123         println!(
124             "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
125             timer.get_parse_time(),
126             timer.get_format_time(),
127         )
128     });
129
130     Ok(context.report)
131 }
132
133 // Used for formatting files.
134 #[derive(new)]
135 struct FormatContext<'a, T: FormatHandler> {
136     krate: &'a ast::Crate,
137     report: FormatReport,
138     parse_session: ParseSess,
139     config: &'a Config,
140     handler: &'a mut T,
141 }
142
143 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
144     fn ignore_file(&self, path: &FileName) -> bool {
145         self.parse_session.ignore_file(path)
146     }
147
148     // Formats a single file/module.
149     fn format_file(
150         &mut self,
151         path: FileName,
152         module: &Module<'_>,
153         is_macro_def: bool,
154     ) -> Result<(), ErrorKind> {
155         let snippet_provider = self.parse_session.snippet_provider(module.span);
156         let mut visitor = FmtVisitor::from_parse_sess(
157             &self.parse_session,
158             &self.config,
159             &snippet_provider,
160             self.report.clone(),
161         );
162         visitor.skip_context.update_with_attrs(&self.krate.attrs);
163         visitor.is_macro_def = is_macro_def;
164         visitor.last_pos = snippet_provider.start_pos();
165         visitor.skip_empty_lines(snippet_provider.end_pos());
166         visitor.format_separate_mod(module, snippet_provider.end_pos());
167
168         debug_assert_eq!(
169             visitor.line_number,
170             count_newlines(&visitor.buffer),
171             "failed in format_file visitor.buffer:\n {:?}",
172             &visitor.buffer
173         );
174
175         // For some reason, the source_map does not include terminating
176         // newlines so we must add one on for each file. This is sad.
177         source_file::append_newline(&mut visitor.buffer);
178
179         format_lines(
180             &mut visitor.buffer,
181             &path,
182             &visitor.skipped_range.borrow(),
183             &self.config,
184             &self.report,
185         );
186
187         apply_newline_style(
188             self.config.newline_style(),
189             &mut visitor.buffer,
190             snippet_provider.entire_snippet(),
191         );
192
193         if visitor.macro_rewrite_failure {
194             self.report.add_macro_format_failure();
195         }
196         self.report
197             .add_non_formatted_ranges(visitor.skipped_range.borrow().clone());
198
199         self.handler.handle_formatted_file(
200             &self.parse_session,
201             path,
202             visitor.buffer.to_owned(),
203             &mut self.report,
204         )
205     }
206 }
207
208 // Handle the results of formatting.
209 trait FormatHandler {
210     fn handle_formatted_file(
211         &mut self,
212         parse_session: &ParseSess,
213         path: FileName,
214         result: String,
215         report: &mut FormatReport,
216     ) -> Result<(), ErrorKind>;
217 }
218
219 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
220     // Called for each formatted file.
221     fn handle_formatted_file(
222         &mut self,
223         parse_session: &ParseSess,
224         path: FileName,
225         result: String,
226         report: &mut FormatReport,
227     ) -> Result<(), ErrorKind> {
228         if let Some(ref mut out) = self.out {
229             match source_file::write_file(
230                 Some(parse_session),
231                 &path,
232                 &result,
233                 out,
234                 &mut *self.emitter,
235                 self.config.newline_style(),
236             ) {
237                 Ok(ref result) if result.has_diff => report.add_diff(),
238                 Err(e) => {
239                     // Create a new error with path_str to help users see which files failed
240                     let err_msg = format!("{}: {}", path, e);
241                     return Err(io::Error::new(e.kind(), err_msg).into());
242                 }
243                 _ => {}
244             }
245         }
246
247         self.source_file.push((path, result));
248         Ok(())
249     }
250 }
251
252 pub(crate) struct FormattingError {
253     pub(crate) line: usize,
254     pub(crate) kind: ErrorKind,
255     is_comment: bool,
256     is_string: bool,
257     pub(crate) line_buffer: String,
258 }
259
260 impl FormattingError {
261     pub(crate) fn from_span(
262         span: Span,
263         parse_sess: &ParseSess,
264         kind: ErrorKind,
265     ) -> FormattingError {
266         FormattingError {
267             line: parse_sess.line_of_byte_pos(span.lo()),
268             is_comment: kind.is_comment(),
269             kind,
270             is_string: false,
271             line_buffer: parse_sess.span_to_first_line_string(span),
272         }
273     }
274
275     pub(crate) fn is_internal(&self) -> bool {
276         match self.kind {
277             ErrorKind::LineOverflow(..)
278             | ErrorKind::TrailingWhitespace
279             | ErrorKind::IoError(_)
280             | ErrorKind::ParseError
281             | ErrorKind::LostComment => true,
282             _ => false,
283         }
284     }
285
286     pub(crate) fn msg_suffix(&self) -> &str {
287         if self.is_comment || self.is_string {
288             "set `error_on_unformatted = false` to suppress \
289              the warning against comments or string literals\n"
290         } else {
291             ""
292         }
293     }
294
295     // (space, target)
296     pub(crate) fn format_len(&self) -> (usize, usize) {
297         match self.kind {
298             ErrorKind::LineOverflow(found, max) => (max, found - max),
299             ErrorKind::TrailingWhitespace
300             | ErrorKind::DeprecatedAttr
301             | ErrorKind::BadIssue(_)
302             | ErrorKind::BadAttr
303             | ErrorKind::LostComment
304             | ErrorKind::LicenseCheck => {
305                 let trailing_ws_start = self
306                     .line_buffer
307                     .rfind(|c: char| !c.is_whitespace())
308                     .map(|pos| pos + 1)
309                     .unwrap_or(0);
310                 (
311                     trailing_ws_start,
312                     self.line_buffer.len() - trailing_ws_start,
313                 )
314             }
315             _ => unreachable!(),
316         }
317     }
318 }
319
320 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
321
322 #[derive(Default, Debug, PartialEq)]
323 pub(crate) struct ReportedErrors {
324     // Encountered e.g., an IO error.
325     pub(crate) has_operational_errors: bool,
326
327     // Failed to reformat code because of parsing errors.
328     pub(crate) has_parsing_errors: bool,
329
330     // Code is valid, but it is impossible to format it properly.
331     pub(crate) has_formatting_errors: bool,
332
333     // Code contains macro call that was unable to format.
334     pub(crate) has_macro_format_failure: bool,
335
336     // Failed a check, such as the license check or other opt-in checking.
337     pub(crate) has_check_errors: bool,
338
339     /// Formatted code differs from existing code (--check only).
340     pub(crate) has_diff: bool,
341
342     /// Formatted code missed something, like lost comments or extra trailing space
343     pub(crate) has_unformatted_code_errors: bool,
344 }
345
346 impl ReportedErrors {
347     /// Combine two summaries together.
348     pub(crate) fn add(&mut self, other: &ReportedErrors) {
349         self.has_operational_errors |= other.has_operational_errors;
350         self.has_parsing_errors |= other.has_parsing_errors;
351         self.has_formatting_errors |= other.has_formatting_errors;
352         self.has_macro_format_failure |= other.has_macro_format_failure;
353         self.has_check_errors |= other.has_check_errors;
354         self.has_diff |= other.has_diff;
355         self.has_unformatted_code_errors |= other.has_unformatted_code_errors;
356     }
357 }
358
359 #[derive(Clone, Copy, Debug)]
360 enum Timer {
361     Disabled,
362     Initialized(Instant),
363     DoneParsing(Instant, Instant),
364     DoneFormatting(Instant, Instant, Instant),
365 }
366
367 impl Timer {
368     fn start() -> Timer {
369         if cfg!(target_arch = "wasm32") {
370             Timer::Disabled
371         } else {
372             Timer::Initialized(Instant::now())
373         }
374     }
375     fn done_parsing(self) -> Self {
376         match self {
377             Timer::Disabled => Timer::Disabled,
378             Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
379             _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
380         }
381     }
382
383     fn done_formatting(self) -> Self {
384         match self {
385             Timer::Disabled => Timer::Disabled,
386             Timer::DoneParsing(init_time, parse_time) => {
387                 Timer::DoneFormatting(init_time, parse_time, Instant::now())
388             }
389             _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
390         }
391     }
392
393     /// Returns the time it took to parse the source files in seconds.
394     fn get_parse_time(&self) -> f32 {
395         match *self {
396             Timer::Disabled => panic!("this platform cannot time execution"),
397             Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
398                 // This should never underflow since `Instant::now()` guarantees monotonicity.
399                 Self::duration_to_f32(parse_time.duration_since(init))
400             }
401             Timer::Initialized(..) => unreachable!(),
402         }
403     }
404
405     /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
406     /// not included.
407     fn get_format_time(&self) -> f32 {
408         match *self {
409             Timer::Disabled => panic!("this platform cannot time execution"),
410             Timer::DoneFormatting(_init, parse_time, format_time) => {
411                 Self::duration_to_f32(format_time.duration_since(parse_time))
412             }
413             Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
414         }
415     }
416
417     fn duration_to_f32(d: Duration) -> f32 {
418         d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
419     }
420 }
421
422 // Formatting done on a char by char or line by line basis.
423 // FIXME(#20): other stuff for parity with make tidy.
424 fn format_lines(
425     text: &mut String,
426     name: &FileName,
427     skipped_range: &[(usize, usize)],
428     config: &Config,
429     report: &FormatReport,
430 ) {
431     let mut formatter = FormatLines::new(name, skipped_range, config);
432     formatter.check_license(text);
433     formatter.iterate(text);
434
435     if formatter.newline_count > 1 {
436         debug!("track truncate: {} {}", text.len(), formatter.newline_count);
437         let line = text.len() - formatter.newline_count + 1;
438         text.truncate(line);
439     }
440
441     report.append(name.clone(), formatter.errors);
442 }
443
444 struct FormatLines<'a> {
445     name: &'a FileName,
446     skipped_range: &'a [(usize, usize)],
447     last_was_space: bool,
448     line_len: usize,
449     cur_line: usize,
450     newline_count: usize,
451     errors: Vec<FormattingError>,
452     issue_seeker: BadIssueSeeker,
453     line_buffer: String,
454     current_line_contains_string_literal: bool,
455     format_line: bool,
456     allow_issue_seek: bool,
457     config: &'a Config,
458 }
459
460 impl<'a> FormatLines<'a> {
461     fn new(
462         name: &'a FileName,
463         skipped_range: &'a [(usize, usize)],
464         config: &'a Config,
465     ) -> FormatLines<'a> {
466         let issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
467         FormatLines {
468             name,
469             skipped_range,
470             last_was_space: false,
471             line_len: 0,
472             cur_line: 1,
473             newline_count: 0,
474             errors: vec![],
475             allow_issue_seek: !issue_seeker.is_disabled(),
476             issue_seeker,
477             line_buffer: String::with_capacity(config.max_width() * 2),
478             current_line_contains_string_literal: false,
479             format_line: config.file_lines().contains_line(name, 1),
480             config,
481         }
482     }
483
484     fn check_license(&mut self, text: &mut String) {
485         if let Some(ref license_template) = self.config.license_template {
486             if !license_template.is_match(text) {
487                 self.errors.push(FormattingError {
488                     line: self.cur_line,
489                     kind: ErrorKind::LicenseCheck,
490                     is_comment: false,
491                     is_string: false,
492                     line_buffer: String::new(),
493                 });
494             }
495         }
496     }
497
498     // Iterate over the chars in the file map.
499     fn iterate(&mut self, text: &mut String) {
500         for (kind, c) in CharClasses::new(text.chars()) {
501             if c == '\r' {
502                 continue;
503             }
504
505             if self.allow_issue_seek && self.format_line {
506                 // Add warnings for bad todos/ fixmes
507                 if let Some(issue) = self.issue_seeker.inspect(c) {
508                     self.push_err(ErrorKind::BadIssue(issue), false, false);
509                 }
510             }
511
512             if c == '\n' {
513                 self.new_line(kind);
514             } else {
515                 self.char(c, kind);
516             }
517         }
518     }
519
520     fn new_line(&mut self, kind: FullCodeCharKind) {
521         if self.format_line {
522             // Check for (and record) trailing whitespace.
523             if self.last_was_space {
524                 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
525                     && !self.is_skipped_line()
526                 {
527                     self.push_err(
528                         ErrorKind::TrailingWhitespace,
529                         kind.is_comment(),
530                         kind.is_string(),
531                     );
532                 }
533                 self.line_len -= 1;
534             }
535
536             // Check for any line width errors we couldn't correct.
537             let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
538             if self.line_len > self.config.max_width()
539                 && !self.is_skipped_line()
540                 && self.should_report_error(kind, &error_kind)
541             {
542                 let is_string = self.current_line_contains_string_literal;
543                 self.push_err(error_kind, kind.is_comment(), is_string);
544             }
545         }
546
547         self.line_len = 0;
548         self.cur_line += 1;
549         self.format_line = self
550             .config
551             .file_lines()
552             .contains_line(self.name, self.cur_line);
553         self.newline_count += 1;
554         self.last_was_space = false;
555         self.line_buffer.clear();
556         self.current_line_contains_string_literal = false;
557     }
558
559     fn char(&mut self, c: char, kind: FullCodeCharKind) {
560         self.newline_count = 0;
561         self.line_len += if c == '\t' {
562             self.config.tab_spaces()
563         } else {
564             1
565         };
566         self.last_was_space = c.is_whitespace();
567         self.line_buffer.push(c);
568         if kind.is_string() {
569             self.current_line_contains_string_literal = true;
570         }
571     }
572
573     fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
574         self.errors.push(FormattingError {
575             line: self.cur_line,
576             kind,
577             is_comment,
578             is_string,
579             line_buffer: self.line_buffer.clone(),
580         });
581     }
582
583     fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
584         let allow_error_report = if char_kind.is_comment()
585             || self.current_line_contains_string_literal
586             || error_kind.is_comment()
587         {
588             self.config.error_on_unformatted()
589         } else {
590             true
591         };
592
593         match error_kind {
594             ErrorKind::LineOverflow(..) => {
595                 self.config.error_on_line_overflow() && allow_error_report
596             }
597             ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
598             _ => true,
599         }
600     }
601
602     /// Returns `true` if the line with the given line number was skipped by `#[rustfmt::skip]`.
603     fn is_skipped_line(&self) -> bool {
604         self.skipped_range
605             .iter()
606             .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
607     }
608 }
609
610 fn should_emit_verbose<F>(forbid_verbose_output: bool, config: &Config, f: F)
611 where
612     F: Fn(),
613 {
614     if config.verbose() == Verbosity::Verbose && !forbid_verbose_output {
615         f();
616     }
617 }