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