rustc_parse/lexer/
diagnostics.rs

1use rustc_ast::token::Delimiter;
2use rustc_errors::Diag;
3use rustc_session::parse::ParseSess;
4use rustc_span::Span;
5use rustc_span::source_map::SourceMap;
6
7use super::UnmatchedDelim;
8use crate::errors::MismatchedClosingDelimiter;
9use crate::pprust;
10
11#[derive(Default)]
12pub(super) struct TokenTreeDiagInfo {
13    /// Stack of open delimiters and their spans. Used for error message.
14    pub open_delimiters: Vec<(Delimiter, Span)>,
15    pub unmatched_delims: Vec<UnmatchedDelim>,
16
17    /// Used only for error recovery when arriving to EOF with mismatched braces.
18    pub last_unclosed_found_span: Option<Span>,
19
20    /// Collect empty block spans that might have been auto-inserted by editors.
21    pub empty_block_spans: Vec<Span>,
22
23    /// Collect the spans of braces (Open, Close). Used only
24    /// for detecting if blocks are empty and only braces.
25    pub matching_block_spans: Vec<(Span, Span)>,
26}
27
28pub(super) fn same_indentation_level(sm: &SourceMap, open_sp: Span, close_sp: Span) -> bool {
29    match (sm.span_to_margin(open_sp), sm.span_to_margin(close_sp)) {
30        (Some(open_padding), Some(close_padding)) => open_padding == close_padding,
31        _ => false,
32    }
33}
34
35// When we get a `)` or `]` for `{`, we should emit help message here
36// it's more friendly compared to report `unmatched error` in later phase
37fn report_missing_open_delim(err: &mut Diag<'_>, unmatched_delims: &[UnmatchedDelim]) -> bool {
38    let mut reported_missing_open = false;
39    for unmatch_brace in unmatched_delims.iter() {
40        if let Some(delim) = unmatch_brace.found_delim
41            && matches!(delim, Delimiter::Parenthesis | Delimiter::Bracket)
42        {
43            let missed_open = match delim {
44                Delimiter::Parenthesis => "(",
45                Delimiter::Bracket => "[",
46                _ => unreachable!(),
47            };
48            err.span_label(
49                unmatch_brace.found_span.shrink_to_lo(),
50                format!("missing open `{missed_open}` for this delimiter"),
51            );
52            reported_missing_open = true;
53        }
54    }
55    reported_missing_open
56}
57
58pub(super) fn report_suspicious_mismatch_block(
59    err: &mut Diag<'_>,
60    diag_info: &TokenTreeDiagInfo,
61    sm: &SourceMap,
62    delim: Delimiter,
63) {
64    if report_missing_open_delim(err, &diag_info.unmatched_delims) {
65        return;
66    }
67
68    let mut matched_spans: Vec<(Span, bool)> = diag_info
69        .matching_block_spans
70        .iter()
71        .map(|&(open, close)| (open.with_hi(close.lo()), same_indentation_level(sm, open, close)))
72        .collect();
73
74    // sort by `lo`, so the large block spans in the front
75    matched_spans.sort_by_key(|(span, _)| span.lo());
76
77    // We use larger block whose indentation is well to cover those inner mismatched blocks
78    // O(N^2) here, but we are on error reporting path, so it is fine
79    for i in 0..matched_spans.len() {
80        let (block_span, same_ident) = matched_spans[i];
81        if same_ident {
82            for j in i + 1..matched_spans.len() {
83                let (inner_block, inner_same_ident) = matched_spans[j];
84                if block_span.contains(inner_block) && !inner_same_ident {
85                    matched_spans[j] = (inner_block, true);
86                }
87            }
88        }
89    }
90
91    // Find the innermost span candidate for final report
92    let candidate_span =
93        matched_spans.into_iter().rev().find(|&(_, same_ident)| !same_ident).map(|(span, _)| span);
94
95    if let Some(block_span) = candidate_span {
96        err.span_label(block_span.shrink_to_lo(), "this delimiter might not be properly closed...");
97        err.span_label(
98            block_span.shrink_to_hi(),
99            "...as it matches this but it has different indentation",
100        );
101
102        // If there is a empty block in the mismatched span, note it
103        if delim == Delimiter::Brace {
104            for span in diag_info.empty_block_spans.iter() {
105                if block_span.contains(*span) {
106                    err.span_label(*span, "block is empty, you might have not meant to close it");
107                    break;
108                }
109            }
110        }
111    } else {
112        // If there is no suspicious span, give the last properly closed block may help
113        if let Some(parent) = diag_info.matching_block_spans.last()
114            && diag_info.open_delimiters.last().is_none()
115            && diag_info.empty_block_spans.iter().all(|&sp| sp != parent.0.to(parent.1))
116        {
117            err.span_label(parent.0, "this opening brace...");
118            err.span_label(parent.1, "...matches this closing brace");
119        }
120    }
121}
122
123pub(crate) fn make_unclosed_delims_error(
124    unmatched: UnmatchedDelim,
125    psess: &ParseSess,
126) -> Option<Diag<'_>> {
127    // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to
128    // `unmatched_delims` only for error recovery in the `Parser`.
129    let found_delim = unmatched.found_delim?;
130    let mut spans = vec![unmatched.found_span];
131    if let Some(sp) = unmatched.unclosed_span {
132        spans.push(sp);
133    };
134    let err = psess.dcx().create_err(MismatchedClosingDelimiter {
135        spans,
136        delimiter: pprust::token_kind_to_string(&found_delim.as_close_token_kind()).to_string(),
137        unmatched: unmatched.found_span,
138        opening_candidate: unmatched.candidate_span,
139        unclosed: unmatched.unclosed_span,
140    });
141    Some(err)
142}