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.
8 use rustc_ast
::expand
::allocator
::AllocatorKind
;
9 use rustc_data_structures
::svh
::Svh
;
10 use rustc_data_structures
::sync
::{self, MetadataRef}
;
11 use rustc_hir
::def
::DefKind
;
12 use rustc_hir
::def_id
::{CrateNum, DefId, LOCAL_CRATE}
;
13 use rustc_hir
::definitions
::{DefKey, DefPath, DefPathHash}
;
14 use rustc_macros
::HashStable
;
15 use rustc_session
::search_paths
::PathKind
;
16 use rustc_session
::utils
::NativeLibKind
;
17 use rustc_session
::CrateDisambiguator
;
18 use rustc_span
::symbol
::Symbol
;
20 use rustc_target
::spec
::Target
;
23 use std
::path
::{Path, PathBuf}
;
25 // lonely orphan structs and enums looking for a better home
27 /// Where a crate came from on the local filesystem. One of these three options
29 #[derive(PartialEq, Clone, Debug, HashStable, Encodable, Decodable)]
30 pub struct CrateSource
{
31 pub dylib
: Option
<(PathBuf
, PathKind
)>,
32 pub rlib
: Option
<(PathBuf
, PathKind
)>,
33 pub rmeta
: Option
<(PathBuf
, PathKind
)>,
37 pub fn paths(&self) -> impl Iterator
<Item
= &PathBuf
> {
38 self.dylib
.iter().chain(self.rlib
.iter()).chain(self.rmeta
.iter()).map(|p
| &p
.0)
42 #[derive(Encodable, Decodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
44 pub enum CrateDepKind
{
45 /// A dependency that is only used for its macros.
47 /// A dependency that is always injected into the dependency list and so
48 /// doesn't need to be linked to an rlib, e.g., the injected allocator.
50 /// A dependency that is required by an rlib version of this crate.
51 /// Ordinary `extern crate`s result in `Explicit` dependencies.
56 pub fn macros_only(self) -> bool
{
58 CrateDepKind
::MacrosOnly
=> true,
59 CrateDepKind
::Implicit
| CrateDepKind
::Explicit
=> false,
64 #[derive(PartialEq, Clone, Debug, Encodable, Decodable)]
72 pub fn is_some(&self) -> bool
{
73 matches
!(self, LibSource
::Some(_
))
76 pub fn option(&self) -> Option
<PathBuf
> {
78 LibSource
::Some(ref p
) => Some(p
.clone()),
79 LibSource
::MetadataOnly
| LibSource
::None
=> None
,
84 #[derive(Copy, Debug, PartialEq, Clone, Encodable, Decodable, HashStable)]
85 pub enum LinkagePreference
{
90 #[derive(Clone, Debug, Encodable, Decodable, HashStable)]
91 pub struct NativeLib
{
92 pub kind
: NativeLibKind
,
93 pub name
: Option
<Symbol
>,
94 pub cfg
: Option
<ast
::MetaItem
>,
95 pub foreign_module
: Option
<DefId
>,
96 pub wasm_import_module
: Option
<Symbol
>,
97 pub verbatim
: Option
<bool
>,
98 pub dll_imports
: Vec
<DllImport
>,
101 #[derive(Clone, Debug, Encodable, Decodable, HashStable)]
102 pub struct DllImport
{
104 pub ordinal
: Option
<u16>,
107 #[derive(Clone, TyEncodable, TyDecodable, HashStable, Debug)]
108 pub struct ForeignModule
{
109 pub foreign_items
: Vec
<DefId
>,
113 #[derive(Copy, Clone, Debug, HashStable)]
114 pub struct ExternCrate
{
115 pub src
: ExternCrateSource
,
117 /// span of the extern crate that caused this to be loaded
120 /// Number of links to reach the extern;
121 /// used to select the extern with the shortest path
124 /// Crate that depends on this crate
125 pub dependency_of
: CrateNum
,
129 /// If true, then this crate is the crate named by the extern
130 /// crate referenced above. If false, then this crate is a dep
132 pub fn is_direct(&self) -> bool
{
133 self.dependency_of
== LOCAL_CRATE
136 pub fn rank(&self) -> impl PartialOrd
{
138 // - direct extern crate to indirect
139 // - shorter paths to longer
140 (self.is_direct(), !self.path_len
)
144 #[derive(Copy, Clone, Debug, HashStable)]
145 pub enum ExternCrateSource
{
146 /// Crate is loaded by `extern crate`.
148 /// def_id of the item in the current crate that caused
149 /// this crate to be loaded; note that there could be multiple
153 /// Crate is implicitly loaded by a path resolving through extern prelude.
157 #[derive(Encodable, Decodable)]
158 pub struct EncodedMetadata
{
159 pub raw_data
: Vec
<u8>,
162 impl EncodedMetadata
{
163 pub fn new() -> EncodedMetadata
{
164 EncodedMetadata { raw_data: Vec::new() }
168 /// The backend's way to give the crate store access to the metadata in a library.
169 /// Note that it returns the raw metadata bytes stored in the library file, whether
170 /// it is compressed, uncompressed, some weird mix, etc.
171 /// rmeta files are backend independent and not handled here.
173 /// At the time of this writing, there is only one backend and one way to store
174 /// metadata in library -- this trait just serves to decouple rustc_metadata from
175 /// the archive reader, which depends on LLVM.
176 pub trait MetadataLoader
{
177 fn get_rlib_metadata(&self, target
: &Target
, filename
: &Path
) -> Result
<MetadataRef
, String
>;
178 fn get_dylib_metadata(&self, target
: &Target
, filename
: &Path
) -> Result
<MetadataRef
, String
>;
181 pub type MetadataLoaderDyn
= dyn MetadataLoader
+ Sync
;
183 /// A store of Rust crates, through which their metadata can be accessed.
185 /// Note that this trait should probably not be expanding today. All new
186 /// functionality should be driven through queries instead!
188 /// If you find a method on this trait named `{name}_untracked` it signifies
189 /// that it's *not* tracked for dependency information throughout compilation
190 /// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
192 pub trait CrateStore
{
193 fn as_any(&self) -> &dyn Any
;
196 fn def_key(&self, def
: DefId
) -> DefKey
;
197 fn def_kind(&self, def
: DefId
) -> DefKind
;
198 fn def_path(&self, def
: DefId
) -> DefPath
;
199 fn def_path_hash(&self, def
: DefId
) -> DefPathHash
;
200 fn def_path_hash_to_def_id(
207 // "queries" used in resolve that aren't tracked for incremental compilation
208 fn crate_name_untracked(&self, cnum
: CrateNum
) -> Symbol
;
209 fn crate_disambiguator_untracked(&self, cnum
: CrateNum
) -> CrateDisambiguator
;
210 fn crate_hash_untracked(&self, cnum
: CrateNum
) -> Svh
;
212 // This is basically a 1-based range of ints, which is a little
213 // silly - I may fix that.
214 fn crates_untracked(&self) -> Vec
<CrateNum
>;
217 fn encode_metadata(&self, tcx
: TyCtxt
<'_
>) -> EncodedMetadata
;
218 fn allocator_kind(&self) -> Option
<AllocatorKind
>;
221 pub type CrateStoreDyn
= dyn CrateStore
+ sync
::Sync
;
223 // This method is used when generating the command line to pass through to
224 // system linker. The linker expects undefined symbols on the left of the
225 // command line to be defined in libraries on the right, not the other way
226 // around. For more info, see some comments in the add_used_library function
229 // In order to get this left-to-right dependency ordering, we perform a
230 // topological sort of all crates putting the leaves at the right-most
232 pub fn used_crates(tcx
: TyCtxt
<'_
>, prefer
: LinkagePreference
) -> Vec
<(CrateNum
, LibSource
)> {
238 if tcx
.dep_kind(cnum
).macros_only() {
241 let source
= tcx
.used_crate_source(cnum
);
242 let path
= match prefer
{
243 LinkagePreference
::RequireDynamic
=> source
.dylib
.clone().map(|p
| p
.0),
244 LinkagePreference
::RequireStatic
=> source
.rlib
.clone().map(|p
| p
.0),
246 let path
= match path
{
247 Some(p
) => LibSource
::Some(p
),
249 if source
.rmeta
.is_some() {
250 LibSource
::MetadataOnly
258 .collect
::<Vec
<_
>>();
259 let mut ordering
= tcx
.postorder_cnums(()).to_owned();
261 libs
.sort_by_cached_key(|&(a
, _
)| ordering
.iter().position(|x
| *x
== a
));