Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clarify error on casting larger integers to char #91939

Merged
merged 2 commits into from
Feb 6, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
11 changes: 8 additions & 3 deletions compiler/rustc_error_codes/src/error_codes/E0604.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,16 @@ Erroneous code example:
0u32 as char; // error: only `u8` can be cast as `char`, not `u32`
```

As the error message indicates, only `u8` can be cast into `char`. Example:
`char` is a Unicode Scalar Value, an integer value from 0 to 0xD7FF and
0xE000 to 0x10FFFF. (The gap is for surrogate pairs.) Only `u8` always fits in
those ranges so only `u8` may be cast to `char`.

To allow larger values, use `char::from_u32`, which checks the value is valid.

```
let c = 86u8 as char; // ok!
assert_eq!(c, 'V');
assert_eq!(86u8 as char, 'V'); // ok!
assert_eq!(char::from_u32(0x3B1), Some('α')); // ok!
assert_eq!(char::from_u32(0xD800), None); // not a USV.
```

For more information about casts, take a look at the Type cast section in
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_typeck/src/check/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
self.expr_ty
)
.span_label(self.span, "invalid cast")
.span_help(self.span, "try `char::from_u32` instead")
Copy link
Member

@camelid camelid Dec 14, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should only be suggested if self.expr_ty is u32. Pseudocode:

Suggested change
.span_help(self.span, "try `char::from_u32` instead")
let err = type_error_struct!(...).span_label(...);
if self.expr_ty == fcx.tcx.types.u32 {
err.span_help(self.span, "try `char::from_u32` instead");
}
err.emit();

.emit();
}
CastError::NonScalar => {
Expand Down