{"id":"cb2d2e645336fc96","repo":"rust-lang/rust","slug":"failed-to-get-layout-for-ty-err","errorCode":null,"errorMessage":"Failed to get layout for `{ty}`: {err}","messagePattern":"Failed to get layout for `(.+?)`: (.+?)","errorType":"exception","errorClass":"B::Error","httpStatus":null,"severity":"error","filePath":"compiler/rustc_public_bridge/src/context/mod.rs","lineNumber":59,"sourceCode":"        err: ty::layout::FnAbiError<'tcx>,\n        _span: rustc_span::Span,\n        fn_abi_request: ty::layout::FnAbiRequest<'tcx>,\n    ) -> B::Error {\n        B::Error::new(format!(\"Failed to get ABI for `{fn_abi_request:?}`: {err:?}\"))\n    }\n}\n\nimpl<'tcx, B: Bridge> LayoutOfHelpers<'tcx> for CompilerCtxt<'tcx, B> {\n    type LayoutOfResult = Result<ty::layout::TyAndLayout<'tcx>, B::Error>;\n\n    #[inline]\n    fn handle_layout_err(\n        &self,\n        err: ty::layout::LayoutError<'tcx>,\n        _span: rustc_span::Span,\n        ty: Ty<'tcx>,\n    ) -> B::Error {\n        B::Error::new(format!(\"Failed to get layout for `{ty}`: {err}\"))\n    }\n}\n\nimpl<'tcx, B: Bridge> HasTypingEnv<'tcx> for CompilerCtxt<'tcx, B> {\n    fn typing_env(&self) -> ty::TypingEnv<'tcx> {\n        ty::TypingEnv::fully_monomorphized()\n    }\n}\n\nimpl<'tcx, B: Bridge> HasTyCtxt<'tcx> for CompilerCtxt<'tcx, B> {\n    fn tcx(&self) -> TyCtxt<'tcx> {\n        self.tcx\n    }\n}\n\nimpl<'tcx, B: Bridge> HasDataLayout for CompilerCtxt<'tcx, B> {\n    fn data_layout(&self) -> &rustc_abi::TargetDataLayout {\n        self.tcx.data_layout()","sourceCodeStart":41,"sourceCodeEnd":77,"githubUrl":"https://github.com/rust-lang/rust/blob/22057b88b091743bc0fd8d592a9264f0a6951403/compiler/rustc_public_bridge/src/context/mod.rs#L41-L77","documentation":"Emitted by CompilerCtxt::handle_layout_err (compiler/rustc_public_bridge/src/context/mod.rs:59), the LayoutOfHelpers impl for CompilerCtxt. It converts the ty::layout::LayoutError produced by rustc's layout_of query into a Bridge::Error string so external consumers of rustc_public receive a typed Result::Err instead of a panic. The LayoutError variants it can wrap are Unknown (no sensible layout, e.g. unsized field or unsatisfiable Sized bound), SizeOverflow (larger than isize::MAX bytes), InvalidSimd (zero-length or too many lanes), TooGeneric (layout depends on a still-generic parameter), NormalizationFailure (alias failed to normalize after opaque-type revelation), and ReferencesError (a non-layout error was already reported elsewhere).","triggerScenarios":"Calling CompilerCtxt::ty_layout(ty) (impls.rs:767) on a type that still contains generic parameters or inference variables; computing layout of an opaque/impl Trait whose concrete type is not revealed under TypingEnv::fully_monomorphized(); a recursive type whose representation is not yet finalized; an array/Vec-like type whose evaluated length exceeds the target object-size bound; a SIMD type with zero elements or more lanes than the target limit; an alias that cannot normalize post-monomorphization.","commonSituations":"Tools built on the unstable rustc_public crate (ABI extractors, code generators, binding emitters, rustdoc-json consumers) iterating over all DefIds of a crate and requesting layouts for Self, generics, or trait-object-related types that legitimately have no monomorphic layout; using a TypingEnv other than fully_monomorphized when querying through CompilerCtxt; toolchain/nightly version skew between rustc_public and rustc_public_bridge; analyzing a crate that emitted type-check errors, leaving LayoutError::ReferencesError behind.","solutions":["Before calling ty_layout, filter out types that cannot have a fixed layout: check ty.has_param() / ty.has_infer() / ty.has_placeholders() and skip those.","Read the embedded LayoutError variant and route accordingly: TooGeneric/Unknown -> expected, skip the type; SizeOverflow/InvalidSimd -> reject the input as malformed; NormalizationFailure -> the target crate must type-check first; ReferencesError -> a prior error must be fixed before layout queries are meaningful.","Ensure the analyzed crate type-checks cleanly (cargo check with no errors) before driving layout queries; rustc cannot compute layouts for error-tainted types.","Restrict iteration to items whose body is available (ctxt.has_body(def_id)) and whose instances are fully monomorphized before requesting their layout.","Pin the exact nightly toolchain that matches your rustc_public consumer crate version, since rustc_public_bridge's LayoutError surface and TypingEnv semantics change across versions."],"exampleFix":"// before\nlet layout = ctxt.ty_layout(ty)?;\n\n// after: skip generic/inference-bearing types instead of erroring\nuse rustc_middle::ty::TypeVisitableExt;\nif ty.has_param() || ty.has_infer() || ty.has_placeholders() {\n    // layout is not fixed; skip this type\n    continue;\n}\nlet layout = ctxt.ty_layout(ty)?;","handlingStrategy":"try-catch","validationCode":"// Before ty_layout() (and the const constructors that call it internally:\n// try_new_const_zst, try_new_const_uint, try_new_ty_const_uint): reject types the bridge cannot lay out.\nif ty.has_param() {\n    return Err(MyError::NotMonomorphized(format!(\"{ty:?} still has generic parameters\")));\n}\nif ty.has_escape_bound_vars() {\n    return Err(MyError::BoundVars(format!(\"{ty:?} has escaping bound vars\")));\n}\nif ty.references_error() {\n    return Err(MyError::TypeError(format!(\"{ty:?} contains Ty::Error\")));\n}","typeGuard":"/// True iff `ty` is layout-computable through CompilerCtxt::ty_layout\n/// (fully monomorphized, no escaping bound vars, no Ty::Error).\nfn ty_layout_safe<'tcx>(ty: rustc_middle::ty::Ty<'tcx>) -> bool {\n    !ty.has_param() && !ty.has_escape_bound_vars() && !ty.references_error()\n}","tryCatchPattern":"// ty_layout() returns Result<Layout, B::Error>; treat failure as 'layout unknown', not fatal.\n// Enrich with the offending type before propagating.\nlet layout = ctxt\n    .ty_layout(ty)\n    .map_err(|e| MyError::LayoutUnavailable {\n        ty: format!(\"{ty:?}\"),\n        source: e,\n    })?;","preventionTips":["Only call ty_layout() (and the internal const constructors try_new_const_zst / try_new_const_uint / try_new_ty_const_uint) on fully monomorphized types: reject ty.has_param() and ty.has_escape_bound_vars() upfront.","Filter out error types (ty.references_error()) before any layout query — they always fail with error 351.","Guard against LayoutError::SizeOverflow for deeply recursive or large repr(Rust) enums/aggregates; bound recursion depth and cache successful layouts.","Never .unwrap() layout results: error 351 is an expected type-system-dependent runtime condition, not a bug; always propagate via ? or map_err.","Remember layout_of also runs implicitly inside the const constructors — apply the same pre-checks there, not just at explicit ty_layout call sites."],"tags":["rustc","rustc-public","layout","compiler-internals","monomorphization"],"analyzedSha":"22057b88b091743bc0fd8d592a9264f0a6951403","analyzedAt":"2026-08-03T08:09:25.915Z","schemaVersion":2}