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