1 //! Validates all used crates and extern libraries and loads their metadata
3 use crate::dynamic_lib::DynamicLibrary;
4 use crate::locator::{CrateError, CrateLocator, CratePaths};
5 use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob};
7 use rustc_ast::expand::allocator::{global_allocator_spans, AllocatorKind};
8 use rustc_ast::{ast, attr};
9 use rustc_data_structures::fx::FxHashSet;
10 use rustc_data_structures::svh::Svh;
11 use rustc_data_structures::sync::Lrc;
12 use rustc_expand::base::SyntaxExtension;
13 use rustc_hir::def_id::{CrateNum, LocalDefId, LOCAL_CRATE};
14 use rustc_hir::definitions::Definitions;
15 use rustc_index::vec::IndexVec;
16 use rustc_middle::middle::cstore::{CrateDepKind, CrateSource, ExternCrate};
17 use rustc_middle::middle::cstore::{ExternCrateSource, MetadataLoaderDyn};
18 use rustc_middle::ty::TyCtxt;
19 use rustc_session::config::{self, CrateType, ExternLocation};
20 use rustc_session::lint;
21 use rustc_session::output::validate_crate_name;
22 use rustc_session::search_paths::PathKind;
23 use rustc_session::{CrateDisambiguator, Session};
24 use rustc_span::edition::Edition;
25 use rustc_span::symbol::{sym, Symbol};
26 use rustc_span::{Span, DUMMY_SP};
27 use rustc_target::spec::{PanicStrategy, TargetTriple};
29 use log::{debug, info};
30 use proc_macro::bridge::client::ProcMacro;
32 use std::{cmp, env, fs};
36 metas: IndexVec<CrateNum, Option<Lrc<CrateMetadata>>>,
37 injected_panic_runtime: Option<CrateNum>,
38 /// This crate needs an allocator and either provides it itself, or finds it in a dependency.
39 /// If the above is true, then this field denotes the kind of the found allocator.
40 allocator_kind: Option<AllocatorKind>,
41 /// This crate has a `#[global_allocator]` item.
42 has_global_allocator: bool,
45 pub struct CrateLoader<'a> {
46 // Immutable configuration.
48 metadata_loader: &'a MetadataLoaderDyn,
49 local_crate_name: Symbol,
52 used_extern_options: FxHashSet<Symbol>,
55 pub enum LoadedMacro {
56 MacroDef(ast::Item, Edition),
57 ProcMacro(SyntaxExtension),
60 crate struct Library {
61 pub source: CrateSource,
62 pub metadata: MetadataBlob,
70 /// A reference to `CrateMetadata` that can also give access to whole crate store when necessary.
71 #[derive(Clone, Copy)]
72 crate struct CrateMetadataRef<'a> {
73 pub cdata: &'a CrateMetadata,
74 pub cstore: &'a CStore,
77 impl std::ops::Deref for CrateMetadataRef<'_> {
78 type Target = CrateMetadata;
80 fn deref(&self) -> &Self::Target {
85 struct CrateDump<'a>(&'a CStore);
87 impl<'a> std::fmt::Debug for CrateDump<'a> {
88 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89 writeln!(fmt, "resolved crates:")?;
90 // `iter_crate_data` does not allow returning values. Thus we use a mutable variable here
91 // that aggregates the value (and any errors that could happen).
93 self.0.iter_crate_data(|cnum, data| {
96 writeln!(fmt, " name: {}", data.name())?;
97 writeln!(fmt, " cnum: {}", cnum)?;
98 writeln!(fmt, " hash: {}", data.hash())?;
99 writeln!(fmt, " reqd: {:?}", data.dep_kind())?;
100 let CrateSource { dylib, rlib, rmeta } = data.source();
101 if let Some(dylib) = dylib {
102 writeln!(fmt, " dylib: {}", dylib.0.display())?;
104 if let Some(rlib) = rlib {
105 writeln!(fmt, " rlib: {}", rlib.0.display())?;
107 if let Some(rmeta) = rmeta {
108 writeln!(fmt, " rmeta: {}", rmeta.0.display())?;
118 crate fn from_tcx(tcx: TyCtxt<'_>) -> &CStore {
119 tcx.cstore_as_any().downcast_ref::<CStore>().expect("`tcx.cstore` is not a `CStore`")
122 fn alloc_new_crate_num(&mut self) -> CrateNum {
123 self.metas.push(None);
124 CrateNum::new(self.metas.len() - 1)
127 crate fn get_crate_data(&self, cnum: CrateNum) -> CrateMetadataRef<'_> {
128 let cdata = self.metas[cnum]
130 .unwrap_or_else(|| panic!("Failed to get crate data for {:?}", cnum));
131 CrateMetadataRef { cdata, cstore: self }
134 fn set_crate_data(&mut self, cnum: CrateNum, data: CrateMetadata) {
135 assert!(self.metas[cnum].is_none(), "Overwriting crate metadata entry");
136 self.metas[cnum] = Some(Lrc::new(data));
139 crate fn iter_crate_data(&self, mut f: impl FnMut(CrateNum, &CrateMetadata)) {
140 for (cnum, data) in self.metas.iter_enumerated() {
141 if let Some(data) = data {
147 fn push_dependencies_in_postorder(&self, deps: &mut Vec<CrateNum>, cnum: CrateNum) {
148 if !deps.contains(&cnum) {
149 let data = self.get_crate_data(cnum);
150 for &dep in data.dependencies().iter() {
152 self.push_dependencies_in_postorder(deps, dep);
160 crate fn crate_dependencies_in_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
161 let mut deps = Vec::new();
162 if cnum == LOCAL_CRATE {
163 self.iter_crate_data(|cnum, _| self.push_dependencies_in_postorder(&mut deps, cnum));
165 self.push_dependencies_in_postorder(&mut deps, cnum);
170 fn crate_dependencies_in_reverse_postorder(&self, cnum: CrateNum) -> Vec<CrateNum> {
171 let mut deps = self.crate_dependencies_in_postorder(cnum);
176 crate fn injected_panic_runtime(&self) -> Option<CrateNum> {
177 self.injected_panic_runtime
180 crate fn allocator_kind(&self) -> Option<AllocatorKind> {
184 crate fn has_global_allocator(&self) -> bool {
185 self.has_global_allocator
189 impl<'a> CrateLoader<'a> {
192 metadata_loader: &'a MetadataLoaderDyn,
193 local_crate_name: &str,
198 local_crate_name: Symbol::intern(local_crate_name),
200 // We add an empty entry for LOCAL_CRATE (which maps to zero) in
201 // order to make array indices in `metas` match with the
202 // corresponding `CrateNum`. This first entry will always remain
204 metas: IndexVec::from_elem_n(None, 1),
205 injected_panic_runtime: None,
206 allocator_kind: None,
207 has_global_allocator: false,
209 used_extern_options: Default::default(),
213 pub fn cstore(&self) -> &CStore {
217 pub fn into_cstore(self) -> CStore {
221 fn existing_match(&self, name: Symbol, hash: Option<Svh>, kind: PathKind) -> Option<CrateNum> {
223 self.cstore.iter_crate_data(|cnum, data| {
224 if data.name() != name {
229 Some(hash) if hash == data.hash() => {
237 // When the hash is None we're dealing with a top-level dependency
238 // in which case we may have a specification on the command line for
239 // this library. Even though an upstream library may have loaded
240 // something of the same name, we have to make sure it was loaded
241 // from the exact same location as well.
243 // We're also sure to compare *paths*, not actual byte slices. The
244 // `source` stores paths which are normalized which may be different
245 // from the strings on the command line.
246 let source = self.cstore.get_crate_data(cnum).cdata.source();
247 if let Some(entry) = self.sess.opts.externs.get(&name.as_str()) {
248 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
249 if let Some(mut files) = entry.files() {
251 let l = fs::canonicalize(l).unwrap_or(l.clone().into());
252 source.dylib.as_ref().map(|p| &p.0) == Some(&l)
253 || source.rlib.as_ref().map(|p| &p.0) == Some(&l)
261 // Alright, so we've gotten this far which means that `data` has the
262 // right name, we don't have a hash, and we don't have a --extern
263 // pointing for ourselves. We're still not quite yet done because we
264 // have to make sure that this crate was found in the crate lookup
265 // path (this is a top-level dependency) as we don't want to
266 // implicitly load anything inside the dependency lookup path.
267 let prev_kind = source
270 .or(source.rlib.as_ref())
271 .or(source.rmeta.as_ref())
272 .expect("No sources for crate")
274 if kind.matches(prev_kind) {
281 fn verify_no_symbol_conflicts(&self, root: &CrateRoot<'_>) -> Result<(), CrateError> {
282 // Check for (potential) conflicts with the local crate
283 if self.local_crate_name == root.name()
284 && self.sess.local_crate_disambiguator() == root.disambiguator()
286 return Err(CrateError::SymbolConflictsCurrent(root.name()));
289 // Check for conflicts with any crate loaded so far
290 let mut res = Ok(());
291 self.cstore.iter_crate_data(|_, other| {
292 if other.name() == root.name() && // same crate-name
293 other.disambiguator() == root.disambiguator() && // same crate-disambiguator
294 other.hash() != root.hash()
297 res = Err(CrateError::SymbolConflictsOthers(root.name()));
306 host_lib: Option<Library>,
307 root: Option<&CratePaths>,
309 dep_kind: CrateDepKind,
311 ) -> Result<CrateNum, CrateError> {
312 let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
314 let Library { source, metadata } = lib;
315 let crate_root = metadata.get_root();
316 let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
317 self.verify_no_symbol_conflicts(&crate_root)?;
320 self.sess.opts.externs.get(&name.as_str()).map(|e| e.is_private_dep).unwrap_or(false);
322 // Claim this crate number and cache it
323 let cnum = self.cstore.alloc_new_crate_num();
326 "register crate `{}` (cnum = {}. private_dep = {})",
332 // Maintain a reference to the top most crate.
333 // Stash paths for top-most crate locally if necessary.
335 let root = if let Some(root) = root {
338 crate_paths = CratePaths::new(crate_root.name(), source.clone());
342 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, dep_kind)?;
344 let raw_proc_macros = if crate_root.is_proc_macro_crate() {
346 let (dlsym_source, dlsym_root) = match &host_lib {
347 Some(host_lib) => (&host_lib.source, {
348 temp_root = host_lib.metadata.get_root();
351 None => (&source, &crate_root),
353 let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
354 Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator())?)
359 let crate_metadata = CrateMetadata::new(
372 self.cstore.set_crate_data(cnum, crate_metadata);
377 fn load_proc_macro<'b>(
379 locator: &mut CrateLocator<'b>,
381 ) -> Result<Option<(LoadResult, Option<Library>)>, CrateError>
385 // Use a new crate locator so trying to load a proc macro doesn't affect the error
387 let mut proc_macro_locator = locator.clone();
389 // Try to load a proc macro
390 proc_macro_locator.is_proc_macro = Some(true);
392 // Load the proc macro crate for the target
393 let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
394 proc_macro_locator.reset();
395 let result = match self.load(&mut proc_macro_locator)? {
396 Some(LoadResult::Previous(cnum)) => {
397 return Ok(Some((LoadResult::Previous(cnum), None)));
399 Some(LoadResult::Loaded(library)) => Some(LoadResult::Loaded(library)),
400 None => return Ok(None),
402 locator.hash = locator.host_hash;
403 // Use the locator when looking for the host proc macro crate, as that is required
404 // so we want it to affect the error message
407 (&mut proc_macro_locator, None)
410 // Load the proc macro crate for the host
413 locator.is_proc_macro = Some(true);
414 locator.target = &self.sess.host;
415 locator.triple = TargetTriple::from_triple(config::host_triple());
416 locator.filesearch = self.sess.host_filesearch(path_kind);
418 let host_result = match self.load(locator)? {
419 Some(host_result) => host_result,
420 None => return Ok(None),
423 Ok(Some(if self.sess.opts.debugging_opts.dual_proc_macros {
424 let host_result = match host_result {
425 LoadResult::Previous(..) => {
426 panic!("host and target proc macros must be loaded in lock-step")
428 LoadResult::Loaded(library) => library,
430 (target_result.unwrap(), Some(host_result))
436 fn resolve_crate<'b>(
440 dep_kind: CrateDepKind,
441 dep: Option<(&'b CratePaths, &'b CrateDep)>,
444 self.used_extern_options.insert(name);
446 self.maybe_resolve_crate(name, dep_kind, dep)
447 .unwrap_or_else(|err| err.report(self.sess, span))
450 fn maybe_resolve_crate<'b>(
453 mut dep_kind: CrateDepKind,
454 dep: Option<(&'b CratePaths, &'b CrateDep)>,
455 ) -> Result<CrateNum, CrateError> {
456 info!("resolving crate `{}`", name);
457 if !name.as_str().is_ascii() {
458 return Err(CrateError::NonAsciiName(name));
460 let (root, hash, host_hash, extra_filename, path_kind) = match dep {
461 Some((root, dep)) => (
465 Some(&dep.extra_filename[..]),
466 PathKind::Dependency,
468 None => (None, None, None, None, PathKind::Crate),
470 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
471 (LoadResult::Previous(cnum), None)
473 info!("falling back to a load");
474 let mut locator = CrateLocator::new(
476 self.metadata_loader,
484 Some(false), // is_proc_macro
487 match self.load(&mut locator)? {
488 Some(res) => (res, None),
490 dep_kind = CrateDepKind::MacrosOnly;
491 match self.load_proc_macro(&mut locator, path_kind)? {
493 None => return Err(locator.into_error()),
500 (LoadResult::Previous(cnum), None) => {
501 let data = self.cstore.get_crate_data(cnum);
502 if data.is_proc_macro_crate() {
503 dep_kind = CrateDepKind::MacrosOnly;
505 data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
508 (LoadResult::Loaded(library), host_library) => {
509 self.register_crate(host_library, root, library, dep_kind, name)
515 fn load(&self, locator: &mut CrateLocator<'_>) -> Result<Option<LoadResult>, CrateError> {
516 let library = match locator.maybe_load_library_crate()? {
517 Some(library) => library,
518 None => return Ok(None),
521 // In the case that we're loading a crate, but not matching
522 // against a hash, we could load a crate which has the same hash
523 // as an already loaded crate. If this is the case prevent
524 // duplicates by just using the first crate.
526 // Note that we only do this for target triple crates, though, as we
527 // don't want to match a host crate against an equivalent target one
529 let root = library.metadata.get_root();
530 Ok(Some(if locator.triple == self.sess.opts.target_triple {
531 let mut result = LoadResult::Loaded(library);
532 self.cstore.iter_crate_data(|cnum, data| {
533 if data.name() == root.name() && root.hash() == data.hash() {
534 assert!(locator.hash.is_none());
535 info!("load success, going to previous cnum: {}", cnum);
536 result = LoadResult::Previous(cnum);
541 LoadResult::Loaded(library)
545 fn update_extern_crate(&self, cnum: CrateNum, extern_crate: ExternCrate) {
546 let cmeta = self.cstore.get_crate_data(cnum);
547 if cmeta.update_extern_crate(extern_crate) {
548 // Propagate the extern crate info to dependencies if it was updated.
549 let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
550 for &dep_cnum in cmeta.dependencies().iter() {
551 self.update_extern_crate(dep_cnum, extern_crate);
556 // Go through the crate metadata and load any crates that it references
557 fn resolve_crate_deps(
560 crate_root: &CrateRoot<'_>,
561 metadata: &MetadataBlob,
563 dep_kind: CrateDepKind,
564 ) -> Result<CrateNumMap, CrateError> {
565 debug!("resolving deps of external crate");
566 if crate_root.is_proc_macro_crate() {
567 return Ok(CrateNumMap::new());
570 // The map from crate numbers in the crate we're resolving to local crate numbers.
571 // We map 0 and all other holes in the map to our parent crate. The "additional"
572 // self-dependencies should be harmless.
573 let deps = crate_root.decode_crate_deps(metadata);
574 let mut crate_num_map = CrateNumMap::with_capacity(1 + deps.len());
575 crate_num_map.push(krate);
578 "resolving dep crate {} hash: `{}` extra filename: `{}`",
579 dep.name, dep.hash, dep.extra_filename
581 let dep_kind = match dep_kind {
582 CrateDepKind::MacrosOnly => CrateDepKind::MacrosOnly,
585 let cnum = self.maybe_resolve_crate(dep.name, dep_kind, Some((root, &dep)))?;
586 crate_num_map.push(cnum);
589 debug!("resolve_crate_deps: cnum_map for {:?} is {:?}", krate, crate_num_map);
593 fn dlsym_proc_macros(
596 disambiguator: CrateDisambiguator,
597 ) -> Result<&'static [ProcMacro], CrateError> {
598 // Make sure the path contains a / or the linker will search for it.
599 let path = env::current_dir().unwrap().join(path);
600 let lib = match DynamicLibrary::open(&path) {
602 Err(s) => return Err(CrateError::DlOpen(s)),
605 let sym = self.sess.generate_proc_macro_decls_symbol(disambiguator);
607 let sym = match lib.symbol(&sym) {
609 Err(s) => return Err(CrateError::DlSym(s)),
611 *(sym as *const &[ProcMacro])
614 // Intentionally leak the dynamic library. We can't ever unload it
615 // since the library can make things that will live arbitrarily long.
616 std::mem::forget(lib);
621 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
622 // If we're only compiling an rlib, then there's no need to select a
623 // panic runtime, so we just skip this section entirely.
624 let any_non_rlib = self.sess.crate_types().iter().any(|ct| *ct != CrateType::Rlib);
626 info!("panic runtime injection skipped, only generating rlib");
630 // If we need a panic runtime, we try to find an existing one here. At
631 // the same time we perform some general validation of the DAG we've got
632 // going such as ensuring everything has a compatible panic strategy.
634 // The logic for finding the panic runtime here is pretty much the same
635 // as the allocator case with the only addition that the panic strategy
636 // compilation mode also comes into play.
637 let desired_strategy = self.sess.panic_strategy();
638 let mut runtime_found = false;
639 let mut needs_panic_runtime = attr::contains_name(&krate.attrs, sym::needs_panic_runtime);
641 self.cstore.iter_crate_data(|cnum, data| {
642 needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
643 if data.is_panic_runtime() {
644 // Inject a dependency from all #![needs_panic_runtime] to this
645 // #![panic_runtime] crate.
646 self.inject_dependency_if(cnum, "a panic runtime", &|data| {
647 data.needs_panic_runtime()
649 runtime_found = runtime_found || data.dep_kind() == CrateDepKind::Explicit;
653 // If an explicitly linked and matching panic runtime was found, or if
654 // we just don't need one at all, then we're done here and there's
655 // nothing else to do.
656 if !needs_panic_runtime || runtime_found {
660 // By this point we know that we (a) need a panic runtime and (b) no
661 // panic runtime was explicitly linked. Here we just load an appropriate
662 // default runtime for our panic strategy and then inject the
665 // We may resolve to an already loaded crate (as the crate may not have
666 // been explicitly linked prior to this) and we may re-inject
667 // dependencies again, but both of those situations are fine.
669 // Also note that we have yet to perform validation of the crate graph
670 // in terms of everyone has a compatible panic runtime format, that's
671 // performed later as part of the `dependency_format` module.
672 let name = match desired_strategy {
673 PanicStrategy::Unwind => sym::panic_unwind,
674 PanicStrategy::Abort => sym::panic_abort,
676 info!("panic runtime not found -- loading {}", name);
678 let cnum = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit, None);
679 let data = self.cstore.get_crate_data(cnum);
681 // Sanity check the loaded crate to ensure it is indeed a panic runtime
682 // and the panic strategy is indeed what we thought it was.
683 if !data.is_panic_runtime() {
684 self.sess.err(&format!("the crate `{}` is not a panic runtime", name));
686 if data.panic_strategy() != desired_strategy {
687 self.sess.err(&format!(
688 "the crate `{}` does not have the panic \
691 desired_strategy.desc()
695 self.cstore.injected_panic_runtime = Some(cnum);
696 self.inject_dependency_if(cnum, "a panic runtime", &|data| data.needs_panic_runtime());
699 fn inject_profiler_runtime(&mut self) {
700 if (self.sess.opts.debugging_opts.instrument_coverage
701 || self.sess.opts.debugging_opts.profile
702 || self.sess.opts.cg.profile_generate.enabled())
703 && !self.sess.opts.debugging_opts.no_profiler_runtime
705 info!("loading profiler");
707 let name = sym::profiler_builtins;
708 let cnum = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit, None);
709 let data = self.cstore.get_crate_data(cnum);
711 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
712 if !data.is_profiler_runtime() {
713 self.sess.err("the crate `profiler_builtins` is not a profiler runtime");
718 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
719 self.cstore.has_global_allocator = match &*global_allocator_spans(krate) {
720 [span1, span2, ..] => {
722 .struct_span_err(*span2, "cannot define multiple global allocators")
723 .span_label(*span2, "cannot define a new global allocator")
724 .span_label(*span1, "previous global allocator defined here")
728 spans => !spans.is_empty(),
731 // Check to see if we actually need an allocator. This desire comes
732 // about through the `#![needs_allocator]` attribute and is typically
733 // written down in liballoc.
734 let mut needs_allocator = attr::contains_name(&krate.attrs, sym::needs_allocator);
735 self.cstore.iter_crate_data(|_, data| {
736 needs_allocator = needs_allocator || data.needs_allocator();
738 if !needs_allocator {
742 // At this point we've determined that we need an allocator. Let's see
743 // if our compilation session actually needs an allocator based on what
745 let all_rlib = self.sess.crate_types().iter().all(|ct| match *ct {
746 CrateType::Rlib => true,
753 // Ok, we need an allocator. Not only that but we're actually going to
754 // create an artifact that needs one linked in. Let's go find the one
755 // that we're going to link in.
757 // First up we check for global allocators. Look at the crate graph here
758 // and see what's a global allocator, including if we ourselves are a
760 let mut global_allocator =
761 self.cstore.has_global_allocator.then(|| Symbol::intern("this crate"));
762 self.cstore.iter_crate_data(|_, data| {
763 if !data.has_global_allocator() {
766 match global_allocator {
767 Some(other_crate) => {
768 self.sess.err(&format!(
769 "the `#[global_allocator]` in {} \
770 conflicts with global \
776 None => global_allocator = Some(data.name()),
779 if global_allocator.is_some() {
780 self.cstore.allocator_kind = Some(AllocatorKind::Global);
784 // Ok we haven't found a global allocator but we still need an
785 // allocator. At this point our allocator request is typically fulfilled
786 // by the standard library, denoted by the `#![default_lib_allocator]`
788 let mut has_default = attr::contains_name(&krate.attrs, sym::default_lib_allocator);
789 self.cstore.iter_crate_data(|_, data| {
790 if data.has_default_lib_allocator() {
797 "no global memory allocator found but one is \
798 required; link to std or \
799 add `#[global_allocator]` to a static item \
800 that implements the GlobalAlloc trait.",
803 self.cstore.allocator_kind = Some(AllocatorKind::Default);
806 fn inject_dependency_if(
810 needs_dep: &dyn Fn(&CrateMetadata) -> bool,
812 // don't perform this validation if the session has errors, as one of
813 // those errors may indicate a circular dependency which could cause
814 // this to stack overflow.
815 if self.sess.has_errors() {
819 // Before we inject any dependencies, make sure we don't inject a
820 // circular dependency by validating that this crate doesn't
821 // transitively depend on any crates satisfying `needs_dep`.
822 for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
823 let data = self.cstore.get_crate_data(dep);
824 if needs_dep(&data) {
825 self.sess.err(&format!(
826 "the crate `{}` cannot depend \
827 on a crate that needs {}, but \
829 self.cstore.get_crate_data(krate).name(),
836 // All crates satisfying `needs_dep` do not explicitly depend on the
837 // crate provided for this compile, but in order for this compilation to
838 // be successfully linked we need to inject a dependency (to order the
839 // crates on the command line correctly).
840 self.cstore.iter_crate_data(|cnum, data| {
841 if !needs_dep(data) {
845 info!("injecting a dep from {} to {}", cnum, krate);
846 data.add_dependency(krate);
850 fn report_unused_deps(&mut self, krate: &ast::Crate) {
851 // Make a point span rather than covering the whole file
852 let span = krate.span.shrink_to_lo();
853 // Complain about anything left over
854 for (name, entry) in self.sess.opts.externs.iter() {
855 if let ExternLocation::FoundInLibrarySearchDirectories = entry.location {
856 // Don't worry about pathless `--extern foo` sysroot references
859 if !self.used_extern_options.contains(&Symbol::intern(name)) {
860 self.sess.parse_sess.buffer_lint(
861 lint::builtin::UNUSED_CRATE_DEPENDENCIES,
865 "external crate `{}` unused in `{}`: remove the dependency or add `use {} as _;`",
867 self.local_crate_name,
874 pub fn postprocess(&mut self, krate: &ast::Crate) {
875 self.inject_profiler_runtime();
876 self.inject_allocator_crate(krate);
877 self.inject_panic_runtime(krate);
879 info!("{:?}", CrateDump(&self.cstore));
881 self.report_unused_deps(krate);
884 pub fn process_extern_crate(
887 definitions: &Definitions,
891 ast::ItemKind::ExternCrate(orig_name) => {
893 "resolving extern crate stmt. ident: {} orig_name: {:?}",
894 item.ident, orig_name
896 let name = match orig_name {
898 validate_crate_name(Some(self.sess), &orig_name.as_str(), Some(item.span));
901 None => item.ident.name,
903 let dep_kind = if attr::contains_name(&item.attrs, sym::no_link) {
904 CrateDepKind::MacrosOnly
906 CrateDepKind::Explicit
909 let cnum = self.resolve_crate(name, item.span, dep_kind, None);
911 let path_len = definitions.def_path(def_id).data.len();
912 self.update_extern_crate(
915 src: ExternCrateSource::Extern(def_id.to_def_id()),
918 dependency_of: LOCAL_CRATE,
927 pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> CrateNum {
928 let cnum = self.resolve_crate(name, span, CrateDepKind::Explicit, None);
930 self.update_extern_crate(
933 src: ExternCrateSource::Path,
935 // to have the least priority in `update_extern_crate`
936 path_len: usize::MAX,
937 dependency_of: LOCAL_CRATE,
944 pub fn maybe_process_path_extern(&mut self, name: Symbol) -> Option<CrateNum> {
945 self.maybe_resolve_crate(name, CrateDepKind::Explicit, None).ok()