diff --git a/compiler/rustc_hir_typeck/src/op.rs b/compiler/rustc_hir_typeck/src/op.rs index d96053e8ffbb3..168672e01e794 100644 --- a/compiler/rustc_hir_typeck/src/op.rs +++ b/compiler/rustc_hir_typeck/src/op.rs @@ -14,6 +14,7 @@ use rustc_middle::ty::adjustment::{ use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{self, IsSuggestable, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::{Span, Spanned, Symbol, bug, sym}; +use rustc_trait_selection::error_reporting::traits::suggestions; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{FulfillmentError, Obligation, ObligationCtxt}; use tracing::debug; @@ -391,6 +392,34 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.param_env, ); self.note_unmet_impls_on_type(&mut err, &errors, false); + // `char` has no arithmetic assign impls, so the result has to be built + // through an integer. `u32 as char` is not allowed, hence `char::from_u32`. + if lhs_ty.is_char() && rhs_ty.is_integral() { + let op = match assign_op.node { + AssignOpKind::AddAssign => Some("+"), + AssignOpKind::SubAssign => Some("-"), + AssignOpKind::MulAssign => Some("*"), + AssignOpKind::DivAssign => Some("/"), + AssignOpKind::RemAssign => Some("%"), + _ => None, + }; + let source_map = self.tcx.sess.source_map(); + if let Some(op) = op + && !lhs_expr.span.from_expansion() + && !rhs_expr.span.from_expansion() + && let Ok(lhs) = source_map.span_to_snippet(lhs_expr.span) + && let Ok(rhs) = source_map.span_to_snippet(rhs_expr.span) + { + err.span_suggestion_verbose( + expr.span, + "convert the `char` through an integer", + format!( + "{lhs} = char::from_u32(({lhs} as u32) {op} {rhs}).unwrap()" + ), + Applicability::MaybeIncorrect, + ); + } + } (err, None) } } @@ -467,6 +496,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .any(|(ty, _)| is_compatible_after_call(ty, rhs_ty)) }, ); + // a `char` on the left has no arithmetic impl to probe, so it lands here + // instead of being reported by trait selection as an E0277 + if lhs_ty.is_char() && rhs_ty.is_integral() { + suggestions::suggest_cast_char_to_int(&mut err, lhs_expr.span, rhs_ty); + } (err, output_def_id) } }; diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 7c9d8ee17254c..63f3b496c7815 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -540,6 +540,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { &mut err, leaf_trait_predicate, ); + suggested |= self.suggest_binop_char_cast( + &obligation, + &mut err, + leaf_trait_predicate, + ); suggested |= self.suggest_dereferences(&obligation, &mut err, leaf_trait_predicate) || self.suggest_remove_reference( diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index 3e7dede0ccc0a..64df662989bdf 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -52,6 +52,39 @@ use crate::infer::InferCtxtExt as _; use crate::traits::query::evaluate_obligation::InferCtxtExt as _; use crate::traits::{ImplDerivedCause, NormalizeExt, ObligationCtxt, SelectionContext}; +/// Suggest casting a `char` operand of an arithmetic operator to the integer it is used with +pub fn suggest_cast_char_to_int(err: &mut Diag<'_>, char_span: Span, int_ty: Ty<'_>) -> bool { + if char_span.from_expansion() { + return false; + } + + // an unconstrained integer defaults to `u32`, which holds every `char` + let target = match int_ty.kind() { + ty::Infer(InferTy::IntVar(_)) => "u32".to_owned(), + ty::Int(_) | ty::Uint(_) => int_ty.to_string(), + _ => return false, + }; + let lossless = matches!( + int_ty.kind(), + ty::Infer(InferTy::IntVar(_)) + | ty::Uint(ty::UintTy::U32 | ty::UintTy::U64 | ty::UintTy::U128) + | ty::Int(ty::IntTy::I32 | ty::IntTy::I64 | ty::IntTy::I128) + ); + let msg = if lossless { + format!("you can cast the `char` to a `{target}`, since a `char` always occupies 4 bytes") + } else { + format!("you can cast the `char` to a `{target}`, truncating the code point") + }; + + err.span_suggestion_verbose( + char_span.shrink_to_hi(), + msg, + format!(" as {target}"), + if lossless { Applicability::MachineApplicable } else { Applicability::MaybeIncorrect }, + ); + true +} + #[derive(Debug)] pub enum CoroutineInteriorOrUpvar { // span of interior type @@ -5131,6 +5164,46 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } + /// Suggest casting the `char` operand of an arithmetic operator, as in `output += c` + pub(super) fn suggest_binop_char_cast( + &self, + obligation: &PredicateObligation<'tcx>, + err: &mut Diag<'_>, + trait_pred: ty::PolyTraitClause<'tcx>, + ) -> bool { + let ObligationCauseCode::BinOp { rhs_hir_id, .. } = obligation.cause.code().peel_derives() + else { + return false; + }; + + let lang = self.tcx.lang_items(); + if ![ + lang.add_trait(), + lang.sub_trait(), + lang.mul_trait(), + lang.div_trait(), + lang.rem_trait(), + lang.add_assign_trait(), + lang.sub_assign_trait(), + lang.mul_assign_trait(), + lang.div_assign_trait(), + lang.rem_assign_trait(), + ] + .contains(&Some(trait_pred.def_id())) + { + return false; + } + + let trait_pred = trait_pred.skip_binder(); + let int_ty = trait_pred.self_ty(); + if !trait_pred.trait_ref.args.type_at(1).is_char() || !int_ty.is_integral() { + return false; + } + + let Node::Expr(char_expr) = self.tcx.hir_node(*rhs_hir_id) else { return false }; + suggest_cast_char_to_int(err, char_expr.span, int_ty) + } + pub fn can_suggest_derive( &self, obligation: &PredicateObligation<'tcx>, diff --git a/tests/ui/binop/char-arith-suggest-cast.rs b/tests/ui/binop/char-arith-suggest-cast.rs new file mode 100644 index 0000000000000..187ebb631d126 --- /dev/null +++ b/tests/ui/binop/char-arith-suggest-cast.rs @@ -0,0 +1,26 @@ +fn main() { + let greeting = "Hello, World!"; + let mut output = 0; + for c in greeting.chars() { + output += c; + //~^ ERROR cannot add-assign `char` to `{integer}` + } + + let mut sum: u32 = 0; + sum += 'a'; + //~^ ERROR cannot add-assign `char` to `u32` + + let _ = 5 + '0'; + //~^ ERROR cannot add `char` to `{integer}` + + let _ = 'a' + 5; + //~^ ERROR cannot add `{integer}` to `char` + + let mut small: u8 = 0; + small += 'a'; + //~^ ERROR cannot add-assign `char` to `u8` + + let mut ch = 'a'; + ch += 5; + //~^ ERROR binary assignment operation `+=` cannot be applied to type `char` +} diff --git a/tests/ui/binop/char-arith-suggest-cast.stderr b/tests/ui/binop/char-arith-suggest-cast.stderr new file mode 100644 index 0000000000000..98c286ca37eb4 --- /dev/null +++ b/tests/ui/binop/char-arith-suggest-cast.stderr @@ -0,0 +1,79 @@ +error[E0277]: cannot add-assign `char` to `{integer}` + --> $DIR/char-arith-suggest-cast.rs:5:16 + | +LL | output += c; + | ^^ no implementation for `{integer} += char` + | + = help: the trait `AddAssign` is not implemented for `{integer}` +help: you can cast the `char` to a `u32`, since a `char` always occupies 4 bytes + | +LL | output += c as u32; + | ++++++ + +error[E0277]: cannot add-assign `char` to `u32` + --> $DIR/char-arith-suggest-cast.rs:10:9 + | +LL | sum += 'a'; + | ^^ no implementation for `u32 += char` + | + = help: the trait `AddAssign` is not implemented for `u32` +help: you can cast the `char` to a `u32`, since a `char` always occupies 4 bytes + | +LL | sum += 'a' as u32; + | ++++++ + +error[E0277]: cannot add `char` to `{integer}` + --> $DIR/char-arith-suggest-cast.rs:13:15 + | +LL | let _ = 5 + '0'; + | ^ no implementation for `{integer} + char` + | + = help: the trait `Add` is not implemented for `{integer}` +help: you can cast the `char` to a `u32`, since a `char` always occupies 4 bytes + | +LL | let _ = 5 + '0' as u32; + | ++++++ + +error[E0369]: cannot add `{integer}` to `char` + --> $DIR/char-arith-suggest-cast.rs:16:17 + | +LL | let _ = 'a' + 5; + | --- ^ - {integer} + | | + | char + | +help: you can cast the `char` to a `u32`, since a `char` always occupies 4 bytes + | +LL | let _ = 'a' as u32 + 5; + | ++++++ + +error[E0277]: cannot add-assign `char` to `u8` + --> $DIR/char-arith-suggest-cast.rs:20:11 + | +LL | small += 'a'; + | ^^ no implementation for `u8 += char` + | + = help: the trait `AddAssign` is not implemented for `u8` +help: you can cast the `char` to a `u8`, truncating the code point + | +LL | small += 'a' as u8; + | +++++ + +error[E0368]: binary assignment operation `+=` cannot be applied to type `char` + --> $DIR/char-arith-suggest-cast.rs:24:5 + | +LL | ch += 5; + | --^^^^^ + | | + | cannot use `+=` on type `char` + | +help: convert the `char` through an integer + | +LL - ch += 5; +LL + ch = char::from_u32((ch as u32) + 5).unwrap(); + | + +error: aborting due to 6 previous errors + +Some errors have detailed explanations: E0277, E0368, E0369. +For more information about an error, try `rustc --explain E0277`.