rustc_session/
cstore.rs

1//! the rustc crate store interface. This also includes types that
2//! are *mostly* used as a part of that interface, but these should
3//! probably get a better home if someone can find one.
4
5use std::any::Any;
6use std::path::PathBuf;
7
8use rustc_abi::ExternAbi;
9use rustc_data_structures::sync::{self, AppendOnlyIndexVec, FreezeLock};
10use rustc_hir::attrs::{CfgEntry, NativeLibKind, PeImportNameType};
11use rustc_hir::def_id::{
12    CrateNum, DefId, LOCAL_CRATE, LocalDefId, StableCrateId, StableCrateIdMap,
13};
14use rustc_hir::definitions::{DefKey, DefPath, DefPathHash, Definitions};
15use rustc_macros::{BlobDecodable, Decodable, Encodable, HashStable_Generic};
16use rustc_span::{Span, Symbol};
17
18// lonely orphan structs and enums looking for a better home
19
20/// Where a crate came from on the local filesystem. One of these three options
21/// must be non-None.
22#[derive(PartialEq, Clone, Debug, HashStable_Generic, Encodable, Decodable)]
23pub struct CrateSource {
24    pub dylib: Option<PathBuf>,
25    pub rlib: Option<PathBuf>,
26    pub rmeta: Option<PathBuf>,
27    pub sdylib_interface: Option<PathBuf>,
28}
29
30impl CrateSource {
31    #[inline]
32    pub fn paths(&self) -> impl Iterator<Item = &PathBuf> {
33        self.dylib.iter().chain(self.rlib.iter()).chain(self.rmeta.iter())
34    }
35}
36
37#[derive(Encodable, BlobDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
38#[derive(HashStable_Generic)]
39pub enum CrateDepKind {
40    /// A dependency that is only used for its macros.
41    MacrosOnly,
42    /// A dependency that is always injected into the dependency list and so
43    /// doesn't need to be linked to an rlib, e.g., the injected panic runtime.
44    Implicit,
45    /// A dependency that is required by an rlib version of this crate.
46    /// Ordinary `extern crate`s result in `Explicit` dependencies.
47    Explicit,
48}
49
50impl CrateDepKind {
51    #[inline]
52    pub fn macros_only(self) -> bool {
53        match self {
54            CrateDepKind::MacrosOnly => true,
55            CrateDepKind::Implicit | CrateDepKind::Explicit => false,
56        }
57    }
58}
59
60#[derive(Copy, Debug, PartialEq, Clone, Encodable, BlobDecodable, HashStable_Generic)]
61pub enum LinkagePreference {
62    RequireDynamic,
63    RequireStatic,
64}
65
66#[derive(Debug, Encodable, Decodable, HashStable_Generic)]
67pub struct NativeLib {
68    pub kind: NativeLibKind,
69    pub name: Symbol,
70    /// If packed_bundled_libs enabled, actual filename of library is stored.
71    pub filename: Option<Symbol>,
72    pub cfg: Option<CfgEntry>,
73    pub foreign_module: Option<DefId>,
74    pub verbatim: Option<bool>,
75    pub dll_imports: Vec<DllImport>,
76}
77
78impl NativeLib {
79    pub fn has_modifiers(&self) -> bool {
80        self.verbatim.is_some() || self.kind.has_modifiers()
81    }
82
83    pub fn wasm_import_module(&self) -> Option<Symbol> {
84        if self.kind == NativeLibKind::WasmImportModule { Some(self.name) } else { None }
85    }
86}
87
88#[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
89pub struct DllImport {
90    pub name: Symbol,
91    pub import_name_type: Option<PeImportNameType>,
92    /// Calling convention for the function.
93    ///
94    /// On x86_64, this is always `DllCallingConvention::C`; on i686, it can be any
95    /// of the values, and we use `DllCallingConvention::C` to represent `"cdecl"`.
96    pub calling_convention: DllCallingConvention,
97    /// Span of import's "extern" declaration; used for diagnostics.
98    pub span: Span,
99    /// Is this for a function (rather than a static variable).
100    pub is_fn: bool,
101}
102
103impl DllImport {
104    pub fn ordinal(&self) -> Option<u16> {
105        if let Some(PeImportNameType::Ordinal(ordinal)) = self.import_name_type {
106            Some(ordinal)
107        } else {
108            None
109        }
110    }
111
112    pub fn is_missing_decorations(&self) -> bool {
113        self.import_name_type == Some(PeImportNameType::Undecorated)
114            || self.import_name_type == Some(PeImportNameType::NoPrefix)
115    }
116}
117
118/// Calling convention for a function defined in an external library.
119///
120/// The usize value, where present, indicates the size of the function's argument list
121/// in bytes.
122#[derive(Clone, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
123pub enum DllCallingConvention {
124    C,
125    Stdcall(usize),
126    Fastcall(usize),
127    Vectorcall(usize),
128}
129
130#[derive(Clone, Encodable, Decodable, HashStable_Generic, Debug)]
131pub struct ForeignModule {
132    pub foreign_items: Vec<DefId>,
133    pub def_id: DefId,
134    pub abi: ExternAbi,
135}
136
137#[derive(Copy, Clone, Debug, HashStable_Generic)]
138pub struct ExternCrate {
139    pub src: ExternCrateSource,
140
141    /// span of the extern crate that caused this to be loaded
142    pub span: Span,
143
144    /// Number of links to reach the extern;
145    /// used to select the extern with the shortest path
146    pub path_len: usize,
147
148    /// Crate that depends on this crate
149    pub dependency_of: CrateNum,
150}
151
152impl ExternCrate {
153    /// If true, then this crate is the crate named by the extern
154    /// crate referenced above. If false, then this crate is a dep
155    /// of the crate.
156    #[inline]
157    pub fn is_direct(&self) -> bool {
158        self.dependency_of == LOCAL_CRATE
159    }
160
161    #[inline]
162    pub fn rank(&self) -> impl PartialOrd {
163        // Prefer:
164        // - direct extern crate to indirect
165        // - shorter paths to longer
166        (self.is_direct(), !self.path_len)
167    }
168}
169
170#[derive(Copy, Clone, Debug, HashStable_Generic)]
171pub enum ExternCrateSource {
172    /// Crate is loaded by `extern crate`.
173    Extern(
174        /// def_id of the item in the current crate that caused
175        /// this crate to be loaded; note that there could be multiple
176        /// such ids
177        DefId,
178    ),
179    /// Crate is implicitly loaded by a path resolving through extern prelude.
180    Path,
181}
182
183/// A store of Rust crates, through which their metadata can be accessed.
184///
185/// Note that this trait should probably not be expanding today. All new
186/// functionality should be driven through queries instead!
187///
188/// If you find a method on this trait named `{name}_untracked` it signifies
189/// that it's *not* tracked for dependency information throughout compilation
190/// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
191/// during resolve)
192pub trait CrateStore: std::fmt::Debug {
193    fn as_any(&self) -> &dyn Any;
194    fn untracked_as_any(&mut self) -> &mut dyn Any;
195
196    // Foreign definitions.
197    // This information is safe to access, since it's hashed as part of the DefPathHash, which incr.
198    // comp. uses to identify a DefId.
199    fn def_key(&self, def: DefId) -> DefKey;
200    fn def_path(&self, def: DefId) -> DefPath;
201    fn def_path_hash(&self, def: DefId) -> DefPathHash;
202
203    // This information is safe to access, since it's hashed as part of the StableCrateId, which
204    // incr. comp. uses to identify a CrateNum.
205    fn crate_name(&self, cnum: CrateNum) -> Symbol;
206    fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId;
207}
208
209pub type CrateStoreDyn = dyn CrateStore + sync::DynSync + sync::DynSend;
210
211pub struct Untracked {
212    pub cstore: FreezeLock<Box<CrateStoreDyn>>,
213    /// Reference span for definitions.
214    pub source_span: AppendOnlyIndexVec<LocalDefId, Span>,
215    pub definitions: FreezeLock<Definitions>,
216    /// The interned [StableCrateId]s.
217    pub stable_crate_ids: FreezeLock<StableCrateIdMap>,
218}