]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/middle/cstore.rs
Rollup merge of #87120 - jyn514:rustdoc-cleanup, r=CraftSpider
[rust.git] / compiler / rustc_middle / src / middle / 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::ty::TyCtxt;
6
7 use rustc_ast as ast;
8 use rustc_data_structures::sync::{self, MetadataRef};
9 use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
10 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash};
11 use rustc_macros::HashStable;
12 use rustc_session::search_paths::PathKind;
13 use rustc_session::utils::NativeLibKind;
14 use rustc_session::StableCrateId;
15 use rustc_span::symbol::Symbol;
16 use rustc_span::Span;
17 use rustc_target::spec::Target;
18
19 use std::any::Any;
20 use std::path::{Path, PathBuf};
21
22 // lonely orphan structs and enums looking for a better home
23
24 /// Where a crate came from on the local filesystem. One of these three options
25 /// must be non-None.
26 #[derive(PartialEq, Clone, Debug, HashStable, Encodable, Decodable)]
27 pub struct CrateSource {
28     pub dylib: Option<(PathBuf, PathKind)>,
29     pub rlib: Option<(PathBuf, PathKind)>,
30     pub rmeta: Option<(PathBuf, PathKind)>,
31 }
32
33 impl CrateSource {
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)]
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     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)]
62 pub enum LinkagePreference {
63     RequireDynamic,
64     RequireStatic,
65 }
66
67 #[derive(Clone, Debug, Encodable, Decodable, HashStable)]
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 #[derive(Clone, Debug, PartialEq, Eq, Encodable, Decodable, Hash, HashStable)]
79 pub struct DllImport {
80     pub name: Symbol,
81     pub ordinal: Option<u16>,
82     /// Calling convention for the function.
83     ///
84     /// On x86_64, this is always `DllCallingConvention::C`; on i686, it can be any
85     /// of the values, and we use `DllCallingConvention::C` to represent `"cdecl"`.
86     pub calling_convention: DllCallingConvention,
87     /// Span of import's "extern" declaration; used for diagnostics.
88     pub span: Span,
89 }
90
91 /// Calling convention for a function defined in an external library.
92 ///
93 /// The usize value, where present, indicates the size of the function's argument list
94 /// in bytes.
95 #[derive(Copy, Clone, Debug, PartialEq, Eq, Encodable, Decodable, Hash, HashStable)]
96 pub enum DllCallingConvention {
97     C,
98     Stdcall(usize),
99     Fastcall(usize),
100     Vectorcall(usize),
101 }
102
103 #[derive(Clone, TyEncodable, TyDecodable, HashStable, Debug)]
104 pub struct ForeignModule {
105     pub foreign_items: Vec<DefId>,
106     pub def_id: DefId,
107 }
108
109 #[derive(Copy, Clone, Debug, HashStable)]
110 pub struct ExternCrate {
111     pub src: ExternCrateSource,
112
113     /// span of the extern crate that caused this to be loaded
114     pub span: Span,
115
116     /// Number of links to reach the extern;
117     /// used to select the extern with the shortest path
118     pub path_len: usize,
119
120     /// Crate that depends on this crate
121     pub dependency_of: CrateNum,
122 }
123
124 impl ExternCrate {
125     /// If true, then this crate is the crate named by the extern
126     /// crate referenced above. If false, then this crate is a dep
127     /// of the crate.
128     pub fn is_direct(&self) -> bool {
129         self.dependency_of == LOCAL_CRATE
130     }
131
132     pub fn rank(&self) -> impl PartialOrd {
133         // Prefer:
134         // - direct extern crate to indirect
135         // - shorter paths to longer
136         (self.is_direct(), !self.path_len)
137     }
138 }
139
140 #[derive(Copy, Clone, Debug, HashStable)]
141 pub enum ExternCrateSource {
142     /// Crate is loaded by `extern crate`.
143     Extern(
144         /// def_id of the item in the current crate that caused
145         /// this crate to be loaded; note that there could be multiple
146         /// such ids
147         DefId,
148     ),
149     /// Crate is implicitly loaded by a path resolving through extern prelude.
150     Path,
151 }
152
153 #[derive(Encodable, Decodable)]
154 pub struct EncodedMetadata {
155     pub raw_data: Vec<u8>,
156 }
157
158 impl EncodedMetadata {
159     pub fn new() -> EncodedMetadata {
160         EncodedMetadata { raw_data: Vec::new() }
161     }
162 }
163
164 /// The backend's way to give the crate store access to the metadata in a library.
165 /// Note that it returns the raw metadata bytes stored in the library file, whether
166 /// it is compressed, uncompressed, some weird mix, etc.
167 /// rmeta files are backend independent and not handled here.
168 ///
169 /// At the time of this writing, there is only one backend and one way to store
170 /// metadata in library -- this trait just serves to decouple rustc_metadata from
171 /// the archive reader, which depends on LLVM.
172 pub trait MetadataLoader {
173     fn get_rlib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String>;
174     fn get_dylib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String>;
175 }
176
177 pub type MetadataLoaderDyn = dyn MetadataLoader + Sync;
178
179 /// A store of Rust crates, through which their metadata can be accessed.
180 ///
181 /// Note that this trait should probably not be expanding today. All new
182 /// functionality should be driven through queries instead!
183 ///
184 /// If you find a method on this trait named `{name}_untracked` it signifies
185 /// that it's *not* tracked for dependency information throughout compilation
186 /// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
187 /// during resolve)
188 pub trait CrateStore: std::fmt::Debug {
189     fn as_any(&self) -> &dyn Any;
190
191     // Foreign definitions.
192     // This information is safe to access, since it's hashed as part of the DefPathHash, which incr.
193     // comp. uses to identify a DefId.
194     fn def_key(&self, def: DefId) -> DefKey;
195     fn def_path(&self, def: DefId) -> DefPath;
196     fn def_path_hash(&self, def: DefId) -> DefPathHash;
197
198     // This information is safe to access, since it's hashed as part of the StableCrateId, which
199     // incr.  comp. uses to identify a CrateNum.
200     fn crate_name(&self, cnum: CrateNum) -> Symbol;
201     fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId;
202
203     /// Fetch a DefId from a DefPathHash for a foreign crate.
204     fn def_path_hash_to_def_id(
205         &self,
206         cnum: CrateNum,
207         index_guess: u32,
208         hash: DefPathHash,
209     ) -> Option<DefId>;
210
211     // utility functions
212     fn encode_metadata(&self, tcx: TyCtxt<'_>) -> EncodedMetadata;
213 }
214
215 pub type CrateStoreDyn = dyn CrateStore + sync::Sync;