1 //! Validity checking for weak lang items
3 use rustc_data_structures::fx::FxHashSet;
4 use rustc_errors::struct_span_err;
5 use rustc_hir::lang_items::{self, LangItem};
6 use rustc_hir::weak_lang_items::WEAK_ITEMS_REFS;
7 use rustc_middle::middle::lang_items::required;
8 use rustc_middle::ty::TyCtxt;
9 use rustc_session::config::CrateType;
11 /// Checks the crate for usage of weak lang items, returning a vector of all the
12 /// language items required by this crate, but not defined yet.
13 pub fn check_crate<'tcx>(tcx: TyCtxt<'tcx>, items: &mut lang_items::LanguageItems) {
14 // These are never called by user code, they're generated by the compiler.
15 // They will never implicitly be added to the `missing` array unless we do
17 if items.eh_personality().is_none() {
18 items.missing.push(LangItem::EhPersonality);
20 if tcx.sess.target.os == "emscripten" && items.eh_catch_typeinfo().is_none() {
21 items.missing.push(LangItem::EhCatchTypeinfo);
24 let crate_items = tcx.hir_crate_items(());
25 for id in crate_items.foreign_items() {
26 let attrs = tcx.hir().attrs(id.hir_id());
27 if let Some((lang_item, _)) = lang_items::extract(attrs) {
28 if let Some(&item) = WEAK_ITEMS_REFS.get(&lang_item) {
29 if items.require(item).is_err() {
30 items.missing.push(item);
33 let span = tcx.def_span(id.def_id);
38 "unknown external lang item: `{}`",
49 fn verify<'tcx>(tcx: TyCtxt<'tcx>, items: &lang_items::LanguageItems) {
50 // We only need to check for the presence of weak lang items if we're
51 // emitting something that's not an rlib.
52 let needs_check = tcx.sess.crate_types().iter().any(|kind| match *kind {
54 | CrateType::ProcMacro
56 | CrateType::Executable
57 | CrateType::Staticlib => true,
58 CrateType::Rlib => false,
64 let mut missing = FxHashSet::default();
65 for &cnum in tcx.crates(()).iter() {
66 for &item in tcx.missing_lang_items(cnum).iter() {
71 for (name, &item) in WEAK_ITEMS_REFS.iter() {
72 if missing.contains(&item) && required(tcx, item) && items.require(item).is_err() {
73 if item == LangItem::PanicImpl {
74 tcx.sess.err("`#[panic_handler]` function required, but not found");
75 } else if item == LangItem::Oom {
76 if !tcx.features().default_alloc_error_handler {
77 tcx.sess.err("`#[alloc_error_handler]` function required, but not found");
78 tcx.sess.note_without_error("use `#![feature(default_alloc_error_handler)]` for a default error handler");
84 .struct_err(&format!("language item required, but not found: `{}`", name))
85 .note(&format!("this can occur when a binary crate with `#![no_std]` is compiled for a target where `{}` is defined in the standard library", name))
86 .help(&format!("you may be able to compile for a target that doesn't need `{}`, specify a target with `--target` or in `.cargo/config`", name))