]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_session/src/cstore.rs
Rollup merge of #106699 - eholk:await-chains-drop-tracking, r=wesleywiser
[rust.git] / compiler / rustc_session / src / 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
5 use crate::search_paths::PathKind;
6 use crate::utils::NativeLibKind;
7 use crate::Session;
8 use rustc_ast as ast;
9 use rustc_data_structures::sync::{self, MetadataRef, RwLock};
10 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, StableCrateId, LOCAL_CRATE};
11 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash, Definitions};
12 use rustc_index::vec::IndexVec;
13 use rustc_span::hygiene::{ExpnHash, ExpnId};
14 use rustc_span::symbol::Symbol;
15 use rustc_span::Span;
16 use rustc_target::spec::Target;
17
18 use std::any::Any;
19 use std::path::{Path, PathBuf};
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)]
26 pub struct CrateSource {
27     pub dylib: Option<(PathBuf, PathKind)>,
28     pub rlib: Option<(PathBuf, PathKind)>,
29     pub rmeta: Option<(PathBuf, PathKind)>,
30 }
31
32 impl 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)]
41 pub 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 allocator.
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
52 impl 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)]
63 pub enum LinkagePreference {
64     RequireDynamic,
65     RequireStatic,
66 }
67
68 #[derive(Debug, Encodable, Decodable, HashStable_Generic)]
69 pub struct NativeLib {
70     pub kind: NativeLibKind,
71     pub name: Option<Symbol>,
72     /// If packed_bundled_libs enabled, actual filename of library is stored.
73     pub filename: Option<Symbol>,
74     pub cfg: Option<ast::MetaItem>,
75     pub foreign_module: Option<DefId>,
76     pub wasm_import_module: Option<Symbol>,
77     pub verbatim: Option<bool>,
78     pub dll_imports: Vec<DllImport>,
79 }
80
81 impl NativeLib {
82     pub fn has_modifiers(&self) -> bool {
83         self.verbatim.is_some() || self.kind.has_modifiers()
84     }
85 }
86
87 /// Different ways that the PE Format can decorate a symbol name.
88 /// From <https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-name-type>
89 #[derive(Copy, Clone, Debug, Encodable, Decodable, HashStable_Generic, PartialEq, Eq)]
90 pub enum PeImportNameType {
91     /// IMPORT_ORDINAL
92     /// Uses the ordinal (i.e., a number) rather than the name.
93     Ordinal(u16),
94     /// Same as IMPORT_NAME
95     /// Name is decorated with all prefixes and suffixes.
96     Decorated,
97     /// Same as IMPORT_NAME_NOPREFIX
98     /// Prefix (e.g., the leading `_` or `@`) is skipped, but suffix is kept.
99     NoPrefix,
100     /// Same as IMPORT_NAME_UNDECORATE
101     /// Prefix (e.g., the leading `_` or `@`) and suffix (the first `@` and all
102     /// trailing characters) are skipped.
103     Undecorated,
104 }
105
106 #[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
107 pub struct DllImport {
108     pub name: Symbol,
109     pub import_name_type: Option<PeImportNameType>,
110     /// Calling convention for the function.
111     ///
112     /// On x86_64, this is always `DllCallingConvention::C`; on i686, it can be any
113     /// of the values, and we use `DllCallingConvention::C` to represent `"cdecl"`.
114     pub calling_convention: DllCallingConvention,
115     /// Span of import's "extern" declaration; used for diagnostics.
116     pub span: Span,
117     /// Is this for a function (rather than a static variable).
118     pub is_fn: bool,
119 }
120
121 impl DllImport {
122     pub fn ordinal(&self) -> Option<u16> {
123         if let Some(PeImportNameType::Ordinal(ordinal)) = self.import_name_type {
124             Some(ordinal)
125         } else {
126             None
127         }
128     }
129 }
130
131 /// Calling convention for a function defined in an external library.
132 ///
133 /// The usize value, where present, indicates the size of the function's argument list
134 /// in bytes.
135 #[derive(Clone, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
136 pub enum DllCallingConvention {
137     C,
138     Stdcall(usize),
139     Fastcall(usize),
140     Vectorcall(usize),
141 }
142
143 #[derive(Clone, Encodable, Decodable, HashStable_Generic, Debug)]
144 pub struct ForeignModule {
145     pub foreign_items: Vec<DefId>,
146     pub def_id: DefId,
147 }
148
149 #[derive(Copy, Clone, Debug, HashStable_Generic)]
150 pub struct ExternCrate {
151     pub src: ExternCrateSource,
152
153     /// span of the extern crate that caused this to be loaded
154     pub span: Span,
155
156     /// Number of links to reach the extern;
157     /// used to select the extern with the shortest path
158     pub path_len: usize,
159
160     /// Crate that depends on this crate
161     pub dependency_of: CrateNum,
162 }
163
164 impl ExternCrate {
165     /// If true, then this crate is the crate named by the extern
166     /// crate referenced above. If false, then this crate is a dep
167     /// of the crate.
168     #[inline]
169     pub fn is_direct(&self) -> bool {
170         self.dependency_of == LOCAL_CRATE
171     }
172
173     #[inline]
174     pub fn rank(&self) -> impl PartialOrd {
175         // Prefer:
176         // - direct extern crate to indirect
177         // - shorter paths to longer
178         (self.is_direct(), !self.path_len)
179     }
180 }
181
182 #[derive(Copy, Clone, Debug, HashStable_Generic)]
183 pub enum ExternCrateSource {
184     /// Crate is loaded by `extern crate`.
185     Extern(
186         /// def_id of the item in the current crate that caused
187         /// this crate to be loaded; note that there could be multiple
188         /// such ids
189         DefId,
190     ),
191     /// Crate is implicitly loaded by a path resolving through extern prelude.
192     Path,
193 }
194
195 /// The backend's way to give the crate store access to the metadata in a library.
196 /// Note that it returns the raw metadata bytes stored in the library file, whether
197 /// it is compressed, uncompressed, some weird mix, etc.
198 /// rmeta files are backend independent and not handled here.
199 ///
200 /// At the time of this writing, there is only one backend and one way to store
201 /// metadata in library -- this trait just serves to decouple rustc_metadata from
202 /// the archive reader, which depends on LLVM.
203 pub trait MetadataLoader {
204     fn get_rlib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String>;
205     fn get_dylib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String>;
206 }
207
208 pub type MetadataLoaderDyn = dyn MetadataLoader + Sync;
209
210 /// A store of Rust crates, through which their metadata can be accessed.
211 ///
212 /// Note that this trait should probably not be expanding today. All new
213 /// functionality should be driven through queries instead!
214 ///
215 /// If you find a method on this trait named `{name}_untracked` it signifies
216 /// that it's *not* tracked for dependency information throughout compilation
217 /// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
218 /// during resolve)
219 pub trait CrateStore: std::fmt::Debug {
220     fn as_any(&self) -> &dyn Any;
221     fn untracked_as_any(&mut self) -> &mut dyn Any;
222
223     // Foreign definitions.
224     // This information is safe to access, since it's hashed as part of the DefPathHash, which incr.
225     // comp. uses to identify a DefId.
226     fn def_key(&self, def: DefId) -> DefKey;
227     fn def_path(&self, def: DefId) -> DefPath;
228     fn def_path_hash(&self, def: DefId) -> DefPathHash;
229
230     // This information is safe to access, since it's hashed as part of the StableCrateId, which
231     // incr. comp. uses to identify a CrateNum.
232     fn crate_name(&self, cnum: CrateNum) -> Symbol;
233     fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId;
234     fn stable_crate_id_to_crate_num(&self, stable_crate_id: StableCrateId) -> CrateNum;
235
236     /// Fetch a DefId from a DefPathHash for a foreign crate.
237     fn def_path_hash_to_def_id(&self, cnum: CrateNum, hash: DefPathHash) -> DefId;
238     fn expn_hash_to_expn_id(
239         &self,
240         sess: &Session,
241         cnum: CrateNum,
242         index_guess: u32,
243         hash: ExpnHash,
244     ) -> ExpnId;
245
246     /// Imports all `SourceFile`s from the given crate into the current session.
247     /// This normally happens automatically when we decode a `Span` from
248     /// that crate's metadata - however, the incr comp cache needs
249     /// to trigger this manually when decoding a foreign `Span`
250     fn import_source_files(&self, sess: &Session, cnum: CrateNum);
251 }
252
253 pub type CrateStoreDyn = dyn CrateStore + sync::Sync;
254
255 #[derive(Debug)]
256 pub struct Untracked {
257     pub cstore: Box<CrateStoreDyn>,
258     /// Reference span for definitions.
259     pub source_span: IndexVec<LocalDefId, Span>,
260     pub definitions: RwLock<Definitions>,
261 }