rust-lang/rust · error · B::Error
Const `{cnst:?}` cannot be encoded as u64
Error message
Const `{cnst:?}` cannot be encoded as u64 What it means
Thrown by `eval_target_usize` in compiler/rustc_public_bridge/src/context/impls.rs:451 when a `MirConst` cannot be reduced to a concrete target-`usize` value. The bridge calls `try_eval_target_usize` under a fully-monomorphized param env; if that returns `None` (the const is `TooGeneric`, not a usize, or otherwise unevaluable) the error fires. This guards callers that need a real machine integer, such as array-length or switch-target encoding.
Source
Thrown at compiler/rustc_public_bridge/src/context/impls.rs:451
pub fn coroutine_discr_for_variant(
&self,
coroutine: DefId,
args: GenericArgsRef<'tcx>,
variant: rustc_abi::VariantIdx,
) -> Discr<'tcx> {
args.as_coroutine().discriminant_for_variant(coroutine, self.tcx, variant)
}
/// The name of a variant.
pub fn variant_name(&self, def: &'tcx VariantDef) -> String {
def.name.to_string()
}
/// Evaluate constant as a target usize.
pub fn eval_target_usize(&self, cnst: MirConst<'tcx>) -> Result<u64, B::Error> {
use crate::context::TypingEnvHelpers;
cnst.try_eval_target_usize(self.tcx, self.fully_monomorphized())
.ok_or_else(|| B::Error::new(format!("Const `{cnst:?}` cannot be encoded as u64")))
}
pub fn eval_target_usize_ty(&self, cnst: ty::Const<'tcx>) -> Result<u64, B::Error> {
cnst.try_to_target_usize(self.tcx)
.ok_or_else(|| B::Error::new(format!("Const `{cnst:?}` cannot be encoded as u64")))
}
pub fn try_new_const_zst(&self, ty_internal: Ty<'tcx>) -> Result<MirConst<'tcx>, B::Error> {
let size = self
.tcx
.layout_of(self.fully_monomorphized().as_query_input(ty_internal))
.map_err(|err| {
B::Error::new(format!(
"Cannot create a zero-sized constant for type `{ty_internal}`: {err}"
))
})?
.size;
if size.bytes() != 0 {View on GitHub (pinned to 22057b88b0)
Solutions
- Ensure the `MirConst` is fully monomorphized and evaluated before calling `eval_target_usize`.
- Verify the const's type is a target usize before calling; otherwise evaluate via the type-appropriate path.
- Handle the `None`/`Err` case explicitly and skip the item rather than propagating.
Example fix
// before
let n: u64 = cx.eval_target_usize(cnst)?;
// after
let n: u64 = cnst
.try_eval_target_usize(cx.tcx, cx.fully_monomorphized())
.ok_or_else(|| format!("unevaluable const: {cnst:?}"))?
.into(); Defensive patterns
Strategy: validation
Validate before calling
// Before MirConst::eval_target_usize():
use rustc_public::ty::{TyKind, UintTy};
let ty = mir_const.ty();
if !matches!(ty.kind(), TyKind::Uint(UintTy::Usize)) {
return Err(format!("const type {:?} is not usize", ty));
}
// Ensure the const is already evaluated (not Unevaluated/Param):
if matches!(mir_const.kind(), ConstantKind::Unevaluated(..)) {
return Err("const is unevaluated; evaluate before reading as usize".into());
}
let v = mir_const.eval_target_usize()?; Type guard
// Narrows a MirConst to one plausibly decodable as a target usize.
fn evaluable_as_usize(c: &MirConst) -> bool {
matches!(c.ty().kind(), TyKind::Uint(UintTy::Usize))
&& !matches!(c.kind(), ConstantKind::Unevaluated(..) | ConstantKind::Param(..))
} Try / catch
match mir_const.eval_target_usize() {
Ok(n) => n,
Err(e) if e.to_string().contains("cannot be encoded as u64") => {
// Const is generic/unevaluated/non-usize; skip or re-evaluate.
return default_usize();
}
Err(e) => return Err(e.into()),
} Prevention
- `eval_target_usize` only succeeds for constants whose type is `usize` and that are fully evaluated to a concrete value in the current typing environment.
- Reject `ConstantKind::Unevaluated` and `Param` kinds before calling — they will not lower to a u64.
- Run these checks inside a `with(|cx| ...)` block whose typing env is fully monomorphized; generic contexts yield `None` from the evaluator.
When it happens
Trigger: Calling `context.eval_target_usize(mir_const)` on a const whose type is not `usize`/`u64`-compatible, or whose value depends on generic parameters. Encoding an array length, enum discriminant, or switch target from a const that has not been fully evaluated.
Common situations: Processing generic code where the const depends on an unconstrained generic. Passing a `MirConst` of the wrong type (e.g. an `i32` or a `bool`) where a usize is expected. Using a typing environment that is not fully monomorphized.
Related errors
- Item requires monomorphization
- Item kind `{:?}` cannot be converted
- Expected a static item, but found: {value:?}
- {self:?}
- Cannot create a zero-sized constant for type `{ty_internal}`
AI-assisted analysis of rust-lang/rust@22057b88b0 (2026-08-03).
Data as JSON: /data/errors/3f5feb9fade3ae3c.json.
Report an issue: GitHub.