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