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