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::AllocatorKind;
8 use rustc_ast::{self as ast, *};
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 proc_macro::bridge::client::ProcMacro;
32 use tracing::{debug, info};
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 {
225 tracing::trace!("{} did not match {}", data.name(), name);
230 Some(hash) if hash == data.hash() => {
235 debug!("actual hash {} did not match expected {}", hash, data.hash());
241 // When the hash is None we're dealing with a top-level dependency
242 // in which case we may have a specification on the command line for
243 // this library. Even though an upstream library may have loaded
244 // something of the same name, we have to make sure it was loaded
245 // from the exact same location as well.
247 // We're also sure to compare *paths*, not actual byte slices. The
248 // `source` stores paths which are normalized which may be different
249 // from the strings on the command line.
250 let source = self.cstore.get_crate_data(cnum).cdata.source();
251 if let Some(entry) = self.sess.opts.externs.get(&name.as_str()) {
252 // Only use `--extern crate_name=path` here, not `--extern crate_name`.
253 if let Some(mut files) = entry.files() {
255 let l = l.canonicalized();
256 source.dylib.as_ref().map(|(p, _)| p) == Some(l)
257 || source.rlib.as_ref().map(|(p, _)| p) == Some(l)
258 || source.rmeta.as_ref().map(|(p, _)| p) == Some(l)
266 // Alright, so we've gotten this far which means that `data` has the
267 // right name, we don't have a hash, and we don't have a --extern
268 // pointing for ourselves. We're still not quite yet done because we
269 // have to make sure that this crate was found in the crate lookup
270 // path (this is a top-level dependency) as we don't want to
271 // implicitly load anything inside the dependency lookup path.
272 let prev_kind = source
275 .or(source.rlib.as_ref())
276 .or(source.rmeta.as_ref())
277 .expect("No sources for crate")
279 if kind.matches(prev_kind) {
283 "failed to load existing crate {}; kind {:?} did not match prev_kind {:?}",
284 name, kind, prev_kind
291 fn verify_no_symbol_conflicts(&self, root: &CrateRoot<'_>) -> Result<(), CrateError> {
292 // Check for (potential) conflicts with the local crate
293 if self.local_crate_name == root.name()
294 && self.sess.local_crate_disambiguator() == root.disambiguator()
296 return Err(CrateError::SymbolConflictsCurrent(root.name()));
299 // Check for conflicts with any crate loaded so far
300 let mut res = Ok(());
301 self.cstore.iter_crate_data(|_, other| {
302 if other.name() == root.name() && // same crate-name
303 other.disambiguator() == root.disambiguator() && // same crate-disambiguator
304 other.hash() != root.hash()
307 res = Err(CrateError::SymbolConflictsOthers(root.name()));
316 host_lib: Option<Library>,
317 root: Option<&CratePaths>,
319 dep_kind: CrateDepKind,
321 ) -> Result<CrateNum, CrateError> {
322 let _prof_timer = self.sess.prof.generic_activity("metadata_register_crate");
324 let Library { source, metadata } = lib;
325 let crate_root = metadata.get_root();
326 let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash());
327 self.verify_no_symbol_conflicts(&crate_root)?;
330 self.sess.opts.externs.get(&name.as_str()).map_or(false, |e| e.is_private_dep);
332 // Claim this crate number and cache it
333 let cnum = self.cstore.alloc_new_crate_num();
336 "register crate `{}` (cnum = {}. private_dep = {})",
342 // Maintain a reference to the top most crate.
343 // Stash paths for top-most crate locally if necessary.
345 let root = if let Some(root) = root {
348 crate_paths = CratePaths::new(crate_root.name(), source.clone());
352 let cnum_map = self.resolve_crate_deps(root, &crate_root, &metadata, cnum, dep_kind)?;
354 let raw_proc_macros = if crate_root.is_proc_macro_crate() {
356 let (dlsym_source, dlsym_root) = match &host_lib {
357 Some(host_lib) => (&host_lib.source, {
358 temp_root = host_lib.metadata.get_root();
361 None => (&source, &crate_root),
363 let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate");
364 Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.disambiguator())?)
369 let crate_metadata = CrateMetadata::new(
382 self.cstore.set_crate_data(cnum, crate_metadata);
387 fn load_proc_macro<'b>(
389 locator: &mut CrateLocator<'b>,
391 ) -> Result<Option<(LoadResult, Option<Library>)>, CrateError>
395 // Use a new crate locator so trying to load a proc macro doesn't affect the error
397 let mut proc_macro_locator = locator.clone();
399 // Try to load a proc macro
400 proc_macro_locator.is_proc_macro = Some(true);
402 // Load the proc macro crate for the target
403 let (locator, target_result) = if self.sess.opts.debugging_opts.dual_proc_macros {
404 proc_macro_locator.reset();
405 let result = match self.load(&mut proc_macro_locator)? {
406 Some(LoadResult::Previous(cnum)) => {
407 return Ok(Some((LoadResult::Previous(cnum), None)));
409 Some(LoadResult::Loaded(library)) => Some(LoadResult::Loaded(library)),
410 None => return Ok(None),
412 locator.hash = locator.host_hash;
413 // Use the locator when looking for the host proc macro crate, as that is required
414 // so we want it to affect the error message
417 (&mut proc_macro_locator, None)
420 // Load the proc macro crate for the host
423 locator.is_proc_macro = Some(true);
424 locator.target = &self.sess.host;
425 locator.triple = TargetTriple::from_triple(config::host_triple());
426 locator.filesearch = self.sess.host_filesearch(path_kind);
428 let host_result = match self.load(locator)? {
429 Some(host_result) => host_result,
430 None => return Ok(None),
433 Ok(Some(if self.sess.opts.debugging_opts.dual_proc_macros {
434 let host_result = match host_result {
435 LoadResult::Previous(..) => {
436 panic!("host and target proc macros must be loaded in lock-step")
438 LoadResult::Loaded(library) => library,
440 (target_result.unwrap(), Some(host_result))
446 fn resolve_crate<'b>(
450 dep_kind: CrateDepKind,
451 dep: Option<(&'b CratePaths, &'b CrateDep)>,
454 self.used_extern_options.insert(name);
456 self.maybe_resolve_crate(name, dep_kind, dep)
457 .unwrap_or_else(|err| err.report(self.sess, span))
460 fn maybe_resolve_crate<'b>(
463 mut dep_kind: CrateDepKind,
464 dep: Option<(&'b CratePaths, &'b CrateDep)>,
465 ) -> Result<CrateNum, CrateError> {
466 info!("resolving crate `{}`", name);
467 if !name.as_str().is_ascii() {
468 return Err(CrateError::NonAsciiName(name));
470 let (root, hash, host_hash, extra_filename, path_kind) = match dep {
471 Some((root, dep)) => (
475 Some(&dep.extra_filename[..]),
476 PathKind::Dependency,
478 None => (None, None, None, None, PathKind::Crate),
480 let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) {
481 (LoadResult::Previous(cnum), None)
483 info!("falling back to a load");
484 let mut locator = CrateLocator::new(
486 self.metadata_loader,
494 Some(false), // is_proc_macro
497 match self.load(&mut locator)? {
498 Some(res) => (res, None),
500 dep_kind = CrateDepKind::MacrosOnly;
501 match self.load_proc_macro(&mut locator, path_kind)? {
503 None => return Err(locator.into_error()),
510 (LoadResult::Previous(cnum), None) => {
511 let data = self.cstore.get_crate_data(cnum);
512 if data.is_proc_macro_crate() {
513 dep_kind = CrateDepKind::MacrosOnly;
515 data.update_dep_kind(|data_dep_kind| cmp::max(data_dep_kind, dep_kind));
518 (LoadResult::Loaded(library), host_library) => {
519 self.register_crate(host_library, root, library, dep_kind, name)
525 fn load(&self, locator: &mut CrateLocator<'_>) -> Result<Option<LoadResult>, CrateError> {
526 let library = match locator.maybe_load_library_crate()? {
527 Some(library) => library,
528 None => return Ok(None),
531 // In the case that we're loading a crate, but not matching
532 // against a hash, we could load a crate which has the same hash
533 // as an already loaded crate. If this is the case prevent
534 // duplicates by just using the first crate.
536 // Note that we only do this for target triple crates, though, as we
537 // don't want to match a host crate against an equivalent target one
539 let root = library.metadata.get_root();
540 Ok(Some(if locator.triple == self.sess.opts.target_triple {
541 let mut result = LoadResult::Loaded(library);
542 self.cstore.iter_crate_data(|cnum, data| {
543 if data.name() == root.name() && root.hash() == data.hash() {
544 assert!(locator.hash.is_none());
545 info!("load success, going to previous cnum: {}", cnum);
546 result = LoadResult::Previous(cnum);
551 LoadResult::Loaded(library)
555 fn update_extern_crate(&self, cnum: CrateNum, extern_crate: ExternCrate) {
556 let cmeta = self.cstore.get_crate_data(cnum);
557 if cmeta.update_extern_crate(extern_crate) {
558 // Propagate the extern crate info to dependencies if it was updated.
559 let extern_crate = ExternCrate { dependency_of: cnum, ..extern_crate };
560 for &dep_cnum in cmeta.dependencies().iter() {
561 self.update_extern_crate(dep_cnum, extern_crate);
566 // Go through the crate metadata and load any crates that it references
567 fn resolve_crate_deps(
570 crate_root: &CrateRoot<'_>,
571 metadata: &MetadataBlob,
573 dep_kind: CrateDepKind,
574 ) -> Result<CrateNumMap, CrateError> {
575 debug!("resolving deps of external crate");
576 if crate_root.is_proc_macro_crate() {
577 return Ok(CrateNumMap::new());
580 // The map from crate numbers in the crate we're resolving to local crate numbers.
581 // We map 0 and all other holes in the map to our parent crate. The "additional"
582 // self-dependencies should be harmless.
583 let deps = crate_root.decode_crate_deps(metadata);
584 let mut crate_num_map = CrateNumMap::with_capacity(1 + deps.len());
585 crate_num_map.push(krate);
588 "resolving dep crate {} hash: `{}` extra filename: `{}`",
589 dep.name, dep.hash, dep.extra_filename
591 let dep_kind = match dep_kind {
592 CrateDepKind::MacrosOnly => CrateDepKind::MacrosOnly,
595 let cnum = self.maybe_resolve_crate(dep.name, dep_kind, Some((root, &dep)))?;
596 crate_num_map.push(cnum);
599 debug!("resolve_crate_deps: cnum_map for {:?} is {:?}", krate, crate_num_map);
603 fn dlsym_proc_macros(
606 disambiguator: CrateDisambiguator,
607 ) -> Result<&'static [ProcMacro], CrateError> {
608 // Make sure the path contains a / or the linker will search for it.
609 let path = env::current_dir().unwrap().join(path);
610 let lib = match DynamicLibrary::open(&path) {
612 Err(s) => return Err(CrateError::DlOpen(s)),
615 let sym = self.sess.generate_proc_macro_decls_symbol(disambiguator);
617 let sym = match lib.symbol(&sym) {
619 Err(s) => return Err(CrateError::DlSym(s)),
621 *(sym as *const &[ProcMacro])
624 // Intentionally leak the dynamic library. We can't ever unload it
625 // since the library can make things that will live arbitrarily long.
626 std::mem::forget(lib);
631 fn inject_panic_runtime(&mut self, krate: &ast::Crate) {
632 // If we're only compiling an rlib, then there's no need to select a
633 // panic runtime, so we just skip this section entirely.
634 let any_non_rlib = self.sess.crate_types().iter().any(|ct| *ct != CrateType::Rlib);
636 info!("panic runtime injection skipped, only generating rlib");
640 // If we need a panic runtime, we try to find an existing one here. At
641 // the same time we perform some general validation of the DAG we've got
642 // going such as ensuring everything has a compatible panic strategy.
644 // The logic for finding the panic runtime here is pretty much the same
645 // as the allocator case with the only addition that the panic strategy
646 // compilation mode also comes into play.
647 let desired_strategy = self.sess.panic_strategy();
648 let mut runtime_found = false;
649 let mut needs_panic_runtime =
650 self.sess.contains_name(&krate.attrs, sym::needs_panic_runtime);
652 self.cstore.iter_crate_data(|cnum, data| {
653 needs_panic_runtime = needs_panic_runtime || data.needs_panic_runtime();
654 if data.is_panic_runtime() {
655 // Inject a dependency from all #![needs_panic_runtime] to this
656 // #![panic_runtime] crate.
657 self.inject_dependency_if(cnum, "a panic runtime", &|data| {
658 data.needs_panic_runtime()
660 runtime_found = runtime_found || data.dep_kind() == CrateDepKind::Explicit;
664 // If an explicitly linked and matching panic runtime was found, or if
665 // we just don't need one at all, then we're done here and there's
666 // nothing else to do.
667 if !needs_panic_runtime || runtime_found {
671 // By this point we know that we (a) need a panic runtime and (b) no
672 // panic runtime was explicitly linked. Here we just load an appropriate
673 // default runtime for our panic strategy and then inject the
676 // We may resolve to an already loaded crate (as the crate may not have
677 // been explicitly linked prior to this) and we may re-inject
678 // dependencies again, but both of those situations are fine.
680 // Also note that we have yet to perform validation of the crate graph
681 // in terms of everyone has a compatible panic runtime format, that's
682 // performed later as part of the `dependency_format` module.
683 let name = match desired_strategy {
684 PanicStrategy::Unwind => sym::panic_unwind,
685 PanicStrategy::Abort => sym::panic_abort,
687 info!("panic runtime not found -- loading {}", name);
689 let cnum = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit, None);
690 let data = self.cstore.get_crate_data(cnum);
692 // Sanity check the loaded crate to ensure it is indeed a panic runtime
693 // and the panic strategy is indeed what we thought it was.
694 if !data.is_panic_runtime() {
695 self.sess.err(&format!("the crate `{}` is not a panic runtime", name));
697 if data.panic_strategy() != desired_strategy {
698 self.sess.err(&format!(
699 "the crate `{}` does not have the panic \
702 desired_strategy.desc()
706 self.cstore.injected_panic_runtime = Some(cnum);
707 self.inject_dependency_if(cnum, "a panic runtime", &|data| data.needs_panic_runtime());
710 fn inject_profiler_runtime(&mut self, krate: &ast::Crate) {
711 if (self.sess.opts.debugging_opts.instrument_coverage
712 || self.sess.opts.debugging_opts.profile
713 || self.sess.opts.cg.profile_generate.enabled())
714 && !self.sess.opts.debugging_opts.no_profiler_runtime
716 info!("loading profiler");
718 if self.sess.contains_name(&krate.attrs, sym::no_core) {
720 "`profiler_builtins` crate (required by compiler options) \
721 is not compatible with crate attribute `#![no_core]`",
725 let name = sym::profiler_builtins;
726 let cnum = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit, None);
727 let data = self.cstore.get_crate_data(cnum);
729 // Sanity check the loaded crate to ensure it is indeed a profiler runtime
730 if !data.is_profiler_runtime() {
731 self.sess.err("the crate `profiler_builtins` is not a profiler runtime");
736 fn inject_allocator_crate(&mut self, krate: &ast::Crate) {
737 self.cstore.has_global_allocator = match &*global_allocator_spans(&self.sess, krate) {
738 [span1, span2, ..] => {
740 .struct_span_err(*span2, "cannot define multiple global allocators")
741 .span_label(*span2, "cannot define a new global allocator")
742 .span_label(*span1, "previous global allocator defined here")
746 spans => !spans.is_empty(),
749 // Check to see if we actually need an allocator. This desire comes
750 // about through the `#![needs_allocator]` attribute and is typically
751 // written down in liballoc.
752 let mut needs_allocator = self.sess.contains_name(&krate.attrs, sym::needs_allocator);
753 self.cstore.iter_crate_data(|_, data| {
754 needs_allocator = needs_allocator || data.needs_allocator();
756 if !needs_allocator {
760 // At this point we've determined that we need an allocator. Let's see
761 // if our compilation session actually needs an allocator based on what
763 let all_rlib = self.sess.crate_types().iter().all(|ct| matches!(*ct, CrateType::Rlib));
768 // Ok, we need an allocator. Not only that but we're actually going to
769 // create an artifact that needs one linked in. Let's go find the one
770 // that we're going to link in.
772 // First up we check for global allocators. Look at the crate graph here
773 // and see what's a global allocator, including if we ourselves are a
775 let mut global_allocator =
776 self.cstore.has_global_allocator.then(|| Symbol::intern("this crate"));
777 self.cstore.iter_crate_data(|_, data| {
778 if !data.has_global_allocator() {
781 match global_allocator {
782 Some(other_crate) => {
783 self.sess.err(&format!(
784 "the `#[global_allocator]` in {} \
785 conflicts with global \
791 None => global_allocator = Some(data.name()),
794 if global_allocator.is_some() {
795 self.cstore.allocator_kind = Some(AllocatorKind::Global);
799 // Ok we haven't found a global allocator but we still need an
800 // allocator. At this point our allocator request is typically fulfilled
801 // by the standard library, denoted by the `#![default_lib_allocator]`
803 let mut has_default = self.sess.contains_name(&krate.attrs, sym::default_lib_allocator);
804 self.cstore.iter_crate_data(|_, data| {
805 if data.has_default_lib_allocator() {
812 "no global memory allocator found but one is \
813 required; link to std or \
814 add `#[global_allocator]` to a static item \
815 that implements the GlobalAlloc trait.",
818 self.cstore.allocator_kind = Some(AllocatorKind::Default);
821 fn inject_dependency_if(
825 needs_dep: &dyn Fn(&CrateMetadata) -> bool,
827 // don't perform this validation if the session has errors, as one of
828 // those errors may indicate a circular dependency which could cause
829 // this to stack overflow.
830 if self.sess.has_errors() {
834 // Before we inject any dependencies, make sure we don't inject a
835 // circular dependency by validating that this crate doesn't
836 // transitively depend on any crates satisfying `needs_dep`.
837 for dep in self.cstore.crate_dependencies_in_reverse_postorder(krate) {
838 let data = self.cstore.get_crate_data(dep);
839 if needs_dep(&data) {
840 self.sess.err(&format!(
841 "the crate `{}` cannot depend \
842 on a crate that needs {}, but \
844 self.cstore.get_crate_data(krate).name(),
851 // All crates satisfying `needs_dep` do not explicitly depend on the
852 // crate provided for this compile, but in order for this compilation to
853 // be successfully linked we need to inject a dependency (to order the
854 // crates on the command line correctly).
855 self.cstore.iter_crate_data(|cnum, data| {
856 if !needs_dep(data) {
860 info!("injecting a dep from {} to {}", cnum, krate);
861 data.add_dependency(krate);
865 fn report_unused_deps(&mut self, krate: &ast::Crate) {
866 // Make a point span rather than covering the whole file
867 let span = krate.span.shrink_to_lo();
868 // Complain about anything left over
869 for (name, entry) in self.sess.opts.externs.iter() {
870 if let ExternLocation::FoundInLibrarySearchDirectories = entry.location {
871 // Don't worry about pathless `--extern foo` sysroot references
874 if !self.used_extern_options.contains(&Symbol::intern(name)) {
875 self.sess.parse_sess.buffer_lint(
876 lint::builtin::UNUSED_CRATE_DEPENDENCIES,
880 "external crate `{}` unused in `{}`: remove the dependency or add `use {} as _;`",
882 self.local_crate_name,
889 pub fn postprocess(&mut self, krate: &ast::Crate) {
890 self.inject_profiler_runtime(krate);
891 self.inject_allocator_crate(krate);
892 self.inject_panic_runtime(krate);
894 info!("{:?}", CrateDump(&self.cstore));
896 self.report_unused_deps(krate);
899 pub fn process_extern_crate(
902 definitions: &Definitions,
906 ast::ItemKind::ExternCrate(orig_name) => {
908 "resolving extern crate stmt. ident: {} orig_name: {:?}",
909 item.ident, orig_name
911 let name = match orig_name {
913 validate_crate_name(self.sess, &orig_name.as_str(), Some(item.span));
916 None => item.ident.name,
918 let dep_kind = if self.sess.contains_name(&item.attrs, sym::no_link) {
919 CrateDepKind::MacrosOnly
921 CrateDepKind::Explicit
924 let cnum = self.resolve_crate(name, item.span, dep_kind, None);
926 let path_len = definitions.def_path(def_id).data.len();
927 self.update_extern_crate(
930 src: ExternCrateSource::Extern(def_id.to_def_id()),
933 dependency_of: LOCAL_CRATE,
942 pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> CrateNum {
943 let cnum = self.resolve_crate(name, span, CrateDepKind::Explicit, None);
945 self.update_extern_crate(
948 src: ExternCrateSource::Path,
950 // to have the least priority in `update_extern_crate`
951 path_len: usize::MAX,
952 dependency_of: LOCAL_CRATE,
959 pub fn maybe_process_path_extern(&mut self, name: Symbol) -> Option<CrateNum> {
960 self.maybe_resolve_crate(name, CrateDepKind::Explicit, None).ok()
964 fn global_allocator_spans(sess: &Session, krate: &ast::Crate) -> Vec<Span> {
970 impl<'ast, 'a> visit::Visitor<'ast> for Finder<'a> {
971 fn visit_item(&mut self, item: &'ast ast::Item) {
972 if item.ident.name == self.name
973 && self.sess.contains_name(&item.attrs, sym::rustc_std_internal_symbol)
975 self.spans.push(item.span);
977 visit::walk_item(self, item)
981 let name = Symbol::intern(&AllocatorKind::Global.fn_name(sym::alloc));
982 let mut f = Finder { sess, name, spans: Vec::new() };
983 visit::walk_crate(&mut f, krate);