{"id":"fbc2c2bdbe79e597","repo":"rust-lang/rust","slug":"value-overflow-cannot-convert-value-to-ty-i","errorCode":null,"errorMessage":"Value overflow: cannot convert `{value}` to `{ty_internal}`.","messagePattern":"Value overflow: cannot convert `(.+?)` to `(.+?)`\\.","errorType":"exception","errorClass":"B::Error","httpStatus":null,"severity":"error","filePath":"compiler/rustc_public_bridge/src/context/impls.rs","lineNumber":520,"sourceCode":"    }\n\n    /// Create a new constant that represents the given boolean value.\n    pub fn new_const_bool(&self, value: bool) -> MirConst<'tcx> {\n        MirConst::from_bool(self.tcx, value)\n    }\n\n    pub fn try_new_const_uint(\n        &self,\n        value: u128,\n        ty_internal: Ty<'tcx>,\n    ) -> Result<MirConst<'tcx>, B::Error> {\n        let size = self\n            .tcx\n            .layout_of(self.fully_monomorphized().as_query_input(ty_internal))\n            .unwrap()\n            .size;\n        let scalar = ScalarInt::try_from_uint(value, size).ok_or_else(|| {\n            B::Error::new(format!(\"Value overflow: cannot convert `{value}` to `{ty_internal}`.\"))\n        })?;\n        Ok(self.mir_const_from_scalar(Scalar::Int(scalar), ty_internal))\n    }\n\n    pub fn try_new_ty_const_uint(\n        &self,\n        value: u128,\n        ty_internal: Ty<'tcx>,\n    ) -> Result<ty::Const<'tcx>, B::Error> {\n        let size = self\n            .tcx\n            .layout_of(self.fully_monomorphized().as_query_input(ty_internal))\n            .unwrap()\n            .size;\n        let scalar = ScalarInt::try_from_uint(value, size).ok_or_else(|| {\n            B::Error::new(format!(\"Value overflow: cannot convert `{value}` to `{ty_internal}`.\"))\n        })?;\n","sourceCodeStart":502,"sourceCodeEnd":538,"githubUrl":"https://github.com/rust-lang/rust/blob/22057b88b091743bc0fd8d592a9264f0a6951403/compiler/rustc_public_bridge/src/context/impls.rs#L502-L538","documentation":"Thrown by `try_new_const_uint` in compiler/rustc_public_bridge/src/context/impls.rs:520 when a `u128` value does not fit into the target integer type's bit width. The bridge computes the type's layout size and calls `ScalarInt::try_from_uint(value, size)`; if the value exceeds the type's maximum (e.g. 256 into a `u8`), the conversion returns `None` and the error is raised. This guards against silent truncation when materializing an unsigned integer constant.","triggerScenarios":"Calling `context.try_new_const_uint(value, ty)` where `value` exceeds the type's range — e.g. `try_new_const_uint(256, u8_ty)`, `try_new_const_uint(u128::MAX, u16_ty)`. Feeding externally sourced `u128` values into typed const construction without bounds-checking.","commonSituations":"Deserializing constants from JSON/external data where the value width is not validated against the target type. Mismatched target type (passing `u8_ty` when the value needs `u32`). Off-by-one or inclusive-bound bugs in value generation.","solutions":["Bounds-check the value against the target type's maximum (`1u128 << (8 * size.bytes()) - 1`) before calling.","If the value legitimately needs more bits, widen the target type (e.g. `u8` -> `u32`) to fit it.","Clamp or reject out-of-range values upstream in the data source."],"exampleFix":"// before\nlet c = cx.try_new_const_uint(value, ty_u8)?;\n// after\nlet max = (1u128 << (8 * size_bytes)) - 1;\nlet c = cx.try_new_const_uint(value.min(max), ty_u8)?;","handlingStrategy":"validation","validationCode":"// Before MirConst::try_from_uint(value, uint_ty):\n// NOTE: the internal impl does layout_of(...).unwrap() (impls.rs:517), so a\n// non-computable layout PANICS before the overflow check. Compute the layout\n// yourself first, then range-check the value.\nlet layout = ty.layout()?;                 // surfaces layout errors safely\nlet size = layout.shape().size;            // MachineSize\nlet max = size.unsigned_int_max()\n    .ok_or_else(|| format!(\"{:?} is wider than 128 bits\", ty))?;\nif value > max {\n    return Err(format!(\"value {} overflows {:?} (max {})\", value, ty, max));\n}\nlet c = MirConst::try_from_uint(value, uint_ty)?;","typeGuard":null,"tryCatchPattern":"// try_from_uint returns Result for overflow, but PANICS on layout failure,\n// so wrap untrusted types in catch_unwind as a last line of defense:\nmatch std::panic::catch_unwind(|| MirConst::try_from_uint(value, uint_ty)) {\n    Ok(Ok(c)) => c,\n    Ok(Err(e)) if e.to_string().contains(\"Value overflow\") => {\n        // Clamp or reject the value; do NOT retry unchanged.\n        return MirConst::try_from_uint(value.clamp(0, max_for(uint_ty)?), uint_ty);\n    }\n    Ok(Err(e)) => return Err(e.into()),\n    Err(_) => return Err(format!(\"layout of {:?} could not be computed\", uint_ty)),\n}","preventionTips":["Range-check the value against the target uint width: `value <= size.unsigned_int_max()` where size comes from `ty.layout()`; `u8` max is 255, `u64` max is 2^64-1, etc.","The internal `layout_of(...).unwrap()` can PANIC for generic/unsized types — always call `Ty::layout()?` first so the layout error is a `Result`, not a panic.","For `usize`, the max depends on the target pointer width (`target_pointer_width()`); do not assume 64-bit when cross-compiling.","Prefer `MirConst::try_from_uint` (fallible) over any constructor that assumes a width; never widen a `u128` into a narrower type without this check."],"tags":["rust","const","overflow","uint"],"analyzedSha":"22057b88b091743bc0fd8d592a9264f0a6951403","analyzedAt":"2026-08-03T08:09:25.915Z","schemaVersion":2}