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