Skip to main content

rustfmt_nightly/
formatting.rs

1// High level formatting functions.
2
3use std::collections::HashMap;
4use std::io::{self, Write};
5use std::time::{Duration, Instant};
6
7use rustc_ast::ast;
8use rustc_span::Span;
9use tracing::debug;
10
11use self::newline_style::apply_newline_style;
12use crate::comment::{CharClasses, FullCodeCharKind};
13use crate::config::{Config, FileName, Verbosity};
14use crate::formatting::generated::is_generated_file;
15use crate::modules::Module;
16use crate::parse::parser::{DirectoryOwnership, Parser, ParserError};
17use crate::parse::session::ParseSess;
18use crate::utils::{contains_skip, count_newlines};
19use crate::visitor::FmtVisitor;
20use crate::{ErrorKind, FormatReport, Input, Session, modules, source_file};
21
22mod generated;
23mod newline_style;
24
25// A map of the files of a crate, with their new content
26pub(crate) type SourceFile = Vec<FileRecord>;
27pub(crate) type FileRecord = (FileName, String);
28
29impl<'b, T: Write + 'b> Session<'b, T> {
30    pub(crate) fn format_input_inner(
31        &mut self,
32        input: Input,
33        is_macro_def: bool,
34    ) -> Result<FormatReport, ErrorKind> {
35        if !self.config.version_meets_requirement() {
36            return Err(ErrorKind::VersionMismatch);
37        }
38
39        rustc_span::create_session_if_not_set_then(self.config.edition().into(), |_| {
40            if self.config.disable_all_formatting() {
41                // When the input is from stdin, echo back the input.
42                return match input {
43                    Input::Text(ref buf) => echo_back_stdin(buf),
44                    _ => Ok(FormatReport::new()),
45                };
46            }
47
48            let config = &self.config.clone();
49            let format_result = format_project(input, config, self, is_macro_def);
50
51            format_result.map(|report| {
52                self.errors.add(&report.internal.borrow().1);
53                report
54            })
55        })
56    }
57}
58
59/// Determine if a module should be skipped. True if the module should be skipped, false otherwise.
60fn should_skip_module<T: FormatHandler>(
61    config: &Config,
62    context: &FormatContext<'_, T>,
63    input_is_stdin: bool,
64    main_file: &FileName,
65    path: &FileName,
66    module: &Module<'_>,
67) -> bool {
68    if contains_skip(module.attrs()) {
69        return true;
70    }
71
72    if config.skip_children() && path != main_file {
73        return true;
74    }
75
76    if !input_is_stdin && context.ignore_file(path) {
77        return true;
78    }
79
80    // FIXME(calebcartwright) - we need to determine how we'll handle the
81    // `format_generated_files` option with stdin based input.
82    if !input_is_stdin && !config.format_generated_files() {
83        let source_file = context.psess.span_to_file_contents(module.span);
84        let src = source_file.src.as_ref().expect("SourceFile without src");
85
86        if is_generated_file(src, config) {
87            return true;
88        }
89    }
90
91    false
92}
93
94fn echo_back_stdin(input: &str) -> Result<FormatReport, ErrorKind> {
95    if let Err(e) = io::stdout().write_all(input.as_bytes()) {
96        return Err(From::from(e));
97    }
98    Ok(FormatReport::new())
99}
100
101// Format an entire crate (or subset of the module tree).
102fn format_project<T: FormatHandler>(
103    input: Input,
104    config: &Config,
105    handler: &mut T,
106    is_macro_def: bool,
107) -> Result<FormatReport, ErrorKind> {
108    let mut timer = Timer::start();
109
110    let main_file = input.file_name();
111    let input_is_stdin = main_file == FileName::Stdin;
112
113    let psess = ParseSess::new(config)?;
114    if config.skip_children() && psess.ignore_file(&main_file) {
115        return Ok(FormatReport::new());
116    }
117
118    // Parse the crate.
119    let mut report = FormatReport::new();
120    let directory_ownership = input.to_directory_ownership();
121
122    let krate = match Parser::parse_crate(input, &psess) {
123        Ok(krate) => krate,
124        // Surface parse error via Session (errors are merged there from report)
125        Err(e) => {
126            let forbid_verbose = input_is_stdin || e != ParserError::ParsePanicError;
127            should_emit_verbose(forbid_verbose, config, || {
128                eprintln!("The Rust parser panicked");
129            });
130            report.add_parsing_error();
131            return Ok(report);
132        }
133    };
134
135    let mut context = FormatContext::new(&krate, report, psess, config, handler);
136    let files = modules::ModResolver::new(
137        &context.psess,
138        directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaBlock),
139        !input_is_stdin && !config.skip_children(),
140    )
141    .visit_crate(&krate)?
142    .into_iter()
143    .filter(|(path, module)| {
144        input_is_stdin
145            || !should_skip_module(config, &context, input_is_stdin, &main_file, path, module)
146    })
147    .collect::<Vec<_>>();
148
149    timer = timer.done_parsing();
150
151    // Suppress error output if we have to do any further parsing.
152    context.psess.set_silent_emitter();
153
154    for (path, module) in files {
155        if input_is_stdin && contains_skip(module.attrs()) {
156            return echo_back_stdin(context.psess.snippet_provider(module.span).entire_snippet());
157        }
158        should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
159        context.format_file(path, &module, is_macro_def)?;
160    }
161    timer = timer.done_formatting();
162
163    should_emit_verbose(input_is_stdin, config, || {
164        println!(
165            "Spent {0:.3} secs in the parsing phase, and {1:.3} secs in the formatting phase",
166            timer.get_parse_time(),
167            timer.get_format_time(),
168        )
169    });
170
171    Ok(context.report)
172}
173
174// Used for formatting files.
175struct FormatContext<'a, T: FormatHandler> {
176    krate: &'a ast::Crate,
177    report: FormatReport,
178    psess: ParseSess,
179    config: &'a Config,
180    handler: &'a mut T,
181}
182
183impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
184    fn new(
185        krate: &'a ast::Crate,
186        report: FormatReport,
187        psess: ParseSess,
188        config: &'a Config,
189        handler: &'a mut T,
190    ) -> Self {
191        FormatContext {
192            krate,
193            report,
194            psess,
195            config,
196            handler,
197        }
198    }
199
200    fn ignore_file(&self, path: &FileName) -> bool {
201        self.psess.ignore_file(path)
202    }
203
204    // Formats a single file/module.
205    fn format_file(
206        &mut self,
207        path: FileName,
208        module: &Module<'_>,
209        is_macro_def: bool,
210    ) -> Result<(), ErrorKind> {
211        let snippet_provider = self.psess.snippet_provider(module.span);
212        let mut visitor = FmtVisitor::from_psess(
213            &self.psess,
214            self.config,
215            &snippet_provider,
216            self.report.clone(),
217        );
218        visitor.skip_context.update_with_attrs(&self.krate.attrs);
219        visitor.is_macro_def = is_macro_def;
220        visitor.last_pos = snippet_provider.start_pos();
221        visitor.skip_empty_lines(snippet_provider.end_pos());
222        visitor.format_separate_mod(module, snippet_provider.end_pos());
223
224        debug_assert_eq!(
225            visitor.line_number,
226            count_newlines(&visitor.buffer),
227            "failed in format_file visitor.buffer:\n {:?}",
228            &visitor.buffer
229        );
230
231        // For some reason, the source_map does not include terminating
232        // newlines so we must add one on for each file. This is sad.
233        let num_newlines = count_newlines(&visitor.buffer);
234        if self
235            .config
236            .file_lines()
237            .contains_line(&path, num_newlines + 1)
238        {
239            source_file::append_newline(&mut visitor.buffer);
240        }
241
242        format_lines(
243            &mut visitor.buffer,
244            &path,
245            &visitor.skipped_range.borrow(),
246            self.config,
247            &self.report,
248        );
249
250        apply_newline_style(
251            self.config.newline_style(),
252            &mut visitor.buffer,
253            snippet_provider.entire_snippet(),
254        );
255
256        if visitor.macro_rewrite_failure {
257            self.report.add_macro_format_failure();
258        }
259        self.report
260            .add_non_formatted_ranges(visitor.skipped_range.borrow().clone());
261
262        self.handler.handle_formatted_file(
263            &self.psess,
264            path,
265            visitor.buffer.to_owned(),
266            &mut self.report,
267        )
268    }
269}
270
271// Handle the results of formatting.
272trait FormatHandler {
273    fn handle_formatted_file(
274        &mut self,
275        psess: &ParseSess,
276        path: FileName,
277        result: String,
278        report: &mut FormatReport,
279    ) -> Result<(), ErrorKind>;
280}
281
282impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
283    // Called for each formatted file.
284    fn handle_formatted_file(
285        &mut self,
286        psess: &ParseSess,
287        path: FileName,
288        result: String,
289        report: &mut FormatReport,
290    ) -> Result<(), ErrorKind> {
291        if let Some(ref mut out) = self.out {
292            match source_file::write_file(
293                Some(psess),
294                &path,
295                &result,
296                out,
297                &mut *self.emitter,
298                self.config.newline_style(),
299            ) {
300                Ok(ref result) if result.has_diff => report.add_diff(),
301                Err(e) => {
302                    // Create a new error with path_str to help users see which files failed
303                    let err_msg = format!("{path}: {e}");
304                    return Err(io::Error::new(e.kind(), err_msg).into());
305                }
306                _ => {}
307            }
308        }
309
310        self.source_file.push((path, result));
311        Ok(())
312    }
313}
314
315pub(crate) struct FormattingError {
316    pub(crate) line: usize,
317    pub(crate) kind: ErrorKind,
318    is_comment: bool,
319    is_string: bool,
320    pub(crate) line_buffer: String,
321}
322
323impl FormattingError {
324    pub(crate) fn from_span(span: Span, psess: &ParseSess, kind: ErrorKind) -> FormattingError {
325        FormattingError {
326            line: psess.line_of_byte_pos(span.lo()),
327            is_comment: kind.is_comment(),
328            kind,
329            is_string: false,
330            line_buffer: psess.span_to_first_line_string(span),
331        }
332    }
333
334    pub(crate) fn is_internal(&self) -> bool {
335        match self.kind {
336            ErrorKind::LineOverflow(..)
337            | ErrorKind::TrailingWhitespace
338            | ErrorKind::IoError(_)
339            | ErrorKind::ParseError
340            | ErrorKind::LostComment => true,
341            _ => false,
342        }
343    }
344
345    pub(crate) fn msg_suffix(&self) -> &str {
346        if self.is_comment || self.is_string {
347            "set `error_on_unformatted = false` to suppress \
348             the warning against comments or string literals\n"
349        } else {
350            ""
351        }
352    }
353
354    // (space, target)
355    pub(crate) fn format_len(&self) -> (usize, usize) {
356        match self.kind {
357            ErrorKind::LineOverflow(found, max) => (max, found - max),
358            ErrorKind::TrailingWhitespace
359            | ErrorKind::DeprecatedAttr
360            | ErrorKind::BadAttr
361            | ErrorKind::LostComment => {
362                let trailing_ws_start = self
363                    .line_buffer
364                    .rfind(|c: char| !c.is_whitespace())
365                    .map(|pos| pos + 1)
366                    .unwrap_or(0);
367                (
368                    trailing_ws_start,
369                    self.line_buffer.len() - trailing_ws_start,
370                )
371            }
372            _ => unreachable!(),
373        }
374    }
375}
376
377pub(crate) type FormatErrorMap = HashMap<FileName, Vec<FormattingError>>;
378
379#[derive(Default, Debug, PartialEq)]
380pub(crate) struct ReportedErrors {
381    // Encountered e.g., an IO error.
382    pub(crate) has_operational_errors: bool,
383
384    // Failed to reformat code because of parsing errors.
385    pub(crate) has_parsing_errors: bool,
386
387    // Code is valid, but it is impossible to format it properly.
388    pub(crate) has_formatting_errors: bool,
389
390    // Code contains macro call that was unable to format.
391    pub(crate) has_macro_format_failure: bool,
392
393    // Failed an opt-in checking.
394    pub(crate) has_check_errors: bool,
395
396    /// Formatted code differs from existing code (--check only).
397    pub(crate) has_diff: bool,
398
399    /// Formatted code missed something, like lost comments or extra trailing space
400    pub(crate) has_unformatted_code_errors: bool,
401}
402
403impl ReportedErrors {
404    /// Combine two summaries together.
405    pub(crate) fn add(&mut self, other: &ReportedErrors) {
406        self.has_operational_errors |= other.has_operational_errors;
407        self.has_parsing_errors |= other.has_parsing_errors;
408        self.has_formatting_errors |= other.has_formatting_errors;
409        self.has_macro_format_failure |= other.has_macro_format_failure;
410        self.has_check_errors |= other.has_check_errors;
411        self.has_diff |= other.has_diff;
412        self.has_unformatted_code_errors |= other.has_unformatted_code_errors;
413    }
414}
415
416#[derive(Clone, Copy, Debug)]
417enum Timer {
418    Disabled,
419    Initialized(Instant),
420    DoneParsing(Instant, Instant),
421    DoneFormatting(Instant, Instant, Instant),
422}
423
424impl Timer {
425    fn start() -> Timer {
426        if cfg!(target_arch = "wasm32") {
427            Timer::Disabled
428        } else {
429            Timer::Initialized(Instant::now())
430        }
431    }
432    fn done_parsing(self) -> Self {
433        match self {
434            Timer::Disabled => Timer::Disabled,
435            Timer::Initialized(init_time) => Timer::DoneParsing(init_time, Instant::now()),
436            _ => panic!("Timer can only transition to DoneParsing from Initialized state"),
437        }
438    }
439
440    fn done_formatting(self) -> Self {
441        match self {
442            Timer::Disabled => Timer::Disabled,
443            Timer::DoneParsing(init_time, parse_time) => {
444                Timer::DoneFormatting(init_time, parse_time, Instant::now())
445            }
446            _ => panic!("Timer can only transition to DoneFormatting from DoneParsing state"),
447        }
448    }
449
450    /// Returns the time it took to parse the source files in seconds.
451    fn get_parse_time(&self) -> f32 {
452        match *self {
453            Timer::Disabled => panic!("this platform cannot time execution"),
454            Timer::DoneParsing(init, parse_time) | Timer::DoneFormatting(init, parse_time, _) => {
455                // This should never underflow since `Instant::now()` guarantees monotonicity.
456                Self::duration_to_f32(parse_time.duration_since(init))
457            }
458            Timer::Initialized(..) => unreachable!(),
459        }
460    }
461
462    /// Returns the time it took to go from the parsed AST to the formatted output. Parsing time is
463    /// not included.
464    fn get_format_time(&self) -> f32 {
465        match *self {
466            Timer::Disabled => panic!("this platform cannot time execution"),
467            Timer::DoneFormatting(_init, parse_time, format_time) => {
468                Self::duration_to_f32(format_time.duration_since(parse_time))
469            }
470            Timer::DoneParsing(..) | Timer::Initialized(..) => unreachable!(),
471        }
472    }
473
474    fn duration_to_f32(d: Duration) -> f32 {
475        d.as_secs() as f32 + d.subsec_nanos() as f32 / 1_000_000_000f32
476    }
477}
478
479// Formatting done on a char by char or line by line basis.
480// FIXME(#20): other stuff for parity with make tidy.
481fn format_lines(
482    text: &mut String,
483    name: &FileName,
484    skipped_range: &[(usize, usize)],
485    config: &Config,
486    report: &FormatReport,
487) {
488    let mut formatter = FormatLines::new(name, skipped_range, config);
489    formatter.iterate(text);
490
491    if formatter.newline_count > 1 {
492        debug!("track truncate: {} {}", text.len(), formatter.newline_count);
493        let line = text.len() - formatter.newline_count + 1;
494        text.truncate(line);
495    }
496
497    report.append(name.clone(), formatter.errors);
498}
499
500struct FormatLines<'a> {
501    name: &'a FileName,
502    skipped_range: &'a [(usize, usize)],
503    last_was_space: bool,
504    line_len: usize,
505    cur_line: usize,
506    newline_count: usize,
507    errors: Vec<FormattingError>,
508    line_buffer: String,
509    current_line_contains_string_literal: bool,
510    format_line: bool,
511    config: &'a Config,
512}
513
514impl<'a> FormatLines<'a> {
515    fn new(
516        name: &'a FileName,
517        skipped_range: &'a [(usize, usize)],
518        config: &'a Config,
519    ) -> FormatLines<'a> {
520        FormatLines {
521            name,
522            skipped_range,
523            last_was_space: false,
524            line_len: 0,
525            cur_line: 1,
526            newline_count: 0,
527            errors: vec![],
528            line_buffer: String::with_capacity(config.max_width() * 2),
529            current_line_contains_string_literal: false,
530            format_line: config.file_lines().contains_line(name, 1),
531            config,
532        }
533    }
534
535    // Iterate over the chars in the file map.
536    fn iterate(&mut self, text: &mut String) {
537        for (kind, c) in CharClasses::new(text.chars()) {
538            if c == '\r' {
539                continue;
540            }
541
542            if c == '\n' {
543                self.new_line(kind);
544            } else {
545                self.char(c, kind);
546            }
547        }
548    }
549
550    fn new_line(&mut self, kind: FullCodeCharKind) {
551        if self.format_line {
552            // Check for (and record) trailing whitespace.
553            if self.last_was_space {
554                if self.should_report_error(kind, &ErrorKind::TrailingWhitespace)
555                    && !self.is_skipped_line()
556                {
557                    self.push_err(
558                        ErrorKind::TrailingWhitespace,
559                        kind.is_comment(),
560                        kind.is_string(),
561                    );
562                }
563                self.line_len -= 1;
564            }
565
566            // Check for any line width errors we couldn't correct.
567            let error_kind = ErrorKind::LineOverflow(self.line_len, self.config.max_width());
568            if self.line_len > self.config.max_width()
569                && !self.is_skipped_line()
570                && self.should_report_error(kind, &error_kind)
571            {
572                let is_string = self.current_line_contains_string_literal;
573                self.push_err(error_kind, kind.is_comment(), is_string);
574            }
575        }
576
577        self.line_len = 0;
578        self.cur_line += 1;
579        self.format_line = self
580            .config
581            .file_lines()
582            .contains_line(self.name, self.cur_line);
583        self.newline_count += 1;
584        self.last_was_space = false;
585        self.line_buffer.clear();
586        self.current_line_contains_string_literal = false;
587    }
588
589    fn char(&mut self, c: char, kind: FullCodeCharKind) {
590        self.newline_count = 0;
591        self.line_len += if c == '\t' {
592            self.config.tab_spaces()
593        } else {
594            1
595        };
596        self.last_was_space = c.is_whitespace();
597        self.line_buffer.push(c);
598        if kind.is_string() {
599            self.current_line_contains_string_literal = true;
600        }
601    }
602
603    fn push_err(&mut self, kind: ErrorKind, is_comment: bool, is_string: bool) {
604        self.errors.push(FormattingError {
605            line: self.cur_line,
606            kind,
607            is_comment,
608            is_string,
609            line_buffer: self.line_buffer.clone(),
610        });
611    }
612
613    fn should_report_error(&self, char_kind: FullCodeCharKind, error_kind: &ErrorKind) -> bool {
614        let allow_error_report = if char_kind.is_comment()
615            || self.current_line_contains_string_literal
616            || error_kind.is_comment()
617        {
618            self.config.error_on_unformatted()
619        } else {
620            true
621        };
622
623        match error_kind {
624            ErrorKind::LineOverflow(..) => {
625                self.config.error_on_line_overflow() && allow_error_report
626            }
627            ErrorKind::TrailingWhitespace | ErrorKind::LostComment => allow_error_report,
628            _ => true,
629        }
630    }
631
632    /// Returns `true` if the line with the given line number was skipped by `#[rustfmt::skip]`.
633    fn is_skipped_line(&self) -> bool {
634        self.skipped_range
635            .iter()
636            .any(|&(lo, hi)| lo <= self.cur_line && self.cur_line <= hi)
637    }
638}
639
640fn should_emit_verbose<F>(forbid_verbose_output: bool, config: &Config, f: F)
641where
642    F: Fn(),
643{
644    if config.verbose() == Verbosity::Verbose && !forbid_verbose_output {
645        f();
646    }
647}