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