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