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