]> git.lizzy.rs Git - rust.git/blob - src/formatting.rs
Merge pull request #3510 from topecongiro/issue3509
[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::panic::{catch_unwind, AssertUnwindSafe};
6 use std::rc::Rc;
7 use std::time::{Duration, Instant};
8
9 use syntax::ast;
10 use syntax::errors::emitter::{ColorConfig, Emitter};
11 use syntax::errors::{DiagnosticBuilder, Handler};
12 use syntax::parse::{self, ParseSess};
13 use syntax::source_map::{FilePathMapping, SourceMap, Span, DUMMY_SP};
14
15 use crate::comment::{CharClasses, FullCodeCharKind};
16 use crate::config::{Config, FileName, Verbosity};
17 use crate::ignore_path::IgnorePathSet;
18 use crate::issues::BadIssueSeeker;
19 use crate::utils::{count_newlines, get_skip_macro_names};
20 use crate::visitor::{FmtVisitor, SnippetProvider};
21 use crate::{modules, source_file, ErrorKind, FormatReport, Input, Session};
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(&mut self, input: Input) -> Result<FormatReport, ErrorKind> {
29         if !self.config.version_meets_requirement() {
30             return Err(ErrorKind::VersionMismatch);
31         }
32
33         syntax::with_globals(|| {
34             syntax_pos::hygiene::set_default_edition(
35                 self.config.edition().to_libsyntax_pos_edition(),
36             );
37
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);
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 ) -> Result<FormatReport, ErrorKind> {
65     let mut timer = Timer::start();
66
67     let main_file = input.file_name();
68     let input_is_stdin = main_file == FileName::Stdin;
69
70     // Parse the crate.
71     let source_map = Rc::new(SourceMap::new(FilePathMapping::empty()));
72     let mut parse_session = make_parse_sess(source_map.clone(), config);
73     let mut report = FormatReport::new();
74     let directory_ownership = input.to_directory_ownership();
75     let krate = match parse_crate(
76         input,
77         &parse_session,
78         config,
79         &mut report,
80         directory_ownership,
81     ) {
82         Ok(krate) => krate,
83         // Surface parse error via Session (errors are merged there from report)
84         Err(ErrorKind::ParseError) => return Ok(report),
85         Err(e) => return Err(e),
86     };
87     timer = timer.done_parsing();
88
89     // Suppress error output if we have to do any further parsing.
90     let silent_emitter = silent_emitter();
91     parse_session.span_diagnostic = Handler::with_emitter(true, None, silent_emitter);
92
93     let mut context = FormatContext::new(&krate, report, parse_session, config, handler);
94     let ignore_path_set = match IgnorePathSet::from_ignore_list(&config.ignore()) {
95         Ok(set) => set,
96         Err(e) => return Err(ErrorKind::InvalidGlobPattern(e)),
97     };
98
99     let files = modules::ModResolver::new(
100         context.parse_session.source_map(),
101         directory_ownership.unwrap_or(parse::DirectoryOwnership::UnownedViaMod(false)),
102         input_is_stdin,
103     )
104     .visit_crate(&krate)
105     .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
106     for (path, (module, _)) in files {
107         let should_ignore = !input_is_stdin && ignore_path_set.is_match(&path);
108         if (config.skip_children() && path != main_file) || should_ignore {
109             continue;
110         }
111         should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
112         let is_root = path == main_file;
113         context.format_file(path, module, is_root)?;
114     }
115     timer = timer.done_formatting();
116
117     should_emit_verbose(input_is_stdin, config, || {
118         println!(
119             "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
120             timer.get_parse_time(),
121             timer.get_format_time(),
122         )
123     });
124
125     Ok(context.report)
126 }
127
128 // Used for formatting files.
129 #[derive(new)]
130 struct FormatContext<'a, T: FormatHandler> {
131     krate: &'a ast::Crate,
132     report: FormatReport,
133     parse_session: ParseSess,
134     config: &'a Config,
135     handler: &'a mut T,
136 }
137
138 impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
139     // Formats a single file/module.
140     fn format_file(
141         &mut self,
142         path: FileName,
143         module: &ast::Mod,
144         is_root: bool,
145     ) -> Result<(), ErrorKind> {
146         let source_file = self
147             .parse_session
148             .source_map()
149             .lookup_char_pos(module.inner.lo())
150             .file;
151         let big_snippet = source_file.src.as_ref().unwrap();
152         let snippet_provider = SnippetProvider::new(source_file.start_pos, big_snippet);
153         let mut visitor = FmtVisitor::from_source_map(
154             &self.parse_session,
155             &self.config,
156             &snippet_provider,
157             self.report.clone(),
158         );
159         visitor
160             .skip_macro_names
161             .borrow_mut()
162             .append(&mut get_skip_macro_names(&self.krate.attrs));
163
164         // Format inner attributes if available.
165         if !self.krate.attrs.is_empty() && is_root {
166             visitor.skip_empty_lines(source_file.end_pos);
167             if visitor.visit_attrs(&self.krate.attrs, ast::AttrStyle::Inner) {
168                 visitor.push_rewrite(module.inner, None);
169             } else {
170                 visitor.format_separate_mod(module, &*source_file);
171             }
172         } else {
173             visitor.last_pos = source_file.start_pos;
174             visitor.skip_empty_lines(source_file.end_pos);
175             visitor.format_separate_mod(module, &*source_file);
176         };
177
178         debug_assert_eq!(visitor.line_number, count_newlines(&visitor.buffer));
179
180         // For some reason, the source_map does not include terminating
181         // newlines so we must add one on for each file. This is sad.
182         source_file::append_newline(&mut visitor.buffer);
183
184         format_lines(
185             &mut visitor.buffer,
186             &path,
187             &visitor.skipped_range,
188             &self.config,
189             &self.report,
190         );
191         self.config
192             .newline_style()
193             .apply(&mut visitor.buffer, &big_snippet);
194
195         if visitor.macro_rewrite_failure {
196             self.report.add_macro_format_failure();
197         }
198         self.report
199             .add_non_formatted_ranges(visitor.skipped_range.clone());
200
201         self.handler.handle_formatted_file(
202             self.parse_session.source_map(),
203             path,
204             visitor.buffer.to_owned(),
205             &mut self.report,
206         )
207     }
208 }
209
210 // Handle the results of formatting.
211 trait FormatHandler {
212     fn handle_formatted_file(
213         &mut self,
214         source_map: &SourceMap,
215         path: FileName,
216         result: String,
217         report: &mut FormatReport,
218     ) -> Result<(), ErrorKind>;
219 }
220
221 impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
222     // Called for each formatted file.
223     fn handle_formatted_file(
224         &mut self,
225         source_map: &SourceMap,
226         path: FileName,
227         result: String,
228         report: &mut FormatReport,
229     ) -> Result<(), ErrorKind> {
230         if let Some(ref mut out) = self.out {
231             match source_file::write_file(Some(source_map), &path, &result, out, &self.config) {
232                 Ok(has_diff) if has_diff => report.add_diff(),
233                 Err(e) => {
234                     // Create a new error with path_str to help users see which files failed
235                     let err_msg = format!("{}: {}", path, e);
236                     return Err(io::Error::new(e.kind(), err_msg).into());
237                 }
238                 _ => {}
239             }
240         }
241
242         self.source_file.push((path, result));
243         Ok(())
244     }
245 }
246
247 pub(crate) struct FormattingError {
248     pub(crate) line: usize,
249     pub(crate) kind: ErrorKind,
250     is_comment: bool,
251     is_string: bool,
252     pub(crate) line_buffer: String,
253 }
254
255 impl FormattingError {
256     pub(crate) fn from_span(
257         span: Span,
258         source_map: &SourceMap,
259         kind: ErrorKind,
260     ) -> FormattingError {
261         FormattingError {
262             line: source_map.lookup_char_pos(span.lo()).line,
263             is_comment: kind.is_comment(),
264             kind,
265             is_string: false,
266             line_buffer: source_map
267                 .span_to_lines(span)
268                 .ok()
269                 .and_then(|fl| {
270                     fl.file
271                         .get_line(fl.lines[0].line_index)
272                         .map(std::borrow::Cow::into_owned)
273                 })
274                 .unwrap_or_else(String::new),
275         }
276     }
277
278     pub(crate) fn is_internal(&self) -> bool {
279         match self.kind {
280             ErrorKind::LineOverflow(..)
281             | ErrorKind::TrailingWhitespace
282             | ErrorKind::IoError(_)
283             | ErrorKind::ParseError
284             | ErrorKind::LostComment => true,
285             _ => false,
286         }
287     }
288
289     pub(crate) fn msg_suffix(&self) -> &str {
290         if self.is_comment || self.is_string {
291             "set `error_on_unformatted = false` to suppress \
292              the warning against comments or string literals\n"
293         } else {
294             ""
295         }
296     }
297
298     // (space, target)
299     pub(crate) fn format_len(&self) -> (usize, usize) {
300         match self.kind {
301             ErrorKind::LineOverflow(found, max) => (max, found - max),
302             ErrorKind::TrailingWhitespace
303             | ErrorKind::DeprecatedAttr
304             | ErrorKind::BadIssue(_)
305             | ErrorKind::BadAttr
306             | ErrorKind::LostComment => {
307                 let trailing_ws_start = self
308                     .line_buffer
309                     .rfind(|c: char| !c.is_whitespace())
310                     .map(|pos| pos + 1)
311                     .unwrap_or(0);
312                 (
313                     trailing_ws_start,
314                     self.line_buffer.len() - trailing_ws_start,
315                 )
316             }
317             _ => unreachable!(),
318         }
319     }
320 }
321
322 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
323
324 #[derive(Default, Debug, PartialEq)]
325 pub(crate) struct ReportedErrors {
326     // Encountered e.g., an IO error.
327     pub(crate) has_operational_errors: bool,
328
329     // Failed to reformat code because of parsing errors.
330     pub(crate) has_parsing_errors: bool,
331
332     // Code is valid, but it is impossible to format it properly.
333     pub(crate) has_formatting_errors: bool,
334
335     // Code contains macro call that was unable to format.
336     pub(crate) has_macro_format_failure: bool,
337
338     // Failed a check, such as the license check or other opt-in checking.
339     pub(crate) has_check_errors: bool,
340
341     /// Formatted code differs from existing code (--check only).
342     pub(crate) has_diff: bool,
343 }
344
345 impl ReportedErrors {
346     /// Combine two summaries together.
347     pub fn add(&mut self, other: &ReportedErrors) {
348         self.has_operational_errors |= other.has_operational_errors;
349         self.has_parsing_errors |= other.has_parsing_errors;
350         self.has_formatting_errors |= other.has_formatting_errors;
351         self.has_macro_format_failure |= other.has_macro_format_failure;
352         self.has_check_errors |= other.has_check_errors;
353         self.has_diff |= other.has_diff;
354     }
355 }
356
357 #[derive(Clone, Copy, Debug)]
358 enum Timer {
359     Disabled,
360     Initialized(Instant),
361     DoneParsing(Instant, Instant),
362     DoneFormatting(Instant, Instant, Instant),
363 }
364
365 impl Timer {
366     fn start() -> Timer {
367         if cfg!(target_arch = "wasm32") {
368             Timer::Disabled
369         } else {
370             Timer::Initialized(Instant::now())
371         }
372     }
373     fn done_parsing(self) -> Self {
374         match self {
375             Timer::Disabled => Timer::Disabled,
376             Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
377             _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
378         }
379     }
380
381     fn done_formatting(self) -> Self {
382         match self {
383             Timer::Disabled => Timer::Disabled,
384             Timer::DoneParsing(init_time, parse_time) => {
385                 Timer::DoneFormatting(init_time, parse_time, Instant::now())
386             }
387             _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
388         }
389     }
390
391     /// Returns the time it took to parse the source files in seconds.
392     fn get_parse_time(&self) -> f32 {
393         match *self {
394             Timer::Disabled => panic!("this platform cannot time execution"),
395             Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
396                 // This should never underflow since `Instant::now()` guarantees monotonicity.
397                 Self::duration_to_f32(parse_time.duration_since(init))
398             }
399             Timer::Initialized(..) => unreachable!(),
400         }
401     }
402
403     /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
404     /// not included.
405     fn get_format_time(&self) -> f32 {
406         match *self {
407             Timer::Disabled => panic!("this platform cannot time execution"),
408             Timer::DoneFormatting(_init, parse_time, format_time) => {
409                 Self::duration_to_f32(format_time.duration_since(parse_time))
410             }
411             Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
412         }
413     }
414
415     fn duration_to_f32(d: Duration) -> f32 {
416         d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
417     }
418 }
419
420 // Formatting done on a char by char or line by line basis.
421 // FIXME(#20): other stuff for parity with make tidy.
422 fn format_lines(
423     text: &mut String,
424     name: &FileName,
425     skipped_range: &[(usize, usize)],
426     config: &Config,
427     report: &FormatReport,
428 ) {
429     let mut formatter = FormatLines::new(name, skipped_range, config);
430     formatter.check_license(text);
431     formatter.iterate(text);
432
433     if formatter.newline_count > 1 {
434         debug!("track truncate: {} {}", text.len(), formatter.newline_count);
435         let line = text.len() - formatter.newline_count + 1;
436         text.truncate(line);
437     }
438
439     report.append(name.clone(), formatter.errors);
440 }
441
442 struct FormatLines<'a> {
443     name: &'a FileName,
444     skipped_range: &'a [(usize, usize)],
445     last_was_space: bool,
446     line_len: usize,
447     cur_line: usize,
448     newline_count: usize,
449     errors: Vec<FormattingError>,
450     issue_seeker: BadIssueSeeker,
451     line_buffer: String,
452     // `true` if the current line contains a string literal.
453     is_string: bool,
454     format_line: bool,
455     allow_issue_seek: bool,
456     config: &'a Config,
457 }
458
459 impl<'a> FormatLines<'a> {
460     fn new(
461         name: &'a FileName,
462         skipped_range: &'a [(usize, usize)],
463         config: &'a Config,
464     ) -> FormatLines<'a> {
465         let issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
466         FormatLines {
467             name,
468             skipped_range,
469             last_was_space: false,
470             line_len: 0,
471             cur_line: 1,
472             newline_count: 0,
473             errors: vec![],
474             allow_issue_seek: !issue_seeker.is_disabled(),
475             issue_seeker,
476             line_buffer: String::with_capacity(config.max_width() * 2),
477             is_string: false,
478             format_line: config.file_lines().contains_line(name, 1),
479             config,
480         }
481     }
482
483     fn check_license(&mut self, text: &mut String) {
484         if let Some(ref license_template) = self.config.license_template {
485             if !license_template.is_match(text) {
486                 self.errors.push(FormattingError {
487                     line: self.cur_line,
488                     kind: ErrorKind::LicenseCheck,
489                     is_comment: false,
490                     is_string: false,
491                     line_buffer: String::new(),
492                 });
493             }
494         }
495     }
496
497     // Iterate over the chars in the file map.
498     fn iterate(&mut self, text: &mut String) {
499         for (kind, c) in CharClasses::new(text.chars()) {
500             if c == '\r' {
501                 continue;
502             }
503
504             if self.allow_issue_seek && self.format_line {
505                 // Add warnings for bad todos/ fixmes
506                 if let Some(issue) = self.issue_seeker.inspect(c) {
507                     self.push_err(ErrorKind::BadIssue(issue), false, false);
508                 }
509             }
510
511             if c == '\n' {
512                 self.new_line(kind);
513             } else {
514                 self.char(c, kind);
515             }
516         }
517     }
518
519     fn new_line(&mut self, kind: FullCodeCharKind) {
520         if self.format_line {
521             // Check for (and record) trailing whitespace.
522             if self.last_was_space {
523                 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
524                     && !self.is_skipped_line()
525                 {
526                     self.push_err(
527                         ErrorKind::TrailingWhitespace,
528                         kind.is_comment(),
529                         kind.is_string(),
530                     );
531                 }
532                 self.line_len -= 1;
533             }
534
535             // Check for any line width errors we couldn't correct.
536             let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
537             if self.line_len > self.config.max_width()
538                 && !self.is_skipped_line()
539                 && self.should_report_error(kind, &error_kind)
540             {
541                 let is_string = self.is_string;
542                 self.push_err(error_kind, kind.is_comment(), is_string);
543             }
544         }
545
546         self.line_len = 0;
547         self.cur_line += 1;
548         self.format_line = self
549             .config
550             .file_lines()
551             .contains_line(self.name, self.cur_line);
552         self.newline_count += 1;
553         self.last_was_space = false;
554         self.line_buffer.clear();
555         self.is_string = false;
556     }
557
558     fn char(&mut self, c: char, kind: FullCodeCharKind) {
559         self.newline_count = 0;
560         self.line_len += if c == '\t' {
561             self.config.tab_spaces()
562         } else {
563             1
564         };
565         self.last_was_space = c.is_whitespace();
566         self.line_buffer.push(c);
567         if kind.is_string() {
568             self.is_string = true;
569         }
570     }
571
572     fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
573         self.errors.push(FormattingError {
574             line: self.cur_line,
575             kind,
576             is_comment,
577             is_string,
578             line_buffer: self.line_buffer.clone(),
579         });
580     }
581
582     fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
583         let allow_error_report =
584             if char_kind.is_comment() || self.is_string || error_kind.is_comment() {
585                 self.config.error_on_unformatted()
586             } else {
587                 true
588             };
589
590         match error_kind {
591             ErrorKind::LineOverflow(..) => {
592                 self.config.error_on_line_overflow() && allow_error_report
593             }
594             ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
595             _ => true,
596         }
597     }
598
599     /// Returns `true` if the line with the given line number was skipped by `#[rustfmt::skip]`.
600     fn is_skipped_line(&self) -> bool {
601         self.skipped_range
602             .iter()
603             .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
604     }
605 }
606
607 fn parse_crate(
608     input: Input,
609     parse_session: &ParseSess,
610     config: &Config,
611     report: &mut FormatReport,
612     directory_ownership: Option<parse::DirectoryOwnership>,
613 ) -> Result<ast::Crate, ErrorKind> {
614     let input_is_stdin = input.is_text();
615
616     let parser = match input {
617         Input::File(ref file) => {
618             // Use `new_sub_parser_from_file` when we the input is a submodule.
619             Ok(if let Some(dir_own) = directory_ownership {
620                 parse::new_sub_parser_from_file(parse_session, file, dir_own, None, DUMMY_SP)
621             } else {
622                 parse::new_parser_from_file(parse_session, file)
623             })
624         }
625         Input::Text(text) => parse::maybe_new_parser_from_source_str(
626             parse_session,
627             syntax::source_map::FileName::Custom("stdin".to_owned()),
628             text,
629         )
630         .map(|mut parser| {
631             parser.recurse_into_file_modules = false;
632             parser
633         })
634         .map_err(|diags| {
635             diags
636                 .into_iter()
637                 .map(|d| DiagnosticBuilder::new_diagnostic(&parse_session.span_diagnostic, d))
638                 .collect::<Vec<_>>()
639         }),
640     };
641
642     let result = match parser {
643         Ok(mut parser) => {
644             parser.cfg_mods = false;
645             if config.skip_children() {
646                 parser.recurse_into_file_modules = false;
647             }
648
649             let mut parser = AssertUnwindSafe(parser);
650             catch_unwind(move || parser.0.parse_crate_mod().map_err(|d| vec![d]))
651         }
652         Err(db) => Ok(Err(db)),
653     };
654
655     match result {
656         Ok(Ok(c)) => {
657             if !parse_session.span_diagnostic.has_errors() {
658                 return Ok(c);
659             }
660         }
661         Ok(Err(mut diagnostics)) => diagnostics.iter_mut().for_each(DiagnosticBuilder::emit),
662         Err(_) => {
663             // Note that if you see this message and want more information,
664             // then run the `parse_crate_mod` function above without
665             // `catch_unwind` so rustfmt panics and you can get a backtrace.
666             should_emit_verbose(input_is_stdin, config, || {
667                 println!("The Rust parser panicked")
668             });
669         }
670     }
671
672     report.add_parsing_error();
673     Err(ErrorKind::ParseError)
674 }
675
676 /// Emitter which discards every error.
677 struct SilentEmitter;
678
679 impl Emitter for SilentEmitter {
680     fn emit(&mut self, _db: &DiagnosticBuilder<'_>) {}
681 }
682
683 fn silent_emitter() -> Box<SilentEmitter> {
684     Box::new(SilentEmitter {})
685 }
686
687 fn make_parse_sess(source_map: Rc<SourceMap>, config: &Config) -> ParseSess {
688     let tty_handler = if config.hide_parse_errors() {
689         let silent_emitter = silent_emitter();
690         Handler::with_emitter(true, None, silent_emitter)
691     } else {
692         let supports_color = term::stderr().map_or(false, |term| term.supports_color());
693         let color_cfg = if supports_color {
694             ColorConfig::Auto
695         } else {
696             ColorConfig::Never
697         };
698         Handler::with_tty_emitter(color_cfg, true, None, Some(source_map.clone()))
699     };
700
701     ParseSess::with_span_handler(tty_handler, source_map)
702 }
703
704 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
705 where
706     F: Fn(),
707 {
708     if config.verbose() == Verbosity::Verbose && !is_stdin {
709         f();
710     }
711 }