rustc_public/
lib.rs

1//! The WIP public interface to rustc internals.
2//!
3//! For more information see <https://github.com/rust-lang/project-stable-mir>
4//!
5//! # Note
6//!
7//! This API is still completely unstable and subject to change.
8
9#![allow(rustc::usage_of_ty_tykind)]
10#![doc(test(attr(allow(unused_variables), deny(warnings), allow(internal_features))))]
11#![feature(sized_hierarchy)]
12//!
13//! This crate shall contain all type definitions and APIs that we expect third-party tools to invoke to
14//! interact with the compiler.
15//!
16//! The goal is to eventually be published on
17//! [crates.io](https://crates.io).
18
19use std::fmt::Debug;
20use std::marker::PhantomData;
21use std::{fmt, io};
22
23pub(crate) use rustc_public_bridge::IndexedVal;
24use rustc_public_bridge::Tables;
25use rustc_public_bridge::context::CompilerCtxt;
26/// Export the rustc_internal APIs. Note that this module has no stability
27/// guarantees and it is not taken into account for semver.
28#[cfg(feature = "rustc_internal")]
29pub mod rustc_internal;
30use serde::Serialize;
31
32use crate::compiler_interface::with;
33pub use crate::crate_def::{CrateDef, CrateDefItems, CrateDefType, DefId};
34pub use crate::error::*;
35use crate::mir::mono::StaticDef;
36use crate::mir::{Body, Mutability};
37use crate::ty::{
38    AssocItem, FnDef, ForeignModuleDef, ImplDef, ProvenanceMap, Span, TraitDef, Ty,
39    serialize_index_impl,
40};
41use crate::unstable::Stable;
42
43pub mod abi;
44mod alloc;
45pub(crate) mod unstable;
46#[macro_use]
47pub mod crate_def;
48pub mod compiler_interface;
49#[macro_use]
50pub mod error;
51pub mod mir;
52pub mod target;
53#[cfg(test)]
54mod tests;
55pub mod ty;
56pub mod visitor;
57
58/// Use String for now but we should replace it.
59pub type Symbol = String;
60
61/// The number that identifies a crate.
62#[derive(Clone, Copy, PartialEq, Eq, Debug)]
63pub struct CrateNum(pub(crate) usize, ThreadLocalIndex);
64serialize_index_impl!(CrateNum);
65
66impl Debug for DefId {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.debug_struct("DefId").field("id", &self.0).field("name", &self.name()).finish()
69    }
70}
71
72/// A list of crate items.
73pub type CrateItems = Vec<CrateItem>;
74
75/// A list of trait decls.
76pub type TraitDecls = Vec<TraitDef>;
77
78/// A list of impl trait decls.
79pub type ImplTraitDecls = Vec<ImplDef>;
80
81/// A list of associated items.
82pub type AssocItems = Vec<AssocItem>;
83
84/// Holds information about a crate.
85#[derive(Clone, PartialEq, Eq, Debug, Serialize)]
86pub struct Crate {
87    pub id: CrateNum,
88    pub name: Symbol,
89    pub is_local: bool,
90}
91
92impl Crate {
93    /// The list of foreign modules in this crate.
94    pub fn foreign_modules(&self) -> Vec<ForeignModuleDef> {
95        with(|cx| cx.foreign_modules(self.id))
96    }
97
98    /// The list of traits declared in this crate.
99    pub fn trait_decls(&self) -> TraitDecls {
100        with(|cx| cx.trait_decls(self.id))
101    }
102
103    /// The list of trait implementations in this crate.
104    pub fn trait_impls(&self) -> ImplTraitDecls {
105        with(|cx| cx.trait_impls(self.id))
106    }
107
108    /// Return a list of function definitions from this crate independent on their visibility.
109    pub fn fn_defs(&self) -> Vec<FnDef> {
110        with(|cx| cx.crate_functions(self.id))
111    }
112
113    /// Return a list of static items defined in this crate independent on their visibility.
114    pub fn statics(&self) -> Vec<StaticDef> {
115        with(|cx| cx.crate_statics(self.id))
116    }
117}
118
119#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, Serialize)]
120pub enum ItemKind {
121    Fn,
122    Static,
123    Const,
124    Ctor(CtorKind),
125}
126
127#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, Serialize)]
128pub enum CtorKind {
129    Const,
130    Fn,
131}
132
133pub type Filename = String;
134
135crate_def_with_ty! {
136    /// Holds information about an item in a crate.
137    #[derive(Serialize)]
138    pub CrateItem;
139}
140
141impl CrateItem {
142    /// This will return the body of an item or panic if it's not available.
143    pub fn expect_body(&self) -> mir::Body {
144        with(|cx| cx.mir_body(self.0))
145    }
146
147    /// Return the body of an item if available.
148    pub fn body(&self) -> Option<mir::Body> {
149        with(|cx| cx.has_body(self.0).then(|| cx.mir_body(self.0)))
150    }
151
152    /// Check if a body is available for this item.
153    pub fn has_body(&self) -> bool {
154        with(|cx| cx.has_body(self.0))
155    }
156
157    pub fn span(&self) -> Span {
158        with(|cx| cx.span_of_an_item(self.0))
159    }
160
161    pub fn kind(&self) -> ItemKind {
162        with(|cx| cx.item_kind(*self))
163    }
164
165    pub fn requires_monomorphization(&self) -> bool {
166        with(|cx| cx.requires_monomorphization(self.0))
167    }
168
169    pub fn ty(&self) -> Ty {
170        with(|cx| cx.def_ty(self.0))
171    }
172
173    pub fn is_foreign_item(&self) -> bool {
174        with(|cx| cx.is_foreign_item(self.0))
175    }
176
177    /// Emit MIR for this item body.
178    pub fn emit_mir<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
179        self.body()
180            .ok_or_else(|| io::Error::other(format!("No body found for `{}`", self.name())))?
181            .dump(w, &self.name())
182    }
183}
184
185/// Return the function where execution starts if the current
186/// crate defines that. This is usually `main`, but could be
187/// `start` if the crate is a no-std crate.
188pub fn entry_fn() -> Option<CrateItem> {
189    with(|cx| cx.entry_fn())
190}
191
192/// Access to the local crate.
193pub fn local_crate() -> Crate {
194    with(|cx| cx.local_crate())
195}
196
197/// Try to find a crate or crates if multiple crates exist from given name.
198pub fn find_crates(name: &str) -> Vec<Crate> {
199    with(|cx| cx.find_crates(name))
200}
201
202/// Try to find a crate with the given name.
203pub fn external_crates() -> Vec<Crate> {
204    with(|cx| cx.external_crates())
205}
206
207/// Retrieve all items in the local crate that have a MIR associated with them.
208pub fn all_local_items() -> CrateItems {
209    with(|cx| cx.all_local_items())
210}
211
212pub fn all_trait_decls() -> TraitDecls {
213    with(|cx| cx.all_trait_decls())
214}
215
216pub fn all_trait_impls() -> ImplTraitDecls {
217    with(|cx| cx.all_trait_impls())
218}
219
220/// A type that provides internal information but that can still be used for debug purpose.
221#[derive(Clone, PartialEq, Eq, Hash, Serialize)]
222pub struct Opaque(String);
223
224impl std::fmt::Display for Opaque {
225    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226        write!(f, "{}", self.0)
227    }
228}
229
230impl std::fmt::Debug for Opaque {
231    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232        write!(f, "{}", self.0)
233    }
234}
235
236pub fn opaque<T: Debug>(value: &T) -> Opaque {
237    Opaque(format!("{value:?}"))
238}
239
240macro_rules! bridge_impl {
241    ($name: ident, $ty: ty) => {
242        impl rustc_public_bridge::bridge::$name<compiler_interface::BridgeTys> for $ty {
243            fn new(def: crate::DefId) -> Self {
244                Self(def)
245            }
246        }
247    };
248}
249
250bridge_impl!(CrateItem, crate::CrateItem);
251bridge_impl!(AdtDef, crate::ty::AdtDef);
252bridge_impl!(ForeignModuleDef, crate::ty::ForeignModuleDef);
253bridge_impl!(ForeignDef, crate::ty::ForeignDef);
254bridge_impl!(FnDef, crate::ty::FnDef);
255bridge_impl!(ClosureDef, crate::ty::ClosureDef);
256bridge_impl!(CoroutineDef, crate::ty::CoroutineDef);
257bridge_impl!(CoroutineClosureDef, crate::ty::CoroutineClosureDef);
258bridge_impl!(AliasDef, crate::ty::AliasDef);
259bridge_impl!(ParamDef, crate::ty::ParamDef);
260bridge_impl!(BrNamedDef, crate::ty::BrNamedDef);
261bridge_impl!(TraitDef, crate::ty::TraitDef);
262bridge_impl!(GenericDef, crate::ty::GenericDef);
263bridge_impl!(ConstDef, crate::ty::ConstDef);
264bridge_impl!(ImplDef, crate::ty::ImplDef);
265bridge_impl!(RegionDef, crate::ty::RegionDef);
266bridge_impl!(CoroutineWitnessDef, crate::ty::CoroutineWitnessDef);
267bridge_impl!(AssocDef, crate::ty::AssocDef);
268bridge_impl!(OpaqueDef, crate::ty::OpaqueDef);
269bridge_impl!(StaticDef, crate::mir::mono::StaticDef);
270
271impl rustc_public_bridge::bridge::Prov<compiler_interface::BridgeTys> for crate::ty::Prov {
272    fn new(aid: crate::mir::alloc::AllocId) -> Self {
273        Self(aid)
274    }
275}
276
277impl rustc_public_bridge::bridge::Allocation<compiler_interface::BridgeTys>
278    for crate::ty::Allocation
279{
280    fn new<'tcx>(
281        bytes: Vec<Option<u8>>,
282        ptrs: Vec<(usize, rustc_middle::mir::interpret::AllocId)>,
283        align: u64,
284        mutability: rustc_middle::mir::Mutability,
285        tables: &mut Tables<'tcx, compiler_interface::BridgeTys>,
286        cx: &CompilerCtxt<'tcx, compiler_interface::BridgeTys>,
287    ) -> Self {
288        Self {
289            bytes,
290            provenance: ProvenanceMap {
291                ptrs: ptrs.iter().map(|(i, aid)| (*i, tables.prov(*aid))).collect(),
292            },
293            align,
294            mutability: mutability.stable(tables, cx),
295        }
296    }
297}
298
299#[derive(Clone, Copy, Hash, PartialEq, Eq, Default)]
300/// Marker type for indexes into thread local structures.
301///
302/// Makes things `!Send`/`!Sync`, so users don't move `rustc_public` types to
303/// thread with no (or worse, different) `rustc_public` pointer.
304///
305/// Note. This doesn't make it impossible to confuse TLS. You could return a
306/// `DefId` from one `run!` invocation, and then use it inside a different
307/// `run!` invocation with different tables.
308pub(crate) struct ThreadLocalIndex {
309    _phantom: PhantomData<*const ()>,
310}
311#[expect(non_upper_case_globals)]
312/// Emulating unit struct `struct ThreadLocalIndex`;
313pub(crate) const ThreadLocalIndex: ThreadLocalIndex = ThreadLocalIndex { _phantom: PhantomData };
314
315impl fmt::Debug for ThreadLocalIndex {
316    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317        f.debug_tuple("ThreadLocalIndex").finish()
318    }
319}