Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions compiler/rustc_hir_typeck/src/op.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
}
}
Expand Down Expand Up @@ -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)
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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>,
Expand Down
26 changes: 26 additions & 0 deletions tests/ui/binop/char-arith-suggest-cast.rs
Original file line number Diff line number Diff line change
@@ -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`
}
79 changes: 79 additions & 0 deletions tests/ui/binop/char-arith-suggest-cast.stderr
Original file line number Diff line number Diff line change
@@ -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<char>` 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<char>` 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<char>` 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<char>` 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`.
Loading