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