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