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