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