• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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::owned_slice::OwnedSlice;
10 use rustc_data_structures::sync::{self, AppendOnlyIndexVec, RwLock};
11 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, StableCrateId, LOCAL_CRATE};
12 use rustc_hir::definitions::{DefKey, DefPath, DefPathHash, Definitions};
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]
paths(&self) -> impl Iterator<Item = &PathBuf>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]
macros_only(self) -> bool54     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: 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 verbatim: Option<bool>,
77     pub dll_imports: Vec<DllImport>,
78 }
79 
80 impl NativeLib {
has_modifiers(&self) -> bool81     pub fn has_modifiers(&self) -> bool {
82         self.verbatim.is_some() || self.kind.has_modifiers()
83     }
84 
wasm_import_module(&self) -> Option<Symbol>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)]
93 pub 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)]
110 pub 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 
124 impl DllImport {
ordinal(&self) -> Option<u16>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 
134 /// Calling convention for a function defined in an external library.
135 ///
136 /// The usize value, where present, indicates the size of the function's argument list
137 /// in bytes.
138 #[derive(Clone, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
139 pub enum DllCallingConvention {
140     C,
141     Stdcall(usize),
142     Fastcall(usize),
143     Vectorcall(usize),
144 }
145 
146 #[derive(Clone, Encodable, Decodable, HashStable_Generic, Debug)]
147 pub struct ForeignModule {
148     pub foreign_items: Vec<DefId>,
149     pub def_id: DefId,
150 }
151 
152 #[derive(Copy, Clone, Debug, HashStable_Generic)]
153 pub struct ExternCrate {
154     pub src: ExternCrateSource,
155 
156     /// span of the extern crate that caused this to be loaded
157     pub span: Span,
158 
159     /// Number of links to reach the extern;
160     /// used to select the extern with the shortest path
161     pub path_len: usize,
162 
163     /// Crate that depends on this crate
164     pub dependency_of: CrateNum,
165 }
166 
167 impl ExternCrate {
168     /// If true, then this crate is the crate named by the extern
169     /// crate referenced above. If false, then this crate is a dep
170     /// of the crate.
171     #[inline]
is_direct(&self) -> bool172     pub fn is_direct(&self) -> bool {
173         self.dependency_of == LOCAL_CRATE
174     }
175 
176     #[inline]
rank(&self) -> impl PartialOrd177     pub fn rank(&self) -> impl PartialOrd {
178         // Prefer:
179         // - direct extern crate to indirect
180         // - shorter paths to longer
181         (self.is_direct(), !self.path_len)
182     }
183 }
184 
185 #[derive(Copy, Clone, Debug, HashStable_Generic)]
186 pub enum ExternCrateSource {
187     /// Crate is loaded by `extern crate`.
188     Extern(
189         /// def_id of the item in the current crate that caused
190         /// this crate to be loaded; note that there could be multiple
191         /// such ids
192         DefId,
193     ),
194     /// Crate is implicitly loaded by a path resolving through extern prelude.
195     Path,
196 }
197 
198 /// The backend's way to give the crate store access to the metadata in a library.
199 /// Note that it returns the raw metadata bytes stored in the library file, whether
200 /// it is compressed, uncompressed, some weird mix, etc.
201 /// rmeta files are backend independent and not handled here.
202 ///
203 /// At the time of this writing, there is only one backend and one way to store
204 /// metadata in library -- this trait just serves to decouple rustc_metadata from
205 /// the archive reader, which depends on LLVM.
206 pub trait MetadataLoader: std::fmt::Debug {
get_rlib_metadata(&self, target: &Target, filename: &Path) -> Result<OwnedSlice, String>207     fn get_rlib_metadata(&self, target: &Target, filename: &Path) -> Result<OwnedSlice, String>;
get_dylib_metadata(&self, target: &Target, filename: &Path) -> Result<OwnedSlice, String>208     fn get_dylib_metadata(&self, target: &Target, filename: &Path) -> Result<OwnedSlice, String>;
209 }
210 
211 pub type MetadataLoaderDyn = dyn MetadataLoader + Send + Sync + sync::DynSend + sync::DynSync;
212 
213 /// A store of Rust crates, through which their metadata can be accessed.
214 ///
215 /// Note that this trait should probably not be expanding today. All new
216 /// functionality should be driven through queries instead!
217 ///
218 /// If you find a method on this trait named `{name}_untracked` it signifies
219 /// that it's *not* tracked for dependency information throughout compilation
220 /// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
221 /// during resolve)
222 pub trait CrateStore: std::fmt::Debug {
as_any(&self) -> &dyn Any223     fn as_any(&self) -> &dyn Any;
untracked_as_any(&mut self) -> &mut dyn Any224     fn untracked_as_any(&mut self) -> &mut dyn Any;
225 
226     // Foreign definitions.
227     // This information is safe to access, since it's hashed as part of the DefPathHash, which incr.
228     // comp. uses to identify a DefId.
def_key(&self, def: DefId) -> DefKey229     fn def_key(&self, def: DefId) -> DefKey;
def_path(&self, def: DefId) -> DefPath230     fn def_path(&self, def: DefId) -> DefPath;
def_path_hash(&self, def: DefId) -> DefPathHash231     fn def_path_hash(&self, def: DefId) -> DefPathHash;
232 
233     // This information is safe to access, since it's hashed as part of the StableCrateId, which
234     // incr. comp. uses to identify a CrateNum.
crate_name(&self, cnum: CrateNum) -> Symbol235     fn crate_name(&self, cnum: CrateNum) -> Symbol;
stable_crate_id(&self, cnum: CrateNum) -> StableCrateId236     fn stable_crate_id(&self, cnum: CrateNum) -> StableCrateId;
stable_crate_id_to_crate_num(&self, stable_crate_id: StableCrateId) -> CrateNum237     fn stable_crate_id_to_crate_num(&self, stable_crate_id: StableCrateId) -> CrateNum;
238 
239     /// Fetch a DefId from a DefPathHash for a foreign crate.
def_path_hash_to_def_id(&self, cnum: CrateNum, hash: DefPathHash) -> DefId240     fn def_path_hash_to_def_id(&self, cnum: CrateNum, hash: DefPathHash) -> DefId;
expn_hash_to_expn_id( &self, sess: &Session, cnum: CrateNum, index_guess: u32, hash: ExpnHash, ) -> ExpnId241     fn expn_hash_to_expn_id(
242         &self,
243         sess: &Session,
244         cnum: CrateNum,
245         index_guess: u32,
246         hash: ExpnHash,
247     ) -> ExpnId;
248 
249     /// Imports all `SourceFile`s from the given crate into the current session.
250     /// This normally happens automatically when we decode a `Span` from
251     /// that crate's metadata - however, the incr comp cache needs
252     /// to trigger this manually when decoding a foreign `Span`
import_source_files(&self, sess: &Session, cnum: CrateNum)253     fn import_source_files(&self, sess: &Session, cnum: CrateNum);
254 }
255 
256 pub type CrateStoreDyn = dyn CrateStore + sync::DynSync + sync::DynSend;
257 
258 pub struct Untracked {
259     pub cstore: RwLock<Box<CrateStoreDyn>>,
260     /// Reference span for definitions.
261     pub source_span: AppendOnlyIndexVec<LocalDefId, Span>,
262     pub definitions: RwLock<Definitions>,
263 }
264