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