{"id":"3f5feb9fade3ae3c","repo":"rust-lang/rust","slug":"const-cnst-cannot-be-encoded-as-u64","errorCode":null,"errorMessage":"Const `{cnst:?}` cannot be encoded as u64","messagePattern":"Const `(.+?)` cannot be encoded as u64","errorType":"exception","errorClass":"B::Error","httpStatus":null,"severity":"error","filePath":"compiler/rustc_public_bridge/src/context/impls.rs","lineNumber":451,"sourceCode":"    pub fn coroutine_discr_for_variant(\n        &self,\n        coroutine: DefId,\n        args: GenericArgsRef<'tcx>,\n        variant: rustc_abi::VariantIdx,\n    ) -> Discr<'tcx> {\n        args.as_coroutine().discriminant_for_variant(coroutine, self.tcx, variant)\n    }\n\n    /// The name of a variant.\n    pub fn variant_name(&self, def: &'tcx VariantDef) -> String {\n        def.name.to_string()\n    }\n\n    /// Evaluate constant as a target usize.\n    pub fn eval_target_usize(&self, cnst: MirConst<'tcx>) -> Result<u64, B::Error> {\n        use crate::context::TypingEnvHelpers;\n        cnst.try_eval_target_usize(self.tcx, self.fully_monomorphized())\n            .ok_or_else(|| B::Error::new(format!(\"Const `{cnst:?}` cannot be encoded as u64\")))\n    }\n\n    pub fn eval_target_usize_ty(&self, cnst: ty::Const<'tcx>) -> Result<u64, B::Error> {\n        cnst.try_to_target_usize(self.tcx)\n            .ok_or_else(|| B::Error::new(format!(\"Const `{cnst:?}` cannot be encoded as u64\")))\n    }\n\n    pub fn try_new_const_zst(&self, ty_internal: Ty<'tcx>) -> Result<MirConst<'tcx>, B::Error> {\n        let size = self\n            .tcx\n            .layout_of(self.fully_monomorphized().as_query_input(ty_internal))\n            .map_err(|err| {\n                B::Error::new(format!(\n                    \"Cannot create a zero-sized constant for type `{ty_internal}`: {err}\"\n                ))\n            })?\n            .size;\n        if size.bytes() != 0 {","sourceCodeStart":433,"sourceCodeEnd":469,"githubUrl":"https://github.com/rust-lang/rust/blob/22057b88b091743bc0fd8d592a9264f0a6951403/compiler/rustc_public_bridge/src/context/impls.rs#L433-L469","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"// before\nlet n: u64 = cx.eval_target_usize(cnst)?;\n// after\nlet n: u64 = cnst\n    .try_eval_target_usize(cx.tcx, cx.fully_monomorphized())\n    .ok_or_else(|| format!(\"unevaluable const: {cnst:?}\"))?\n    .into();","handlingStrategy":"validation","validationCode":"// Before MirConst::eval_target_usize():\nuse rustc_public::ty::{TyKind, UintTy};\nlet ty = mir_const.ty();\nif !matches!(ty.kind(), TyKind::Uint(UintTy::Usize)) {\n    return Err(format!(\"const type {:?} is not usize\", ty));\n}\n// Ensure the const is already evaluated (not Unevaluated/Param):\nif matches!(mir_const.kind(), ConstantKind::Unevaluated(..)) {\n    return Err(\"const is unevaluated; evaluate before reading as usize\".into());\n}\nlet v = mir_const.eval_target_usize()?;","typeGuard":"// Narrows a MirConst to one plausibly decodable as a target usize.\nfn evaluable_as_usize(c: &MirConst) -> bool {\n    matches!(c.ty().kind(), TyKind::Uint(UintTy::Usize))\n        && !matches!(c.kind(), ConstantKind::Unevaluated(..) | ConstantKind::Param(..))\n}","tryCatchPattern":"match mir_const.eval_target_usize() {\n    Ok(n) => n,\n    Err(e) if e.to_string().contains(\"cannot be encoded as u64\") => {\n        // Const is generic/unevaluated/non-usize; skip or re-evaluate.\n        return default_usize();\n    }\n    Err(e) => return Err(e.into()),\n}","preventionTips":["`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."],"tags":["rust","const","usize","mir"],"analyzedSha":"22057b88b091743bc0fd8d592a9264f0a6951403","analyzedAt":"2026-08-03T08:09:25.915Z","schemaVersion":2}