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