]> git.lizzy.rs Git - rust.git/blob - src/formatting.rs
Refactoring: factor `format_lines` and `format_project` into smaller chunks
[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                 })
250                 .unwrap_or_else(|| String::new()),
251         }
252     }
253
254     pub(crate) fn msg_prefix(&self) -> &str {
255         match self.kind {
256             ErrorKind::LineOverflow(..)
257             | ErrorKind::TrailingWhitespace
258             | ErrorKind::IoError(_)
259             | ErrorKind::ParseError
260             | ErrorKind::LostComment => "internal error:",
261             ErrorKind::LicenseCheck | ErrorKind::BadAttr | ErrorKind::VersionMismatch => "error:",
262             ErrorKind::BadIssue(_) | ErrorKind::DeprecatedAttr => "warning:",
263         }
264     }
265
266     pub(crate) fn msg_suffix(&self) -> &str {
267         if self.is_comment || self.is_string {
268             "set `error_on_unformatted = false` to suppress \
269              the warning against comments or string literals\n"
270         } else {
271             ""
272         }
273     }
274
275     // (space, target)
276     pub(crate) fn format_len(&self) -> (usize, usize) {
277         match self.kind {
278             ErrorKind::LineOverflow(found, max) => (max, found - max),
279             ErrorKind::TrailingWhitespace
280             | ErrorKind::DeprecatedAttr
281             | ErrorKind::BadAttr
282             | ErrorKind::LostComment => {
283                 let trailing_ws_start = self
284                     .line_buffer
285                     .rfind(|c: char| !c.is_whitespace())
286                     .map(|pos| pos + 1)
287                     .unwrap_or(0);
288                 (
289                     trailing_ws_start,
290                     self.line_buffer.len() - trailing_ws_start,
291                 )
292             }
293             _ => unreachable!(),
294         }
295     }
296 }
297
298 pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
299
300 #[derive(Default, Debug)]
301 pub(crate) struct ReportedErrors {
302     pub(crate) has_operational_errors: bool,
303     pub(crate) has_check_errors: bool,
304 }
305
306 /// A single span of changed lines, with 0 or more removed lines
307 /// and a vector of 0 or more inserted lines.
308 #[derive(Debug, PartialEq, Eq)]
309 pub(crate) struct ModifiedChunk {
310     /// The first to be removed from the original text
311     pub line_number_orig: u32,
312     /// The number of lines which have been replaced
313     pub lines_removed: u32,
314     /// The new lines
315     pub lines: Vec<String>,
316 }
317
318 /// Set of changed sections of a file.
319 #[derive(Debug, PartialEq, Eq)]
320 pub(crate) struct ModifiedLines {
321     /// The set of changed chunks.
322     pub chunks: Vec<ModifiedChunk>,
323 }
324
325 /// A summary of a Rustfmt run.
326 #[derive(Debug, Default, Clone, Copy)]
327 pub struct Summary {
328     // Encountered e.g. an IO error.
329     has_operational_errors: bool,
330
331     // Failed to reformat code because of parsing errors.
332     has_parsing_errors: bool,
333
334     // Code is valid, but it is impossible to format it properly.
335     has_formatting_errors: bool,
336
337     // Code contains macro call that was unable to format.
338     pub(crate) has_macro_format_failure: bool,
339
340     // Failed a check, such as the license check or other opt-in checking.
341     has_check_errors: bool,
342
343     /// Formatted code differs from existing code (--check only).
344     pub has_diff: bool,
345 }
346
347 impl Summary {
348     pub fn has_operational_errors(&self) -> bool {
349         self.has_operational_errors
350     }
351
352     pub fn has_parsing_errors(&self) -> bool {
353         self.has_parsing_errors
354     }
355
356     pub fn has_formatting_errors(&self) -> bool {
357         self.has_formatting_errors
358     }
359
360     pub fn has_check_errors(&self) -> bool {
361         self.has_check_errors
362     }
363
364     pub(crate) fn has_macro_formatting_failure(&self) -> bool {
365         self.has_macro_format_failure
366     }
367
368     pub fn add_operational_error(&mut self) {
369         self.has_operational_errors = true;
370     }
371
372     pub(crate) fn add_parsing_error(&mut self) {
373         self.has_parsing_errors = true;
374     }
375
376     pub(crate) fn add_formatting_error(&mut self) {
377         self.has_formatting_errors = true;
378     }
379
380     pub(crate) fn add_check_error(&mut self) {
381         self.has_check_errors = true;
382     }
383
384     pub(crate) fn add_diff(&mut self) {
385         self.has_diff = true;
386     }
387
388     pub(crate) fn add_macro_format_failure(&mut self) {
389         self.has_macro_format_failure = true;
390     }
391
392     pub fn has_no_errors(&self) -> bool {
393         !(self.has_operational_errors
394             || self.has_parsing_errors
395             || self.has_formatting_errors
396             || self.has_diff)
397     }
398
399     /// Combine two summaries together.
400     pub fn add(&mut self, other: Summary) {
401         self.has_operational_errors |= other.has_operational_errors;
402         self.has_formatting_errors |= other.has_formatting_errors;
403         self.has_macro_format_failure |= other.has_macro_format_failure;
404         self.has_parsing_errors |= other.has_parsing_errors;
405         self.has_check_errors |= other.has_check_errors;
406         self.has_diff |= other.has_diff;
407     }
408 }
409
410 #[derive(Clone, Copy, Debug)]
411 enum Timer {
412     Initialized(Instant),
413     DoneParsing(Instant, Instant),
414     DoneFormatting(Instant, Instant, Instant),
415 }
416
417 impl Timer {
418     fn done_parsing(self) -> Self {
419         match self {
420             Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
421             _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
422         }
423     }
424
425     fn done_formatting(self) -> Self {
426         match self {
427             Timer::DoneParsing(init_time, parse_time) => {
428                 Timer::DoneFormatting(init_time, parse_time, Instant::now())
429             }
430             _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
431         }
432     }
433
434     /// Returns the time it took to parse the source files in seconds.
435     fn get_parse_time(&self) -> f32 {
436         match *self {
437             Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
438                 // This should never underflow since `Instant::now()` guarantees monotonicity.
439                 Self::duration_to_f32(parse_time.duration_since(init))
440             }
441             Timer::Initialized(..) => unreachable!(),
442         }
443     }
444
445     /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
446     /// not included.
447     fn get_format_time(&self) -> f32 {
448         match *self {
449             Timer::DoneFormatting(_init, parse_time, format_time) => {
450                 Self::duration_to_f32(format_time.duration_since(parse_time))
451             }
452             Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
453         }
454     }
455
456     fn duration_to_f32(d: Duration) -> f32 {
457         d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
458     }
459 }
460
461 // Formatting done on a char by char or line by line basis.
462 // FIXME(#20) other stuff for parity with make tidy
463 fn format_lines(
464     text: &mut String,
465     name: &FileName,
466     skipped_range: &[(usize, usize)],
467     config: &Config,
468     report: &FormatReport,
469 ) {
470     let mut formatter = FormatLines::new(name, skipped_range, config);
471     formatter.check_license(text);
472     formatter.iterate(text);
473
474     if formatter.newline_count > 1 {
475         debug!("track truncate: {} {}", text.len(), formatter.newline_count);
476         let line = text.len() - formatter.newline_count + 1;
477         text.truncate(line);
478     }
479
480     report.append(name.clone(), formatter.errors);
481 }
482
483 struct FormatLines<'a> {
484     name: &'a FileName,
485     skipped_range: &'a [(usize, usize)],
486     last_was_space: bool,
487     line_len: usize,
488     cur_line: usize,
489     newline_count: usize,
490     errors: Vec<FormattingError>,
491     issue_seeker: BadIssueSeeker,
492     line_buffer: String,
493     // true if the current line contains a string literal.
494     is_string: bool,
495     format_line: bool,
496     allow_issue_seek: bool,
497     config: &'a Config,
498 }
499
500 impl<'a> FormatLines<'a> {
501     fn new(
502         name: &'a FileName,
503         skipped_range: &'a [(usize, usize)],
504         config: &'a Config,
505     ) -> FormatLines<'a> {
506         let issue_seeker = BadIssueSeeker::new(config.report_todo(), config.report_fixme());
507         FormatLines {
508             name,
509             skipped_range,
510             last_was_space: false,
511             line_len: 0,
512             cur_line: 1,
513             newline_count: 0,
514             errors: vec![],
515             allow_issue_seek: !issue_seeker.is_disabled(),
516             issue_seeker,
517             line_buffer: String::with_capacity(config.max_width() * 2),
518             is_string: false,
519             format_line: config.file_lines().contains_line(name, 1),
520             config,
521         }
522     }
523
524     fn check_license(&mut self, text: &mut String) {
525         if let Some(ref license_template) = self.config.license_template {
526             if !license_template.is_match(text) {
527                 self.errors.push(FormattingError {
528                     line: self.cur_line,
529                     kind: ErrorKind::LicenseCheck,
530                     is_comment: false,
531                     is_string: false,
532                     line_buffer: String::new(),
533                 });
534             }
535         }
536     }
537
538     // Iterate over the chars in the file map.
539     fn iterate(&mut self, text: &mut String) {
540         for (kind, c) in CharClasses::new(text.chars()) {
541             if c == '\r' {
542                 continue;
543             }
544
545             if self.allow_issue_seek && self.format_line {
546                 // Add warnings for bad todos/ fixmes
547                 if let Some(issue) = self.issue_seeker.inspect(c) {
548                     self.push_err(ErrorKind::BadIssue(issue), false, false);
549                 }
550             }
551
552             if c == '\n' {
553                 self.new_line(kind);
554             } else {
555                 self.char(c, kind);
556             }
557         }
558     }
559
560     fn new_line(&mut self, kind: FullCodeCharKind) {
561         if self.format_line {
562             // Check for (and record) trailing whitespace.
563             if self.last_was_space {
564                 if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
565                     && !self.is_skipped_line()
566                 {
567                     self.push_err(
568                         ErrorKind::TrailingWhitespace,
569                         kind.is_comment(),
570                         kind.is_string(),
571                     );
572                 }
573                 self.line_len -= 1;
574             }
575
576             // Check for any line width errors we couldn't correct.
577             let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
578             if self.line_len > self.config.max_width()
579                 && !self.is_skipped_line()
580                 && self.should_report_error(kind, &error_kind)
581             {
582                 self.push_err(error_kind, kind.is_comment(), self.is_string);
583             }
584         }
585
586         self.line_len = 0;
587         self.cur_line += 1;
588         self.format_line = self
589             .config
590             .file_lines()
591             .contains_line(self.name, self.cur_line);
592         self.newline_count += 1;
593         self.last_was_space = false;
594         self.line_buffer.clear();
595         self.is_string = false;
596     }
597
598     fn char(&mut self, c: char, kind: FullCodeCharKind) {
599         self.newline_count = 0;
600         self.line_len += if c == '\t' {
601             self.config.tab_spaces()
602         } else {
603             1
604         };
605         self.last_was_space = c.is_whitespace();
606         self.line_buffer.push(c);
607         if kind.is_string() {
608             self.is_string = true;
609         }
610     }
611
612     fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
613         self.errors.push(FormattingError {
614             line: self.cur_line,
615             kind,
616             is_comment,
617             is_string,
618             line_buffer: self.line_buffer.clone(),
619         });
620     }
621
622     fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
623         let allow_error_report =
624             if char_kind.is_comment() || self.is_string || error_kind.is_comment() {
625                 self.config.error_on_unformatted()
626             } else {
627                 true
628             };
629
630         match error_kind {
631             ErrorKind::LineOverflow(..) => {
632                 self.config.error_on_line_overflow() && allow_error_report
633             }
634             ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
635             _ => true,
636         }
637     }
638
639     /// Returns true if the line with the given line number was skipped by `#[rustfmt::skip]`.
640     fn is_skipped_line(&self) -> bool {
641         self.skipped_range
642             .iter()
643             .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
644     }
645 }
646
647 fn parse_crate(
648     input: Input,
649     parse_session: &ParseSess,
650     config: &Config,
651     summary: &mut Summary,
652 ) -> Result<ast::Crate, ErrorKind> {
653     let input_is_stdin = input.is_text();
654
655     let mut parser = match input {
656         Input::File(file) => parse::new_parser_from_file(parse_session, &file),
657         Input::Text(text) => parse::new_parser_from_source_str(
658             parse_session,
659             syntax::codemap::FileName::Custom("stdin".to_owned()),
660             text,
661         ),
662     };
663
664     parser.cfg_mods = false;
665     if config.skip_children() {
666         parser.recurse_into_file_modules = false;
667     }
668
669     let mut parser = AssertUnwindSafe(parser);
670     let result = catch_unwind(move || parser.0.parse_crate_mod());
671
672     match result {
673         Ok(Ok(c)) => {
674             if !parse_session.span_diagnostic.has_errors() {
675                 return Ok(c);
676             }
677         }
678         Ok(Err(mut e)) => e.emit(),
679         Err(_) => {
680             // Note that if you see this message and want more information,
681             // then run the `parse_crate_mod` function above without
682             // `catch_unwind` so rustfmt panics and you can get a backtrace.
683             should_emit_verbose(!input_is_stdin, config, || {
684                 println!("The Rust parser panicked")
685             });
686         }
687     }
688
689     summary.add_parsing_error();
690     Err(ErrorKind::ParseError)
691 }
692
693 fn silent_emitter(codemap: Rc<CodeMap>) -> Box<EmitterWriter> {
694     Box::new(EmitterWriter::new(
695         Box::new(Vec::new()),
696         Some(codemap),
697         false,
698         false,
699     ))
700 }
701
702 fn make_parse_sess(codemap: Rc<CodeMap>, config: &Config) -> ParseSess {
703     let tty_handler = if config.hide_parse_errors() {
704         let silent_emitter = silent_emitter(codemap.clone());
705         Handler::with_emitter(true, false, silent_emitter)
706     } else {
707         let supports_color = term::stderr().map_or(false, |term| term.supports_color());
708         let color_cfg = if supports_color {
709             ColorConfig::Auto
710         } else {
711             ColorConfig::Never
712         };
713         Handler::with_tty_emitter(color_cfg, true, false, Some(codemap.clone()))
714     };
715
716     ParseSess::with_span_handler(tty_handler, codemap)
717 }
718
719 fn replace_with_system_newlines(text: &mut String, config: &Config) -> () {
720     let style = if config.newline_style() == NewlineStyle::Native {
721         if cfg!(windows) {
722             NewlineStyle::Windows
723         } else {
724             NewlineStyle::Unix
725         }
726     } else {
727         config.newline_style()
728     };
729
730     match style {
731         NewlineStyle::Unix => return,
732         NewlineStyle::Windows => {
733             let mut transformed = String::with_capacity(text.capacity());
734             for c in text.chars() {
735                 match c {
736                     '\n' => transformed.push_str("\r\n"),
737                     '\r' => continue,
738                     c => transformed.push(c),
739                 }
740             }
741             *text = transformed;
742         }
743         NewlineStyle::Native => unreachable!(),
744     }
745 }
746
747 fn should_emit_verbose<F>(is_stdin: bool, config: &Config, f: F)
748 where
749     F: Fn(),
750 {
751     if config.verbose() == Verbosity::Verbose && !is_stdin {
752         f();
753     }
754 }