]> git.lizzy.rs Git - rust.git/blob - src/formatting.rs
feat: remove license_template_path config option
[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::rc::Rc;
6 use std::time::{Duration, Instant};
7
8 use rustc_ast::ast;
9 use rustc_ast::AstLike;
10 use rustc_span::Span;
11
12 use self::newline_style::apply_newline_style;
13 use crate::comment::{CharClasses, FullCodeCharKind};
14 use crate::config::{Config, FileName, Verbosity};
15 use crate::formatting::generated::is_generated_file;
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             Rc::default(),
194         );
195         visitor.skip_context.update_with_attrs(&self.krate.attrs);
196         visitor.is_macro_def = is_macro_def;
197         visitor.last_pos = snippet_provider.start_pos();
198         visitor.skip_empty_lines(snippet_provider.end_pos());
199         visitor.format_separate_mod(module, snippet_provider.end_pos());
200
201         debug_assert_eq!(
202             visitor.line_number,
203             count_newlines(&visitor.buffer),
204             "failed in format_file visitor.buffer:\n {:?}",
205             &visitor.buffer
206         );
207
208         // For some reason, the source_map does not include terminating
209         // newlines so we must add one on for each file. This is sad.
210         source_file::append_newline(&mut visitor.buffer);
211
212         format_lines(
213             &mut visitor.buffer,
214             &path,
215             &visitor.skipped_range.borrow(),
216             self.config,
217             &self.report,
218         );
219
220         apply_newline_style(
221             self.config.newline_style(),
222             &mut visitor.buffer,
223             snippet_provider.entire_snippet(),
224         );
225
226         if visitor.macro_rewrite_failure {
227             self.report.add_macro_format_failure();
228         }
229         self.report
230             .add_non_formatted_ranges(visitor.skipped_range.borrow().clone());
231
232         self.handler.handle_formatted_file(
233             &self.parse_session,
234             path,
235             visitor.buffer.to_owned(),
236             &mut self.report,
237         )
238     }
239 }
240
241 // Handle the results of formatting.
242 trait FormatHandler {
243     fn handle_formatted_file(
244         &mut self,
245         parse_session: &ParseSess,
246         path: FileName,
247         result: String,
248         report: &mut FormatReport,
249     ) -> Result<(), ErrorKind>;
250 }
251
252 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
253     // Called for each formatted file.
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         if let Some(ref mut out) = self.out {
262             match source_file::write_file(
263                 Some(parse_session),
264                 &path,
265                 &result,
266                 out,
267                 &mut *self.emitter,
268                 self.config.newline_style(),
269             ) {
270                 Ok(ref result) if result.has_diff => report.add_diff(),
271                 Err(e) => {
272                     // Create a new error with path_str to help users see which files failed
273                     let err_msg = format!("{}: {}", path, e);
274                     return Err(io::Error::new(e.kind(), err_msg).into());
275                 }
276                 _ => {}
277             }
278         }
279
280         self.source_file.push((path, result));
281         Ok(())
282     }
283 }
284
285 pub(crate) struct FormattingError {
286     pub(crate) line: usize,
287     pub(crate) kind: ErrorKind,
288     is_comment: bool,
289     is_string: bool,
290     pub(crate) line_buffer: String,
291 }
292
293 impl FormattingError {
294     pub(crate) fn from_span(
295         span: Span,
296         parse_sess: &ParseSess,
297         kind: ErrorKind,
298     ) -> FormattingError {
299         FormattingError {
300             line: parse_sess.line_of_byte_pos(span.lo()),
301             is_comment: kind.is_comment(),
302             kind,
303             is_string: false,
304             line_buffer: parse_sess.span_to_first_line_string(span),
305         }
306     }
307
308     pub(crate) fn is_internal(&self) -> bool {
309         match self.kind {
310             ErrorKind::LineOverflow(..)
311             | ErrorKind::TrailingWhitespace
312             | ErrorKind::IoError(_)
313             | ErrorKind::ParseError
314             | ErrorKind::LostComment => true,
315             _ => false,
316         }
317     }
318
319     pub(crate) fn msg_suffix(&self) -> &str {
320         if self.is_comment || self.is_string {
321             "set `error_on_unformatted = false` to suppress \
322              the warning against comments or string literals\n"
323         } else {
324             ""
325         }
326     }
327
328     // (space, target)
329     pub(crate) fn format_len(&self) -> (usize, usize) {
330         match self.kind {
331             ErrorKind::LineOverflow(found, max) => (max, found - max),
332             ErrorKind::TrailingWhitespace
333             | ErrorKind::DeprecatedAttr
334             | ErrorKind::BadAttr
335             | ErrorKind::LostComment => {
336                 let trailing_ws_start = self
337                     .line_buffer
338                     .rfind(|c: char| !c.is_whitespace())
339                     .map(|pos| pos + 1)
340                     .unwrap_or(0);
341                 (
342                     trailing_ws_start,
343                     self.line_buffer.len() - trailing_ws_start,
344                 )
345             }
346             _ => unreachable!(),
347         }
348     }
349 }
350
351 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
352
353 #[derive(Default, Debug, PartialEq)]
354 pub(crate) struct ReportedErrors {
355     // Encountered e.g., an IO error.
356     pub(crate) has_operational_errors: bool,
357
358     // Failed to reformat code because of parsing errors.
359     pub(crate) has_parsing_errors: bool,
360
361     // Code is valid, but it is impossible to format it properly.
362     pub(crate) has_formatting_errors: bool,
363
364     // Code contains macro call that was unable to format.
365     pub(crate) has_macro_format_failure: bool,
366
367     // Failed an opt-in checking.
368     pub(crate) has_check_errors: bool,
369
370     /// Formatted code differs from existing code (--check only).
371     pub(crate) has_diff: bool,
372
373     /// Formatted code missed something, like lost comments or extra trailing space
374     pub(crate) has_unformatted_code_errors: bool,
375 }
376
377 impl ReportedErrors {
378     /// Combine two summaries together.
379     pub(crate) fn add(&mut self, other: &ReportedErrors) {
380         self.has_operational_errors |= other.has_operational_errors;
381         self.has_parsing_errors |= other.has_parsing_errors;
382         self.has_formatting_errors |= other.has_formatting_errors;
383         self.has_macro_format_failure |= other.has_macro_format_failure;
384         self.has_check_errors |= other.has_check_errors;
385         self.has_diff |= other.has_diff;
386         self.has_unformatted_code_errors |= other.has_unformatted_code_errors;
387     }
388 }
389
390 #[derive(Clone, Copy, Debug)]
391 enum Timer {
392     Disabled,
393     Initialized(Instant),
394     DoneParsing(Instant, Instant),
395     DoneFormatting(Instant, Instant, Instant),
396 }
397
398 impl Timer {
399     fn start() -> Timer {
400         if cfg!(target_arch = "wasm32") {
401             Timer::Disabled
402         } else {
403             Timer::Initialized(Instant::now())
404         }
405     }
406     fn done_parsing(self) -> Self {
407         match self {
408             Timer::Disabled => Timer::Disabled,
409             Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
410             _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
411         }
412     }
413
414     fn done_formatting(self) -> Self {
415         match self {
416             Timer::Disabled => Timer::Disabled,
417             Timer::DoneParsing(init_time, parse_time) => {
418                 Timer::DoneFormatting(init_time, parse_time, Instant::now())
419             }
420             _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
421         }
422     }
423
424     /// Returns the time it took to parse the source files in seconds.
425     fn get_parse_time(&self) -> f32 {
426         match *self {
427             Timer::Disabled => panic!("this platform cannot time execution"),
428             Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
429                 // This should never underflow since `Instant::now()` guarantees monotonicity.
430                 Self::duration_to_f32(parse_time.duration_since(init))
431             }
432             Timer::Initialized(..) => unreachable!(),
433         }
434     }
435
436     /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
437     /// not included.
438     fn get_format_time(&self) -> f32 {
439         match *self {
440             Timer::Disabled => panic!("this platform cannot time execution"),
441             Timer::DoneFormatting(_init, parse_time, format_time) => {
442                 Self::duration_to_f32(format_time.duration_since(parse_time))
443             }
444             Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
445         }
446     }
447
448     fn duration_to_f32(d: Duration) -> f32 {
449         d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
450     }
451 }
452
453 // Formatting done on a char by char or line by line basis.
454 // FIXME(#20): other stuff for parity with make tidy.
455 fn format_lines(
456     text: &mut String,
457     name: &FileName,
458     skipped_range: &[(usize, usize)],
459     config: &Config,
460     report: &FormatReport,
461 ) {
462     let mut formatter = FormatLines::new(name, skipped_range, config);
463     formatter.iterate(text);
464
465     if formatter.newline_count > 1 {
466         debug!("track truncate: {} {}", text.len(), formatter.newline_count);
467         let line = text.len() - formatter.newline_count + 1;
468         text.truncate(line);
469     }
470
471     report.append(name.clone(), formatter.errors);
472 }
473
474 struct FormatLines<'a> {
475     name: &'a FileName,
476     skipped_range: &'a [(usize, usize)],
477     last_was_space: bool,
478     line_len: usize,
479     cur_line: usize,
480     newline_count: usize,
481     errors: Vec<FormattingError>,
482     line_buffer: String,
483     current_line_contains_string_literal: bool,
484     format_line: bool,
485     config: &'a Config,
486 }
487
488 impl<'a> FormatLines<'a> {
489     fn new(
490         name: &'a FileName,
491         skipped_range: &'a [(usize, usize)],
492         config: &'a Config,
493     ) -> FormatLines<'a> {
494         FormatLines {
495             name,
496             skipped_range,
497             last_was_space: false,
498             line_len: 0,
499             cur_line: 1,
500             newline_count: 0,
501             errors: vec![],
502             line_buffer: String::with_capacity(config.max_width() * 2),
503             current_line_contains_string_literal: false,
504             format_line: config.file_lines().contains_line(name, 1),
505             config,
506         }
507     }
508
509     // Iterate over the chars in the file map.
510     fn iterate(&mut self, text: &mut String) {
511         for (kind, c) in CharClasses::new(text.chars()) {
512             if c == '\r' {
513                 continue;
514             }
515
516             if c == '\n' {
517                 self.new_line(kind);
518             } else {
519                 self.char(c, kind);
520             }
521         }
522     }
523
524     fn new_line(&mut self, kind: FullCodeCharKind) {
525         if self.format_line {
526             // Check for (and record) trailing whitespace.
527             if self.last_was_space {
528                 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
529                     && !self.is_skipped_line()
530                 {
531                     self.push_err(
532                         ErrorKind::TrailingWhitespace,
533                         kind.is_comment(),
534                         kind.is_string(),
535                     );
536                 }
537                 self.line_len -= 1;
538             }
539
540             // Check for any line width errors we couldn't correct.
541             let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
542             if self.line_len > self.config.max_width()
543                 && !self.is_skipped_line()
544                 && self.should_report_error(kind, &error_kind)
545             {
546                 let is_string = self.current_line_contains_string_literal;
547                 self.push_err(error_kind, kind.is_comment(), is_string);
548             }
549         }
550
551         self.line_len = 0;
552         self.cur_line += 1;
553         self.format_line = self
554             .config
555             .file_lines()
556             .contains_line(self.name, self.cur_line);
557         self.newline_count += 1;
558         self.last_was_space = false;
559         self.line_buffer.clear();
560         self.current_line_contains_string_literal = false;
561     }
562
563     fn char(&mut self, c: char, kind: FullCodeCharKind) {
564         self.newline_count = 0;
565         self.line_len += if c == '\t' {
566             self.config.tab_spaces()
567         } else {
568             1
569         };
570         self.last_was_space = c.is_whitespace();
571         self.line_buffer.push(c);
572         if kind.is_string() {
573             self.current_line_contains_string_literal = true;
574         }
575     }
576
577     fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
578         self.errors.push(FormattingError {
579             line: self.cur_line,
580             kind,
581             is_comment,
582             is_string,
583             line_buffer: self.line_buffer.clone(),
584         });
585     }
586
587     fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
588         let allow_error_report = if char_kind.is_comment()
589             || self.current_line_contains_string_literal
590             || error_kind.is_comment()
591         {
592             self.config.error_on_unformatted()
593         } else {
594             true
595         };
596
597         match error_kind {
598             ErrorKind::LineOverflow(..) => {
599                 self.config.error_on_line_overflow() && allow_error_report
600             }
601             ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
602             _ => true,
603         }
604     }
605
606     /// Returns `true` if the line with the given line number was skipped by `#[rustfmt::skip]`.
607     fn is_skipped_line(&self) -> bool {
608         self.skipped_range
609             .iter()
610             .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
611     }
612 }
613
614 fn should_emit_verbose<F>(forbid_verbose_output: bool, config: &Config, f: F)
615 where
616     F: Fn(),
617 {
618     if config.verbose() == Verbosity::Verbose && !forbid_verbose_output {
619         f();
620     }
621 }