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