Skip to main content

rustc_parse/parser/expr/
diagnostics.rs

1use std::mem;
2
3use rustc_ast::util::parser::AssocOp;
4use rustc_ast::{BinOpKind, Expr, ExprKind, UnOp, token};
5use rustc_ast_pretty::pprust;
6use rustc_errors::{Applicability, Diag, PResult};
7use rustc_span::{Span, Spanned, respan, sym};
8
9use crate::parser::{AttrWrapper, Parser, SeqSep, token_descr};
10use crate::{diagnostics, exp};
11
12impl<'a> Parser<'a> {
13    /// Recover from numeric literals with leading plus as found in many C-style languages.
14    pub(super) fn recover_from_leading_plus_on_expr_lit(
15        &mut self,
16        lo: Span,
17    ) -> PResult<'a, Box<Expr>> {
18        let mut err = diagnostics::LeadingPlusNotSupported {
19            span: lo,
20            remove_plus: None,
21            add_parentheses: None,
22        };
23        // A block on the LHS might have been intended to be an expression instead.
24        if let Some(sp) = self.psess.complete_stmt_exprs_before_bin_op_lookalike.borrow().get(&lo) {
25            err.add_parentheses = Some(diagnostics::ExprParenthesesNeeded::surrounding(*sp));
26        } else {
27            err.remove_plus = Some(lo);
28        }
29        self.dcx().emit_err(err);
30
31        self.bump(); // `+`
32        self.parse_expr_prefix_common(lo).map(|(_, expr)| expr)
33    }
34
35    pub(super) fn is_mistaken_alpha_logic_un_op(&self) -> bool {
36        self.may_recover()
37            && self.token.is_ident_named(sym::not)
38            && self.look_ahead(1, |t: &token::Token| match t.uninterpolate().kind {
39                // These tokens can start an expression after `!`, but
40                // can't continue an expression after an ident
41                token::Ident(name, kind) => token::ident_can_begin_expr(name, t.span, kind),
42                token::Literal(..) | token::Pound => true,
43                _ => t.is_metavar_expr(),
44            })
45    }
46
47    /// Recover from alphabetic logic operator `not` as found in e.g., Python.
48    pub(super) fn recover_from_alpha_logic_un_op(
49        &mut self,
50        lo: Span,
51    ) -> PResult<'a, (Span, ExprKind)> {
52        let negated_token = self.look_ahead(1, |t| *t);
53
54        let sub_diag = if negated_token.is_numeric_lit() {
55            diagnostics::NotAsNegationOperatorSub::SuggestNotBitwise
56        } else if negated_token.is_bool_lit() {
57            diagnostics::NotAsNegationOperatorSub::SuggestNotLogical
58        } else {
59            diagnostics::NotAsNegationOperatorSub::SuggestNotDefault
60        };
61
62        self.dcx().emit_err(crate::diagnostics::NotAsNegationOperator {
63            negated: negated_token.span,
64            negated_desc: token_descr(&negated_token),
65            // Span the `not` plus trailing whitespace to avoid
66            // trailing whitespace after the `!` in our suggestion
67            sub: sub_diag(
68                self.psess.source_map().span_until_non_whitespace(lo.to(negated_token.span)),
69            ),
70        });
71
72        self.parse_expr_unary(lo, UnOp::Not)
73    }
74
75    /// Recover from bitwise negation operator `~` as found in many C-style languages.
76    pub(super) fn recover_from_tilde_bitwise_neg_op(
77        &mut self,
78        lo: Span,
79    ) -> PResult<'a, (Span, ExprKind)> {
80        self.dcx().emit_err(diagnostics::TildeAsUnaryOperator(lo));
81        self.parse_expr_unary(lo, UnOp::Not)
82    }
83
84    /// Recover from arrow operators as found in C like `ptr->field`.
85    pub(super) fn recover_from_c_arrow_op(
86        &mut self,
87        lo: Span,
88        base: &mut Box<Expr>,
89    ) -> Option<PResult<'a, Box<Expr>>> {
90        if self.may_recover() && self.eat_noexpect(&token::RArrow) {
91            let guar =
92                self.dcx().emit_err(diagnostics::ExprRArrowCall { span: self.prev_token.span });
93            let base = mem::replace(base, self.mk_expr_err(base.span, guar));
94            return Some(self.parse_dot_suffix_expr(lo, base));
95        }
96        None
97    }
98
99    /// Recover from a binary operator after complete statement expression as in `{ 4 } / 2`.
100    pub(super) fn recover_from_bin_op_after_complete_stmt_expr(&self, lhs: &Expr) -> bool {
101        use BinOpKind::*;
102
103        // Starting point: We've just parsed a *complete* stmt expr (e.g., a block like `{ 4 }`).
104
105        let Some(op) = AssocOp::from_token(&self.token) else { return false };
106
107        // We've now encountered a token that could(!) be interpreted as a binary operator. This
108        // could mean that the user intended to write a binary operation where the left operand is
109        // block-like. In that case they would need to parenthesize the LHS or the entire operation
110        // (e.g., `{ 4 } / 2` -> `({ 4 }) / 2` or `({ 4 } / 2)`).
111
112        if op_can_continue_stmt_expr_unambiguously(op) {
113            // We know that the token (e.g., `/`) can't possibly begin a new statement or pattern.
114            // Instead of letting the stmt/pat parser emit a generic & rather confusing diagnostic,
115            // let's emit a more targeted one, and continue parsing the expression.
116
117            self.dcx().emit_err(diagnostics::FoundExprWouldBeStmt {
118                span: self.token.span,
119                token: pprust::token_to_string(&self.token),
120                suggestion: diagnostics::ExprParenthesesNeeded::surrounding(lhs.span),
121            });
122            return true;
123        }
124
125        // The token can begin a new statement or pattern; this means we're on the happy path!
126        // Still, the user might've meant to write a bin op here but we can't tell at this stage of
127        // compilation. So if it's a "common lookalike" let's proactively register it somewhere for
128        // later stages of compilation to potentially retrieve (e.g., in typeck).
129        //
130        // We've left out `BitAnd` because guessing its intent is hard. We can make suggestions
131        // based on the assumption that double-refs are rarely intentional, and closures are
132        // distinct enough that they don't get mixed up with their return value.
133        if let AssocOp::Binary(Add | And | BitOr | Mul | Or | Sub) = op {
134            let sp = self.psess.source_map().start_point(self.token.span);
135            self.psess
136                .complete_stmt_exprs_before_bin_op_lookalike
137                .borrow_mut()
138                .insert(sp, lhs.span);
139        }
140
141        false
142    }
143
144    /// Recover from alphabetic logic operators `and` and `or` as found in e.g., Python and PHP.
145    pub(super) fn recover_from_alpha_logic_bin_op(&self) -> Option<Spanned<AssocOp>> {
146        if self.may_recover()
147            && let Some(ident) = self.token.non_raw_ident()
148        {
149            let (op, sub): (_, fn(_) -> _) = match ident.name {
150                sym::and => (BinOpKind::And, diagnostics::InvalidLogicalOperatorSub::Conjunction),
151                sym::or => (BinOpKind::Or, diagnostics::InvalidLogicalOperatorSub::Disjunction),
152                _ => return None,
153            };
154
155            self.dcx().emit_err(diagnostics::InvalidLogicalOperator {
156                span: self.token.span,
157                incorrect: ident.name,
158                sub: sub(self.token.span),
159            });
160
161            Some(respan(self.token.span, AssocOp::Binary(op)))
162        } else {
163            None
164        }
165    }
166
167    /// Reject `...` being used as an expression operator.
168    pub(super) fn reject_dotdotdot_expr_op(&self) {
169        if self.token == token::DotDotDot {
170            self.dcx().emit_err(diagnostics::DotDotDotExprOp { span: self.token.span });
171        }
172    }
173
174    /// Reject `<-` being used as an expression operator.
175    pub(super) fn reject_larrow_expr_op(&self) {
176        if self.token == token::LArrow {
177            self.dcx().emit_err(diagnostics::LArrowExprOp { span: self.token.span });
178        }
179    }
180
181    /// Recover from strict equality operators `===` and `!==` as found in e.g., JS and PHP.
182    pub(super) fn recover_from_strict_eq_op(&mut self, op: Spanned<AssocOp>) {
183        if let AssocOp::Binary(bop @ BinOpKind::Eq | bop @ BinOpKind::Ne) = op.node
184            && self.token == token::Eq
185            && self.prev_token.span.hi() == self.token.span.lo()
186        {
187            let sp = op.span.to(self.token.span);
188            let sugg = bop.as_str().into();
189            let invalid = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}=", sugg))
    })format!("{sugg}=");
190            self.dcx().emit_err(diagnostics::InvalidComparisonOperator {
191                span: sp,
192                invalid: invalid.clone(),
193                sub: diagnostics::InvalidComparisonOperatorSub::Correctable {
194                    span: sp,
195                    invalid,
196                    correct: sugg,
197                },
198            });
199            self.bump();
200        }
201    }
202
203    /// Recover from inequality operator `<>` ("diamond") as found in e.g., PHP.
204    pub(super) fn recover_from_diamond_ne_op(&mut self) {
205        if let (token::Lt, token::Gt) = (self.prev_token.kind, self.token.kind)
206            && self.prev_token.span.hi() == self.token.span.lo()
207        {
208            let sp = self.prev_token.span.to(self.token.span);
209            self.dcx().emit_err(diagnostics::InvalidComparisonOperator {
210                span: sp,
211                invalid: "<>".into(),
212                sub: diagnostics::InvalidComparisonOperatorSub::Correctable {
213                    span: sp,
214                    invalid: "<>".into(),
215                    correct: "!=".into(),
216                },
217            });
218            self.bump();
219        }
220    }
221
222    /// Recover from comparison operator `<=>` ("spaceship") as found in e.g., C++.
223    pub(super) fn recover_from_spaceship_cmp_op(&mut self) {
224        if let (token::Le, token::Gt) = (self.prev_token.kind, self.token.kind)
225            && self.prev_token.span.hi() == self.token.span.lo()
226        {
227            let sp = self.prev_token.span.to(self.token.span);
228            self.dcx().emit_err(diagnostics::InvalidComparisonOperator {
229                span: sp,
230                invalid: "<=>".into(),
231                sub: diagnostics::InvalidComparisonOperatorSub::Spaceship(sp),
232            });
233            self.bump();
234        }
235    }
236
237    /// Recover from prefix increment operator `++` as found in many C-style languages.
238    pub(super) fn recover_from_prefix_inc_op(
239        &mut self,
240        attrs: AttrWrapper,
241    ) -> PResult<'a, Box<Expr>> {
242        let starts_stmt = self.prev_token == token::Semi || self.prev_token == token::CloseBrace;
243        let pre_span = self.token.span.to(self.look_ahead(1, |t| t.span));
244        // Eat both `+`s.
245        self.bump();
246        self.bump();
247
248        let operand = self.parse_expr_dot_or_call(attrs)?;
249
250        Err(self.report_inc_dec_op(
251            &operand,
252            starts_stmt,
253            IncOrDec::Inc,
254            UnaryFixity::Pre,
255            pre_span,
256        ))
257    }
258
259    /// Recover from postfix increment operator `++` as found in many C-style languages.
260    pub(super) fn recover_from_postfix_inc_op(
261        &mut self,
262        lhs: &Expr,
263        starts_stmt: bool,
264    ) -> PResult<'a, ()> {
265        if let (token::Plus, token::Plus) = (self.prev_token.kind, self.token.kind)
266            && self.prev_token.span.hi() == self.token.span.lo()
267        {
268            let op_span = self.prev_token.span.to(self.token.span);
269            self.bump(); // eat the second `+`
270            Err(self.report_inc_dec_op(lhs, starts_stmt, IncOrDec::Inc, UnaryFixity::Post, op_span))
271        } else {
272            Ok(())
273        }
274    }
275
276    /// Recover from postfix decrement operator `--` as found in many C-style languages.
277    pub(super) fn recover_from_postfix_dec_op(
278        &mut self,
279        lhs: &Expr,
280        starts_stmt: bool,
281    ) -> PResult<'a, ()> {
282        if let (token::Minus, token::Minus) = (self.prev_token.kind, self.token.kind)
283            && self.prev_token.span.hi() == self.token.span.lo()
284            && !self.look_ahead(1, |tok| tok.can_begin_expr())
285        {
286            let op_span = self.prev_token.span.to(self.token.span);
287            self.bump(); // eat the second `-`
288            Err(self.report_inc_dec_op(lhs, starts_stmt, IncOrDec::Dec, UnaryFixity::Post, op_span))
289        } else {
290            Ok(())
291        }
292    }
293
294    /// Report increment operator `++` & decrement operator `--` as found in many C-style languages.
295    fn report_inc_dec_op(
296        &mut self,
297        base: &Expr,
298        starts_stmt: bool,
299        op: IncOrDec,
300        fixity: UnaryFixity,
301        op_span: Span,
302    ) -> Diag<'a> {
303        // FIXME: Don't return an error diag, emit the diag here *and* return a new expr of the form
304        //        `$base += 1` / `$base -= 1` (taking `base: Expr` by value) for *proper* recovery.
305        //        (Just emitting the diag would be insufficient since callers would most likely just
306        //        use `$base` as the recovered AST node which would lead to annoying follow-up diags
307        //        like "variable doesn't need to be mutable" getting emitted in some cases.)
308
309        let mut err = {
310            let fixity = match fixity {
311                UnaryFixity::Pre => "prefix",
312                UnaryFixity::Post => "postfix",
313            };
314            let op = match op {
315                IncOrDec::Inc => "increment",
316                IncOrDec::Dec => "decrement",
317            };
318            self.dcx()
319                .struct_span_err(op_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Rust has no {0} {1} operator",
                fixity, op))
    })format!("Rust has no {fixity} {op} operator"))
320                .with_span_label(op_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("not a valid {0} operator", fixity))
    })format!("not a valid {fixity} operator"))
321        };
322
323        let op = match op {
324            IncOrDec::Inc => "+= 1",
325            IncOrDec::Dec => "-= 1",
326        };
327        let (pre_span, post_span) = match fixity {
328            UnaryFixity::Pre => (op_span, base.span.shrink_to_hi()),
329            UnaryFixity::Post => (base.span.shrink_to_lo(), op_span),
330        };
331
332        if starts_stmt {
333            let mut patches = Vec::new();
334            if !pre_span.is_empty() {
335                patches.push((pre_span, String::new()));
336            }
337            patches.push((post_span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" {0}", op))
    })format!(" {op}")));
338            err.multipart_suggestion(
339                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use `{0}` instead", op))
    })format!("use `{op}` instead"),
340                patches,
341                Applicability::MachineApplicable,
342            );
343        } else {
344            let Ok(base_src) = self.span_to_snippet(base.span) else {
345                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use `{0}` instead", op))
    })format!("use `{op}` instead"));
346                return err;
347            };
348            match fixity {
349                UnaryFixity::Pre => {
350                    err.multipart_suggestion(
351                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use `{0}` instead", op))
    })format!("use `{op}` instead"),
352                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(pre_span, "{ ".into()),
                (post_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(" {0}; {1} }}", op,
                                    base_src))
                        }))]))vec![(pre_span, "{ ".into()), (post_span, format!(" {op}; {base_src} }}"))],
353                        Applicability::MachineApplicable,
354                    );
355                }
356                UnaryFixity::Post => {
357                    // won't suggest since we can not handle the precedences
358                    // for example: `a + b++` has been parsed (a + b)++ and we can not suggest here
359                    if !#[allow(non_exhaustive_omitted_patterns)] match base.kind {
    ExprKind::Binary(..) => true,
    _ => false,
}matches!(base.kind, ExprKind::Binary(..)) {
360                        let tmp_var = if base_src.trim() == "tmp" { "tmp_" } else { "tmp" };
361                        err.multipart_suggestion(
362                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use `{0}` instead", op))
    })format!("use `{op}` instead"),
363                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(pre_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{{ let {0} = ", tmp_var))
                        })),
                (post_span,
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("; {0} {1}; {2} }}",
                                    base_src, op, tmp_var))
                        }))]))vec![
364                                (pre_span, format!("{{ let {tmp_var} = ")),
365                                (post_span, format!("; {base_src} {op}; {tmp_var} }}")),
366                            ],
367                            Applicability::HasPlaceholders,
368                        );
369                    }
370                }
371            }
372        }
373        err
374    }
375
376    /// Recover from array expressions as found in C like `{0, 1, 2, 3}`.
377    pub(super) fn recover_from_c_array(&mut self, lo: Span) -> Option<Box<Expr>> {
378        if !self.may_recover()
379            || self.token.kind != token::OpenBrace
380            || self.look_ahead(1, |t| !#[allow(non_exhaustive_omitted_patterns)] match t.kind {
    token::Literal(_) => true,
    _ => false,
}matches!(t.kind, token::Literal(_)))
381            || self.look_ahead(2, |t| t != &token::Comma)
382            || self.look_ahead(3, |t| !t.can_begin_expr())
383        {
384            return None;
385        }
386
387        let mut snapshot = self.create_snapshot_for_diagnostic();
388        match snapshot.parse_expr_array_or_repeat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBrace,
    token_type: crate::parser::token_type::TokenType::CloseBrace,
}exp!(CloseBrace)) {
389            Ok(arr) => {
390                let guar = self.dcx().emit_err(diagnostics::ArrayBracketsInsteadOfBraces {
391                    span: arr.span,
392                    sub: diagnostics::ArrayBracketsInsteadOfBracesSugg {
393                        left: lo,
394                        right: snapshot.prev_token.span,
395                    },
396                });
397
398                self.restore_snapshot(snapshot);
399                Some(self.mk_expr_err(arr.span, guar))
400            }
401            Err(e) => {
402                e.cancel();
403                None
404            }
405        }
406    }
407
408    pub(super) fn recover_from_missing_semicolon_before_array(
409        &self,
410        prev_span: Span,
411        open_delim_span: Span,
412    ) -> PResult<'a, ()> {
413        if !self.may_recover()
414            || self.token != token::Comma
415            // Only make this suggestion if the `[` is not on the same line as the last token of
416            // the expression preceding it, which is a sign that it is not intended as an
417            // index expression.
418            || !self.psess.source_map().is_multiline(prev_span.until(open_delim_span))
419        {
420            return Ok(());
421        }
422
423        let mut snapshot = self.create_snapshot_for_diagnostic();
424        snapshot.bump();
425        match snapshot.parse_seq_to_before_end(
426            crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket),
427            SeqSep::trailing_allowed(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)),
428            |p| p.parse_expr(),
429        ) {
430            Ok(_)
431                // When the close delim is `)`, `token.kind` is expected to be `token::CloseParen`,
432                // but the actual `token.kind` is `token::CloseBracket`. This is because the
433                // `token.kind` of the close delim is treated as the same as that of the open delim
434                // in `TokenTreesReader::parse_token_tree`, even if the delimiters of them are
435                // different. Therefore, `token.kind` should not be compared here.
436                if snapshot
437                    .span_to_snippet(snapshot.token.span)
438                    .is_ok_and(|snippet| snippet == "]") =>
439            {
440                // FIXME: This is way to assertive for a diagnostic with so many false positives!
441                //        Just `expect(Comma)` and modify the diagnostic with a note that says sth.
442                //        along the lines of "consider adding a `;` here if you meant the `[...]` to
443                //        denote an array instead of an index".
444                // FIXME: In most cases there certainly isn't a "missing `;`". E.g., if we're nested
445                //        in an expression like `(x[y, z])` or `match x[y, z] {}`. Requiring that
446                //        we're not under `Restriction::STMT_EXPR` isn't sufficient by the way since
447                //        we could still be part of a match arm body *and* it would prevent us from
448                //        suggesting a `;` in cases like `let x = y[z, w];`.
449                Err(self.dcx().create_err(crate::diagnostics::MissingSemicolonBeforeArray {
450                    open_delim: open_delim_span,
451                    semicolon: prev_span.shrink_to_hi(),
452                }))
453            }
454            Ok(_) => Ok(()),
455            Err(err) => {
456                err.cancel();
457                Ok(())
458            }
459        }
460    }
461}
462
463/// Whether this operator could be used to follow a complete statement expression unambiguously
464/// during parse error recovery.
465pub(in crate::parser) fn op_can_continue_stmt_expr_unambiguously(op: AssocOp) -> bool {
466    // NOTE: At the time of writing, it's only safe to return `true` for tokens that don't share a
467    //       prefix with statements or patterns. For context, statement lists and match arm bodies
468    //       are (the only two) places that use `Restriction::STMT_EXPR` (in the happy path).
469
470    use BinOpKind::*;
471    match op {
472        AssocOp::Assign | AssocOp::AssignOp(_) | AssocOp::Cast => true,
473        AssocOp::Binary(bin_op) => match bin_op {
474            | BitXor | Div | Ge | Gt | Le | Rem | Shr => true,
475            | Add // unambiguous but would inhibit our recovery from unary plus
476            | And // `&&` starts repeated borrow (e.g., `&&x`)
477            | BitAnd // `&` starts borrow (e.g., `&x`)
478            | BitOr // `|` starts closure (e.g., `|_| ()`) or leading vert (e.g., `| Some(_)`)
479            | Eq | Ne // unambiguous but would inhibit our recovery from bad struct literals
480            | Lt // `<` starts qualified path (e.g., `<T as X>::P`)
481            | Mul // `*` starts unary deref (e.g., `*x`, `*x = 0`)
482            | Or // `||` starts parameterless closure (e.g. `|| 0`)
483            | Shl // `<<` starts repeated qualified path (e.g., `<<T>::Q as X>::P`)
484            | Sub => false, // `-` starts unary negation (e.g, `-x`)
485        },
486        AssocOp::Range(_) => false, // `..`/`..=` start ranges w/o lower bound (e.g., `..`, `..=1`)
487    }
488}
489
490#[derive(#[automatically_derived]impl ::core::marker::Copy for IncOrDec { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for IncOrDec {
}
#[automatically_derived]impl ::core::clone::Clone for IncOrDec {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
491pub(super) enum IncOrDec {
492    Inc,
493    Dec,
494}
495
496#[derive(#[automatically_derived]impl ::core::marker::Copy for UnaryFixity { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for UnaryFixity {
}
#[automatically_derived]impl ::core::clone::Clone for UnaryFixity {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
497pub(super) enum UnaryFixity {
498    Pre,
499    Post,
500}