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