1//! # `rustc_public` — A Public Interface to `rustc`
2//!
3//! This crate provides a public API for querying and analyzing Rust programs through the
4//! compiler's internal representations. It is designed for third-party tools such as
5//! verification engines, linters, and code generators that need access to type information,
6//! MIR bodies, monomorphized instances, and ABI details.
7//!
8//! The goal is to publish this crate on [crates.io](https://crates.io) with semver
9//! guarantees. For more details on the proposed plan, see
10//! <https://github.com/rust-lang/compiler-team/issues/949>.
11//!
12//! ## Usage
13//!
14//! For now, the entry point is the [`run!`] macro, which sets up the compiler session and provides
15//! access to the API within a callback. All queries must be performed inside this callback
16//! since the data structures are tied to the compiler's thread-local state.
17//!
18//! ```rust,ignore (requires compiler session)
19//! use rustc_public::*;
20//! use std::ops::ControlFlow;
21//!
22//! let result = run!(args, || -> ControlFlow<()> {
23//! // Find all crates with the same name (potential duplicates).
24//! for krate in external_crates() {
25//! let dupes = find_crates(&krate.name);
26//! if dupes.len() > 1 {
27//! println!("Warning: multiple versions of `{}`", krate.name);
28//! }
29//! }
30//! ControlFlow::Continue(())
31//! });
32//! ```
33//!
34//! ## Crate Discovery
35//!
36//! Use [`local_crate()`] to access the crate being compiled, [`external_crates()`] to list
37//! dependencies, or [`find_crates()`] to search by name. Use [`entry_fn()`] to find the
38//! program entry point, and [`all_local_items()`] to retrieve all local definitions.
39//!
40//! ## Status
41//!
42//! This API is not yet published and is still subject to breaking changes.
43//! For more information, see <https://github.com/rust-lang/rustc_public>.
4445#![allow(rustc::usage_of_ty_tykind)]
46#![doc(test(attr(allow(unused_variables), deny(warnings), allow(internal_features))))]
47#![feature(sized_hierarchy)]
4849use std::fmt::Debug;
50use std::marker::PhantomData;
51use std::{fmt, io};
5253pub(crate) use rustc_public_bridge::IndexedVal;
54use rustc_public_bridge::Tables;
55use rustc_public_bridge::context::CompilerCtxt;
56use serde::Serialize;
5758/// Unstable internal APIs for bridging with `rustc` internals.
59///
60/// This module has no stability guarantees and is not covered by semver.
61/// It is only available when the `rustc_internal` feature is enabled.
62#[cfg(feature = "rustc_internal")]
63pub mod rustc_internal;
6465use crate::compiler_interface::with;
66pub use crate::crate_def::{CrateDef, CrateDefType, DefId};
67pub use crate::error::*;
68use crate::mir::mono::StaticDef;
69use crate::mir::{Body, Mutability};
70use crate::ty::{
71AdtDef, AssocItem, FnDef, ForeignModuleDef, ImplDef, ProvenanceMap, Span, TraitDef, Ty,
72serialize_index_impl,
73};
74use crate::unstable::Stable;
7576pub mod abi;
77mod alloc;
78pub(crate) mod unstable;
79#[macro_use]
80pub mod crate_def;
81pub mod compiler_interface;
82#[macro_use]
83pub mod error;
84pub mod mir;
85pub mod target;
86#[cfg(test)]
87mod tests;
88pub mod ty;
89pub mod visitor;
9091// FIXME: Consider replacing with an opaque or interned type.
92/// A symbol name (e.g., function name, crate name), currently represented as a `String`.
93pub type Symbol = String;
9495/// A unique identifier for a crate within the current compilation session.
96#[derive(#[automatically_derived]
impl ::core::clone::Clone for CrateNum {
#[inline]
fn clone(&self) -> CrateNum {
let _: ::core::clone::AssertParamIsClone<usize>;
let _: ::core::clone::AssertParamIsClone<ThreadLocalIndex>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CrateNum { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for CrateNum {
#[inline]
fn eq(&self, other: &CrateNum) -> bool {
self.0 == other.0 && self.1 == other.1
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for CrateNum {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
let _: ::core::cmp::AssertParamIsEq<ThreadLocalIndex>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for CrateNum {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field2_finish(f, "CrateNum",
&self.0, &&self.1)
}
}Debug)]
97pub struct CrateNum(pub(crate) usize, ThreadLocalIndex);
98impl ::serde::Serialize for CrateNum {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where
S: ::serde::Serializer {
let n: usize = self.0;
::serde::Serialize::serialize(&n, serializer)
}
}serialize_index_impl!(CrateNum);
99100impl Debugfor DefId {
101fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102f.debug_struct("DefId").field("id", &self.0).field("name", &self.name()).finish()
103 }
104}
105106/// A collection of items defined in a crate.
107pub type CrateItems = Vec<CrateItem>;
108109/// A collection of trait declarations.
110pub type TraitDecls = Vec<TraitDef>;
111112/// A collection of trait implementation blocks.
113pub type ImplTraitDecls = Vec<ImplDef>;
114115/// A collection of associated items (methods, constants, or types within a trait or impl).
116pub type AssocItems = Vec<AssocItem>;
117118/// Metadata about a crate in the current compilation.
119///
120/// Use [`local_crate()`] to obtain the crate being compiled, or [`external_crates()`]
121/// and [`find_crates()`] to discover dependencies.
122#[derive(#[automatically_derived]
impl ::core::clone::Clone for Crate {
#[inline]
fn clone(&self) -> Crate {
Crate {
id: ::core::clone::Clone::clone(&self.id),
name: ::core::clone::Clone::clone(&self.name),
is_local: ::core::clone::Clone::clone(&self.is_local),
}
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Crate {
#[inline]
fn eq(&self, other: &Crate) -> bool {
self.is_local == other.is_local && self.id == other.id &&
self.name == other.name
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Crate {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<CrateNum>;
let _: ::core::cmp::AssertParamIsEq<Symbol>;
let _: ::core::cmp::AssertParamIsEq<bool>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for Crate {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "Crate", "id",
&self.id, "name", &self.name, "is_local", &&self.is_local)
}
}Debug, #[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications,
clippy :: absolute_paths,)]
const _: () =
{
#[allow(unused_extern_crates, clippy :: useless_attribute)]
extern crate serde as _serde;
;
#[automatically_derived]
impl _serde::Serialize for Crate {
fn serialize<__S>(&self, __serializer: __S)
-> _serde::__private228::Result<__S::Ok, __S::Error> where
__S: _serde::Serializer {
let mut __serde_state =
_serde::Serializer::serialize_struct(__serializer, "Crate",
false as usize + 1 + 1 + 1)?;
_serde::ser::SerializeStruct::serialize_field(&mut __serde_state,
"id", &self.id)?;
_serde::ser::SerializeStruct::serialize_field(&mut __serde_state,
"name", &self.name)?;
_serde::ser::SerializeStruct::serialize_field(&mut __serde_state,
"is_local", &self.is_local)?;
_serde::ser::SerializeStruct::end(__serde_state)
}
}
};Serialize)]
123pub struct Crate {
124/// The crate's unique identifier in this compilation session.
125pub id: CrateNum,
126/// The crate name as declared in `Cargo.toml` or `--crate-name`.
127pub name: Symbol,
128/// Whether this is the crate currently being compiled.
129pub is_local: bool,
130}
131132impl Crate {
133/// Return all foreign modules (e.g., `extern "C" { ... }` blocks) in this crate.
134pub fn foreign_modules(&self) -> Vec<ForeignModuleDef> {
135with(|cx| cx.foreign_modules(self.id))
136 }
137138/// Return all trait declarations in this crate.
139 ///
140 /// For the local crate, this includes private traits. For external crates,
141 /// it returns all traits available in metadata.
142pub fn trait_decls(&self) -> TraitDecls {
143with(|cx| cx.trait_decls(self.id))
144 }
145146/// Return all trait implementation blocks in this crate.
147pub fn trait_impls(&self) -> ImplTraitDecls {
148with(|cx| cx.trait_impls(self.id))
149 }
150151/// Return all function definitions in this crate.
152 ///
153 /// For the local crate, this includes private functions. For external crates,
154 /// it returns all functions available in metadata.
155pub fn fn_defs(&self) -> Vec<FnDef> {
156with(|cx| cx.crate_functions(self.id))
157 }
158159/// Return all static items in this crate.
160 ///
161 /// For the local crate, this includes private statics. For external crates,
162 /// it returns all statics available in metadata.
163pub fn statics(&self) -> Vec<StaticDef> {
164with(|cx| cx.crate_statics(self.id))
165 }
166167/// Return all ADT (struct, enum, union) definitions in this crate.
168 ///
169 /// For the local crate, this includes private types. For external crates,
170 /// it returns all ADTs available in metadata.
171pub fn adts(&self) -> Vec<AdtDef> {
172with(|cx| cx.crate_adts(self.id))
173 }
174}
175176/// The kind of a [`CrateItem`].
177#[derive(#[automatically_derived]
impl ::core::marker::Copy for ItemKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ItemKind {
#[inline]
fn clone(&self) -> ItemKind {
let _: ::core::clone::AssertParamIsClone<CtorKind>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ItemKind {
#[inline]
fn eq(&self, other: &ItemKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ItemKind::Ctor(__self_0), ItemKind::Ctor(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ItemKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<CtorKind>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for ItemKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ItemKind::Fn => ::core::fmt::Formatter::write_str(f, "Fn"),
ItemKind::Static =>
::core::fmt::Formatter::write_str(f, "Static"),
ItemKind::Const => ::core::fmt::Formatter::write_str(f, "Const"),
ItemKind::Ctor(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ctor",
&__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::hash::Hash for ItemKind {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state);
match self {
ItemKind::Ctor(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
_ => {}
}
}
}Hash, #[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications,
clippy :: absolute_paths,)]
const _: () =
{
#[allow(unused_extern_crates, clippy :: useless_attribute)]
extern crate serde as _serde;
;
#[automatically_derived]
impl _serde::Serialize for ItemKind {
fn serialize<__S>(&self, __serializer: __S)
-> _serde::__private228::Result<__S::Ok, __S::Error> where
__S: _serde::Serializer {
match *self {
ItemKind::Fn =>
_serde::Serializer::serialize_unit_variant(__serializer,
"ItemKind", 0u32, "Fn"),
ItemKind::Static =>
_serde::Serializer::serialize_unit_variant(__serializer,
"ItemKind", 1u32, "Static"),
ItemKind::Const =>
_serde::Serializer::serialize_unit_variant(__serializer,
"ItemKind", 2u32, "Const"),
ItemKind::Ctor(ref __field0) =>
_serde::Serializer::serialize_newtype_variant(__serializer,
"ItemKind", 3u32, "Ctor", __field0),
}
}
}
};Serialize)]
178pub enum ItemKind {
179/// A function (`fn`) or method.
180Fn,
181/// A static variable (`static`).
182Static,
183/// A compile-time constant (`const`).
184Const,
185/// A data constructor for a struct or enum variant.
186Ctor(CtorKind),
187}
188189/// The kind of a data constructor.
190#[derive(#[automatically_derived]
impl ::core::marker::Copy for CtorKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for CtorKind {
#[inline]
fn clone(&self) -> CtorKind { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for CtorKind {
#[inline]
fn eq(&self, other: &CtorKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for CtorKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for CtorKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self { CtorKind::Const => "Const", CtorKind::Fn => "Fn", })
}
}Debug, #[automatically_derived]
impl ::core::hash::Hash for CtorKind {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state)
}
}Hash, #[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications,
clippy :: absolute_paths,)]
const _: () =
{
#[allow(unused_extern_crates, clippy :: useless_attribute)]
extern crate serde as _serde;
;
#[automatically_derived]
impl _serde::Serialize for CtorKind {
fn serialize<__S>(&self, __serializer: __S)
-> _serde::__private228::Result<__S::Ok, __S::Error> where
__S: _serde::Serializer {
match *self {
CtorKind::Const =>
_serde::Serializer::serialize_unit_variant(__serializer,
"CtorKind", 0u32, "Const"),
CtorKind::Fn =>
_serde::Serializer::serialize_unit_variant(__serializer,
"CtorKind", 1u32, "Fn"),
}
}
}
};Serialize)]
191pub enum CtorKind {
192/// A unit or constant constructor (e.g., `None`, `struct Foo;`).
193Const,
194/// A function-like constructor (e.g., `Some(x)`, `struct Foo(u32)`).
195Fn,
196}
197198/// A file path string used for source locations and diagnostics.
199pub type Filename = String;
200201#[automatically_derived]
impl ::core::clone::Clone for CrateItem {
#[inline]
fn clone(&self) -> CrateItem {
let _: ::core::clone::AssertParamIsClone<DefId>;
*self
}
}
#[automatically_derived]
impl ::core::marker::Copy for CrateItem { }
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for CrateItem { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CrateItem {
#[inline]
fn eq(&self, other: &CrateItem) -> bool { self.0 == other.0 }
}
#[automatically_derived]
impl ::core::cmp::Eq for CrateItem {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<DefId>;
}
}
#[automatically_derived]
impl ::core::fmt::Debug for CrateItem {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "CrateItem",
&&self.0)
}
}
#[automatically_derived]
impl ::core::hash::Hash for CrateItem {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}
#[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications,
clippy :: absolute_paths,)]
const _: () =
{
#[allow(unused_extern_crates, clippy :: useless_attribute)]
extern crate serde as _serde;
;
#[automatically_derived]
impl _serde::Serialize for CrateItem {
fn serialize<__S>(&self, __serializer: __S)
-> _serde::__private228::Result<__S::Ok, __S::Error> where
__S: _serde::Serializer {
_serde::Serializer::serialize_newtype_struct(__serializer,
"CrateItem", &self.0)
}
}
};
impl CrateDef for CrateItem {
fn def_id(&self) -> DefId { self.0 }
}
impl CrateDefType for CrateItem {}crate_def_with_ty! {
202/// A definition in the local crate (function, static, const, or constructor).
203 ///
204 /// Obtain instances via [`all_local_items()`] or [`Crate::fn_defs()`].
205 /// Use [`CrateItem::body()`] to access the MIR, or convert to an
206 /// [`Instance`](mir::mono::Instance) for monomorphized analysis.
207#[derive(Serialize)]
208pub CrateItem;
209}210211impl CrateItem {
212/// Return the MIR body of this item, panicking if unavailable.
213 ///
214 /// Prefer [`body()`](Self::body) for a non-panicking alternative.
215pub fn expect_body(&self) -> mir::Body {
216with(|cx| cx.mir_body(self.0))
217 }
218219/// Return the MIR body of this item, or `None` if unavailable.
220 ///
221 /// A body may be unavailable for foreign items or compiler built-ins.
222pub fn body(&self) -> Option<mir::Body> {
223with(|cx| cx.has_body(self.0).then(|| cx.mir_body(self.0)))
224 }
225226/// Check whether this item has a MIR body available.
227pub fn has_body(&self) -> bool {
228with(|cx| cx.has_body(self.0))
229 }
230231/// Return the source span of this item's definition.
232pub fn span(&self) -> Span {
233self.0.span()
234 }
235236/// Return what kind of item this is (function, static, const, or constructor).
237pub fn kind(&self) -> ItemKind {
238with(|cx| cx.item_kind(*self))
239 }
240241/// Check whether this item is generic and requires monomorphization.
242 ///
243 /// Returns `true` if this item, or any enclosing definition (e.g., the impl
244 /// block it belongs to), has type or const generic parameters.
245pub fn requires_monomorphization(&self) -> bool {
246with(|cx| cx.requires_monomorphization(self.0))
247 }
248249/// Return the type of this item.
250 ///
251 /// For functions, this returns the function type (e.g., `fn(u32) -> bool`).
252pub fn ty(&self) -> Ty {
253with(|cx| cx.def_ty(self.0))
254 }
255256/// Check whether this item was declared inside an `extern` block.
257 ///
258 /// Foreign items (e.g., `extern "C" { fn foo(); }`) are locally defined
259 /// declarations of externally-linked symbols.
260pub fn is_foreign_item(&self) -> bool {
261with(|cx| cx.is_foreign_item(self.0))
262 }
263264/// Write the MIR textual representation of this item's body to `w`.
265pub fn emit_mir<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
266self.body()
267 .ok_or_else(|| io::Error::other(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("No body found for `{0}`",
self.name()))
})format!("No body found for `{}`", self.name())))?
268.dump(w, &self.trimmed_name())
269 }
270}
271272/// Return the program entry point (usually `main`) if defined in the local crate.
273///
274/// Returns `None` for library crates. For `no_std` crates this may resolve to
275/// a `#[start]` function.
276pub fn entry_fn() -> Option<CrateItem> {
277with(|cx| cx.entry_fn())
278}
279280/// Return the local crate (the crate currently being compiled).
281pub fn local_crate() -> Crate {
282with(|cx| cx.local_crate())
283}
284285/// Find all crates matching the given name.
286///
287/// Multiple crates with the same name can exist when different versions of the
288/// same dependency are linked.
289pub fn find_crates(name: &str) -> Vec<Crate> {
290with(|cx| cx.find_crates(name))
291}
292293/// Return all external (non-local) crates in the compilation.
294pub fn external_crates() -> Vec<Crate> {
295with(|cx| cx.external_crates())
296}
297298/// Return all items in the local crate that have a MIR body.
299///
300/// This includes functions, closures, statics with initializers, and constants.
301pub fn all_local_items() -> CrateItems {
302with(|cx| cx.all_local_items())
303}
304305/// Return all trait declarations from the local crate and all its dependencies.
306///
307/// This includes private traits. Use [`Crate::trait_decls()`] to query a specific crate.
308pub fn all_trait_decls() -> TraitDecls {
309with(|cx| cx.all_trait_decls())
310}
311312/// Return all trait implementations from the local crate and all its dependencies.
313///
314/// Use [`Crate::trait_impls()`] to query a specific crate.
315pub fn all_trait_impls() -> ImplTraitDecls {
316with(|cx| cx.all_trait_impls())
317}
318319/// An opaque wrapper around internal compiler data.
320///
321/// This type is used for compiler details that are exposed for debug printing
322/// but whose internal structure is not part of the public API.
323#[derive(#[automatically_derived]
impl ::core::clone::Clone for Opaque {
#[inline]
fn clone(&self) -> Opaque { Opaque(::core::clone::Clone::clone(&self.0)) }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Opaque {
#[inline]
fn eq(&self, other: &Opaque) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Opaque {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<String>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for Opaque {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash, #[doc(hidden)]
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications,
clippy :: absolute_paths,)]
const _: () =
{
#[allow(unused_extern_crates, clippy :: useless_attribute)]
extern crate serde as _serde;
;
#[automatically_derived]
impl _serde::Serialize for Opaque {
fn serialize<__S>(&self, __serializer: __S)
-> _serde::__private228::Result<__S::Ok, __S::Error> where
__S: _serde::Serializer {
_serde::Serializer::serialize_newtype_struct(__serializer,
"Opaque", &self.0)
}
}
};Serialize)]
324pub struct Opaque(String);
325326impl std::fmt::Displayfor Opaque {
327fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
328f.write_fmt(format_args!("{0}", self.0))write!(f, "{}", self.0)329 }
330}
331332impl std::fmt::Debugfor Opaque {
333fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
334f.write_fmt(format_args!("{0}", self.0))write!(f, "{}", self.0)335 }
336}
337338/// Create an [`Opaque`] value from any debuggable type.
339pub fn opaque<T: Debug>(value: &T) -> Opaque {
340Opaque(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", value))
})format!("{value:?}"))
341}
342343macro_rules!bridge_impl {
344 ( $( $name:ident, $ty:ty ),* $(,)? ) => {
345 $(
346impl rustc_public_bridge::bridge::$name<compiler_interface::BridgeTys> for $ty {
347fn new(def: crate::DefId) -> Self {
348Self(def)
349 }
350 }
351 )*
352 };
353}
354355#[rustfmt::skip]
356impl rustc_public_bridge::bridge::StaticDef<compiler_interface::BridgeTys> for
crate::mir::mono::StaticDef {
fn new(def: crate::DefId) -> Self { Self(def) }
}bridge_impl!(
357 CrateItem, crate::CrateItem,
358 AdtDef, crate::ty::AdtDef,
359 ForeignModuleDef, crate::ty::ForeignModuleDef,
360 ForeignDef, crate::ty::ForeignDef,
361 FnDef, crate::ty::FnDef,
362 ClosureDef, crate::ty::ClosureDef,
363 CoroutineDef, crate::ty::CoroutineDef,
364 CoroutineClosureDef, crate::ty::CoroutineClosureDef,
365 AliasDef, crate::ty::AliasDef,
366 ParamDef, crate::ty::ParamDef,
367 BrNamedDef, crate::ty::BrNamedDef,
368 TraitDef, crate::ty::TraitDef,
369 GenericDef, crate::ty::GenericDef,
370 ConstDef, crate::ty::ConstDef,
371 ImplDef, crate::ty::ImplDef,
372 RegionDef, crate::ty::RegionDef,
373 CoroutineWitnessDef, crate::ty::CoroutineWitnessDef,
374 AssocDef, crate::ty::AssocDef,
375 OpaqueDef, crate::ty::OpaqueDef,
376 StaticDef, crate::mir::mono::StaticDef377);
378379impl rustc_public_bridge::bridge::Prov<compiler_interface::BridgeTys> for crate::ty::Prov {
380fn new(aid: crate::mir::alloc::AllocId) -> Self {
381Self(aid)
382 }
383}
384385impl rustc_public_bridge::bridge::Allocation<compiler_interface::BridgeTys>
386for crate::ty::Allocation387{
388fn new<'tcx>(
389 bytes: Vec<Option<u8>>,
390 ptrs: Vec<(usize, rustc_middle::mir::interpret::AllocId)>,
391 align: u64,
392 mutability: rustc_middle::mir::Mutability,
393 tables: &mut Tables<'tcx, compiler_interface::BridgeTys>,
394 cx: &CompilerCtxt<'tcx, compiler_interface::BridgeTys>,
395 ) -> Self {
396Self {
397bytes,
398 provenance: ProvenanceMap {
399 ptrs: ptrs.iter().map(|(i, aid)| (*i, tables.prov(*aid))).collect(),
400 },
401align,
402 mutability: mutability.stable(tables, cx),
403 }
404 }
405}
406407#[derive(#[automatically_derived]
impl ::core::clone::Clone for ThreadLocalIndex {
#[inline]
fn clone(&self) -> ThreadLocalIndex {
let _: ::core::clone::AssertParamIsClone<PhantomData<*const ()>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ThreadLocalIndex { }Copy, #[automatically_derived]
impl ::core::hash::Hash for ThreadLocalIndex {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self._phantom, state)
}
}Hash, #[automatically_derived]
impl ::core::cmp::PartialEq for ThreadLocalIndex {
#[inline]
fn eq(&self, other: &ThreadLocalIndex) -> bool {
self._phantom == other._phantom
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ThreadLocalIndex {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<PhantomData<*const ()>>;
}
}Eq, #[automatically_derived]
impl ::core::default::Default for ThreadLocalIndex {
#[inline]
fn default() -> ThreadLocalIndex {
ThreadLocalIndex { _phantom: ::core::default::Default::default() }
}
}Default)]
408/// Marker type for indexes into thread local structures.
409///
410/// Makes things `!Send`/`!Sync`, so users don't move `rustc_public` types to
411/// thread with no (or worse, different) `rustc_public` pointer.
412///
413/// Note. This doesn't make it impossible to confuse TLS. You could return a
414/// `DefId` from one `run!` invocation, and then use it inside a different
415/// `run!` invocation with different tables.
416pub(crate) struct ThreadLocalIndex {
417 _phantom: PhantomData<*const ()>,
418}
419#[expect(non_upper_case_globals)]
420/// Emulating unit struct `struct ThreadLocalIndex`;
421pub(crate) const ThreadLocalIndex: ThreadLocalIndex = ThreadLocalIndex { _phantom: PhantomData };
422423impl fmt::Debugfor ThreadLocalIndex {
424fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
425f.debug_tuple("ThreadLocalIndex").finish()
426 }
427}