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_ast as ast;
10use rustc_data_structures::sync::{self, AppendOnlyIndexVec, FreezeLock};
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;
19use crate::utils::NativeLibKind;
20
21// lonely orphan structs and enums looking for a better home
22
23/// Where a crate came from on the local filesystem. One of these three options
24/// must be non-None.
25#[derive(PartialEq, Clone, Debug, HashStable_Generic, Encodable, Decodable)]
26pub struct CrateSource {
27    pub dylib: Option<(PathBuf, PathKind)>,
28    pub rlib: Option<(PathBuf, PathKind)>,
29    pub rmeta: 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<ast::MetaItemInner>,
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/// Different ways that the PE Format can decorate a symbol name.
91/// From <https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-name-type>
92#[derive(Copy, Clone, Debug, Encodable, Decodable, HashStable_Generic, PartialEq, Eq)]
93pub enum PeImportNameType {
94    /// IMPORT_ORDINAL
95    /// Uses the ordinal (i.e., a number) rather than the name.
96    Ordinal(u16),
97    /// Same as IMPORT_NAME
98    /// Name is decorated with all prefixes and suffixes.
99    Decorated,
100    /// Same as IMPORT_NAME_NOPREFIX
101    /// Prefix (e.g., the leading `_` or `@`) is skipped, but suffix is kept.
102    NoPrefix,
103    /// Same as IMPORT_NAME_UNDECORATE
104    /// Prefix (e.g., the leading `_` or `@`) and suffix (the first `@` and all
105    /// trailing characters) are skipped.
106    Undecorated,
107}
108
109#[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
110pub struct DllImport {
111    pub name: Symbol,
112    pub import_name_type: Option<PeImportNameType>,
113    /// Calling convention for the function.
114    ///
115    /// On x86_64, this is always `DllCallingConvention::C`; on i686, it can be any
116    /// of the values, and we use `DllCallingConvention::C` to represent `"cdecl"`.
117    pub calling_convention: DllCallingConvention,
118    /// Span of import's "extern" declaration; used for diagnostics.
119    pub span: Span,
120    /// Is this for a function (rather than a static variable).
121    pub is_fn: bool,
122}
123
124impl DllImport {
125    pub fn ordinal(&self) -> Option<u16> {
126        if let Some(PeImportNameType::Ordinal(ordinal)) = self.import_name_type {
127            Some(ordinal)
128        } else {
129            None
130        }
131    }
132
133    pub fn is_missing_decorations(&self) -> bool {
134        self.import_name_type == Some(PeImportNameType::Undecorated)
135            || self.import_name_type == Some(PeImportNameType::NoPrefix)
136    }
137}
138
139/// Calling convention for a function defined in an external library.
140///
141/// The usize value, where present, indicates the size of the function's argument list
142/// in bytes.
143#[derive(Clone, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
144pub enum DllCallingConvention {
145    C,
146    Stdcall(usize),
147    Fastcall(usize),
148    Vectorcall(usize),
149}
150
151#[derive(Clone, Encodable, Decodable, HashStable_Generic, Debug)]
152pub struct ForeignModule {
153    pub foreign_items: Vec<DefId>,
154    pub def_id: DefId,
155    pub abi: ExternAbi,
156}
157
158#[derive(Copy, Clone, Debug, HashStable_Generic)]
159pub struct ExternCrate {
160    pub src: ExternCrateSource,
161
162    /// span of the extern crate that caused this to be loaded
163    pub span: Span,
164
165    /// Number of links to reach the extern;
166    /// used to select the extern with the shortest path
167    pub path_len: usize,
168
169    /// Crate that depends on this crate
170    pub dependency_of: CrateNum,
171}
172
173impl ExternCrate {
174    /// If true, then this crate is the crate named by the extern
175    /// crate referenced above. If false, then this crate is a dep
176    /// of the crate.
177    #[inline]
178    pub fn is_direct(&self) -> bool {
179        self.dependency_of == LOCAL_CRATE
180    }
181
182    #[inline]
183    pub fn rank(&self) -> impl PartialOrd {
184        // Prefer:
185        // - direct extern crate to indirect
186        // - shorter paths to longer
187        (self.is_direct(), !self.path_len)
188    }
189}
190
191#[derive(Copy, Clone, Debug, HashStable_Generic)]
192pub enum ExternCrateSource {
193    /// Crate is loaded by `extern crate`.
194    Extern(
195        /// def_id of the item in the current crate that caused
196        /// this crate to be loaded; note that there could be multiple
197        /// such ids
198        DefId,
199    ),
200    /// Crate is implicitly loaded by a path resolving through extern prelude.
201    Path,
202}
203
204/// A store of Rust crates, through which their metadata can be accessed.
205///
206/// Note that this trait should probably not be expanding today. All new
207/// functionality should be driven through queries instead!
208///
209/// If you find a method on this trait named `{name}_untracked` it signifies
210/// that it's *not* tracked for dependency information throughout compilation
211/// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
212/// during resolve)
213pub trait CrateStore: std::fmt::Debug {
214    fn as_any(&self) -> &dyn Any;
215    fn untracked_as_any(&mut self) -> &mut dyn Any;
216
217    // Foreign definitions.
218    // This information is safe to access, since it's hashed as part of the DefPathHash, which incr.
219    // comp. uses to identify a DefId.
220    fn def_key(&self, def: DefId) -> DefKey;
221    fn def_path(&self, def: DefId) -> DefPath;
222    fn def_path_hash(&self, def: DefId) -> DefPathHash;
223
224    // This information is safe to access, since it's hashed as part of the StableCrateId, which
225    // incr. comp. uses to identify a CrateNum.
226    fn crate_name(&self, cnum: CrateNum) -> Symbol;
227    fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId;
228}
229
230pub type CrateStoreDyn = dyn CrateStore + sync::DynSync + sync::DynSend;
231
232pub struct Untracked {
233    pub cstore: FreezeLock<Box<CrateStoreDyn>>,
234    /// Reference span for definitions.
235    pub source_span: AppendOnlyIndexVec<LocalDefId, Span>,
236    pub definitions: FreezeLock<Definitions>,
237    /// The interned [StableCrateId]s.
238    pub stable_crate_ids: FreezeLock<StableCrateIdMap>,
239}