]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_session/src/cstore.rs
Rollup merge of #99000 - JulianKnodt:allow_resolve_no_substs, r=lcnr
[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};
10 use rustc_hir::def_id::{CrateNum, DefId, StableCrateId, LOCAL_CRATE};
11 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
12 use rustc_span::hygiene::{ExpnHash, ExpnId};
13 use rustc_span::symbol::Symbol;
14 use rustc_span::Span;
15 use rustc_target::spec::Target;
16
17 use std::any::Any;
18 use std::path::{Path, PathBuf};
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)]
25 pub struct CrateSource {
26     pub dylib: Option<(PathBuf, PathKind)>,
27     pub rlib: Option<(PathBuf, PathKind)>,
28     pub rmeta: Option<(PathBuf, PathKind)>,
29 }
30
31 impl CrateSource {
32     #[inline]
33     pub fn paths(&self) -> impl Iterator<Item = &PathBuf> {
34         self.dylib.iter().chain(self.rlib.iter()).chain(self.rmeta.iter()).map(|p| &p.0)
35     }
36 }
37
38 #[derive(Encodable, Decodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
39 #[derive(HashStable_Generic)]
40 pub enum CrateDepKind {
41     /// A dependency that is only used for its macros.
42     MacrosOnly,
43     /// A dependency that is always injected into the dependency list and so
44     /// doesn't need to be linked to an rlib, e.g., the injected allocator.
45     Implicit,
46     /// A dependency that is required by an rlib version of this crate.
47     /// Ordinary `extern crate`s result in `Explicit` dependencies.
48     Explicit,
49 }
50
51 impl CrateDepKind {
52     #[inline]
53     pub fn macros_only(self) -> bool {
54         match self {
55             CrateDepKind::MacrosOnly => true,
56             CrateDepKind::Implicit | CrateDepKind::Explicit => false,
57         }
58     }
59 }
60
61 #[derive(Copy, Debug, PartialEq, Clone, Encodable, Decodable, HashStable_Generic)]
62 pub enum LinkagePreference {
63     RequireDynamic,
64     RequireStatic,
65 }
66
67 #[derive(Debug, Encodable, Decodable, HashStable_Generic)]
68 pub struct NativeLib {
69     pub kind: NativeLibKind,
70     pub name: Option<Symbol>,
71     pub cfg: Option<ast::MetaItem>,
72     pub foreign_module: Option<DefId>,
73     pub wasm_import_module: Option<Symbol>,
74     pub verbatim: Option<bool>,
75     pub dll_imports: Vec<DllImport>,
76 }
77
78 impl NativeLib {
79     pub fn has_modifiers(&self) -> bool {
80         self.verbatim.is_some() || self.kind.has_modifiers()
81     }
82 }
83
84 #[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
85 pub struct DllImport {
86     pub name: Symbol,
87     pub ordinal: Option<u16>,
88     /// Calling convention for the function.
89     ///
90     /// On x86_64, this is always `DllCallingConvention::C`; on i686, it can be any
91     /// of the values, and we use `DllCallingConvention::C` to represent `"cdecl"`.
92     pub calling_convention: DllCallingConvention,
93     /// Span of import's "extern" declaration; used for diagnostics.
94     pub span: Span,
95 }
96
97 /// Calling convention for a function defined in an external library.
98 ///
99 /// The usize value, where present, indicates the size of the function's argument list
100 /// in bytes.
101 #[derive(Clone, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
102 pub enum DllCallingConvention {
103     C,
104     Stdcall(usize),
105     Fastcall(usize),
106     Vectorcall(usize),
107 }
108
109 #[derive(Clone, Encodable, Decodable, HashStable_Generic, Debug)]
110 pub struct ForeignModule {
111     pub foreign_items: Vec<DefId>,
112     pub def_id: DefId,
113 }
114
115 #[derive(Copy, Clone, Debug, HashStable_Generic)]
116 pub struct ExternCrate {
117     pub src: ExternCrateSource,
118
119     /// span of the extern crate that caused this to be loaded
120     pub span: Span,
121
122     /// Number of links to reach the extern;
123     /// used to select the extern with the shortest path
124     pub path_len: usize,
125
126     /// Crate that depends on this crate
127     pub dependency_of: CrateNum,
128 }
129
130 impl ExternCrate {
131     /// If true, then this crate is the crate named by the extern
132     /// crate referenced above. If false, then this crate is a dep
133     /// of the crate.
134     #[inline]
135     pub fn is_direct(&self) -> bool {
136         self.dependency_of == LOCAL_CRATE
137     }
138
139     #[inline]
140     pub fn rank(&self) -> impl PartialOrd {
141         // Prefer:
142         // - direct extern crate to indirect
143         // - shorter paths to longer
144         (self.is_direct(), !self.path_len)
145     }
146 }
147
148 #[derive(Copy, Clone, Debug, HashStable_Generic)]
149 pub enum ExternCrateSource {
150     /// Crate is loaded by `extern crate`.
151     Extern(
152         /// def_id of the item in the current crate that caused
153         /// this crate to be loaded; note that there could be multiple
154         /// such ids
155         DefId,
156     ),
157     /// Crate is implicitly loaded by a path resolving through extern prelude.
158     Path,
159 }
160
161 /// The backend's way to give the crate store access to the metadata in a library.
162 /// Note that it returns the raw metadata bytes stored in the library file, whether
163 /// it is compressed, uncompressed, some weird mix, etc.
164 /// rmeta files are backend independent and not handled here.
165 ///
166 /// At the time of this writing, there is only one backend and one way to store
167 /// metadata in library -- this trait just serves to decouple rustc_metadata from
168 /// the archive reader, which depends on LLVM.
169 pub trait MetadataLoader {
170     fn get_rlib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String>;
171     fn get_dylib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String>;
172 }
173
174 pub type MetadataLoaderDyn = dyn MetadataLoader + Sync;
175
176 /// A store of Rust crates, through which their metadata can be accessed.
177 ///
178 /// Note that this trait should probably not be expanding today. All new
179 /// functionality should be driven through queries instead!
180 ///
181 /// If you find a method on this trait named `{name}_untracked` it signifies
182 /// that it's *not* tracked for dependency information throughout compilation
183 /// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
184 /// during resolve)
185 pub trait CrateStore: std::fmt::Debug {
186     fn as_any(&self) -> &dyn Any;
187
188     // Foreign definitions.
189     // This information is safe to access, since it's hashed as part of the DefPathHash, which incr.
190     // comp. uses to identify a DefId.
191     fn def_key(&self, def: DefId) -> DefKey;
192     fn def_path(&self, def: DefId) -> DefPath;
193     fn def_path_hash(&self, def: DefId) -> DefPathHash;
194
195     // This information is safe to access, since it's hashed as part of the StableCrateId, which
196     // incr.  comp. uses to identify a CrateNum.
197     fn crate_name(&self, cnum: CrateNum) -> Symbol;
198     fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId;
199     fn stable_crate_id_to_crate_num(&self, stable_crate_id: StableCrateId) -> CrateNum;
200
201     /// Fetch a DefId from a DefPathHash for a foreign crate.
202     fn def_path_hash_to_def_id(&self, cnum: CrateNum, hash: DefPathHash) -> DefId;
203     fn expn_hash_to_expn_id(
204         &self,
205         sess: &Session,
206         cnum: CrateNum,
207         index_guess: u32,
208         hash: ExpnHash,
209     ) -> ExpnId;
210
211     /// Imports all `SourceFile`s from the given crate into the current session.
212     /// This normally happens automatically when we decode a `Span` from
213     /// that crate's metadata - however, the incr comp cache needs
214     /// to trigger this manually when decoding a foreign `Span`
215     fn import_source_files(&self, sess: &Session, cnum: CrateNum);
216 }
217
218 pub type CrateStoreDyn = dyn CrateStore + sync::Sync;