{"record":{"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":462,"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":444,"sourceCodeEnd":480,"githubUrl":"https://github.com/rust-lang/rust/blob/7088e4b63a9516ebfbfe2ab2d999cf01a528ac14/compiler/rustc_public_bridge/src/context/impls.rs#L444-L480","documentation":"Thrown by `eval_target_usize` (impls.rs:462) when a `MirConst` cannot be evaluated to a concrete target `usize` (u64). `try_eval_target_usize` returns `None` when the constant is unevaluated, too generic, or not an integer-like scalar.","triggerScenarios":"Calling `eval_target_usize` on a MIR constant that is `Unevaluated`, depends on generic params (TooGeneric), or holds a non-scalar/aggregate value that cannot be read as a usize.","commonSituations":"Reading array lengths, enum discriminants, or padding from generic MIR during analysis; evaluating constants from upstream crates whose bodies are not available.","solutions":["Confirm the constant is fully monomorphized and has been evaluated before requesting a usize.","If the value may legitimately be non-integer, branch on the const's kind and only call `eval_target_usize` for scalar integer consts.","Use `try_eval_target_usize` directly and handle `None` instead of erroring."],"exampleFix":"// before\nlet n: u64 = ctxt.eval_target_usize(cnst)?;\n\n// after\nlet n: u64 = match cnst.try_eval_target_usize(ctxt.tcx, typing_env) {\n    Some(v) => v,\n    None => return Ok(default_len), // constant is unevaluated/generic\n};","handlingStrategy":"try-catch","validationCode":"// Only request usize encoding for constants that actually evaluate to a scalar.\nlet opt = cnst.try_eval_target_usize(tcx, typing_env);\nif opt.is_none() {\n    return Ok(0); // or skip this constant\n}","typeGuard":"fn is_evaluable_usize<'tcx>(cnst: &MirConst<'tcx>, tcx: TyCtxt<'tcx>, env: TypingEnv<'tcx>) -> bool {\n    cnst.try_eval_target_usize(tcx, env).is_some()\n}","tryCatchPattern":"let v = ctxt.eval_target_usize(cnst).unwrap_or_else(|_| {\n    // constant could not be encoded; use a fallback or propagate\n    0\n});","preventionTips":["Evaluate/normalize constants before assuming they are concrete integers.","Prefer the underlying try_eval_* helpers that return Option when None is a normal case."],"tags":["rustc-public-bridge","const-eval","mir","usize"],"backgroundTag":null,"analyzedSha":"7088e4b63a9516ebfbfe2ab2d999cf01a528ac14","analyzedAt":"2026-08-10T14:17:03.603Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}