]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/weak_lang_items.rs
Auto merge of #62040 - felixrabe:patch-3, r=dtolnay
[rust.git] / src / librustc / middle / weak_lang_items.rs
1 //! Validity checking for weak lang items
2
3 use crate::session::config;
4 use crate::middle::lang_items;
5
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_target::spec::PanicStrategy;
8 use syntax::ast;
9 use syntax::symbol::{Symbol, sym};
10 use syntax_pos::Span;
11 use crate::hir::def_id::DefId;
12 use crate::hir::intravisit::{Visitor, NestedVisitorMap};
13 use crate::hir::intravisit;
14 use crate::hir;
15 use crate::ty::TyCtxt;
16
17 macro_rules! weak_lang_items {
18     ($($name:ident, $item:ident, $sym:ident;)*) => (
19
20 struct Context<'a, 'tcx> {
21     tcx: TyCtxt<'tcx>,
22     items: &'a mut lang_items::LanguageItems,
23 }
24
25 /// Checks the crate for usage of weak lang items, returning a vector of all the
26 /// language items required by this crate, but not defined yet.
27 pub fn check_crate<'tcx>(tcx: TyCtxt<'tcx>,
28                              items: &mut lang_items::LanguageItems) {
29     // These are never called by user code, they're generated by the compiler.
30     // They will never implicitly be added to the `missing` array unless we do
31     // so here.
32     if items.eh_personality().is_none() {
33         items.missing.push(lang_items::EhPersonalityLangItem);
34     }
35     if tcx.sess.target.target.options.custom_unwind_resume &
36        items.eh_unwind_resume().is_none() {
37         items.missing.push(lang_items::EhUnwindResumeLangItem);
38     }
39
40     {
41         let mut cx = Context { tcx, items };
42         tcx.hir().krate().visit_all_item_likes(&mut cx.as_deep_visitor());
43     }
44     verify(tcx, items);
45 }
46
47 pub fn link_name(attrs: &[ast::Attribute]) -> Option<Symbol> {
48     lang_items::extract(attrs).and_then(|(name, _)| {
49         $(if name == sym::$name {
50             Some(sym::$sym)
51         } else)* {
52             None
53         }
54     })
55 }
56
57 /// Returns `true` if the specified `lang_item` doesn't actually need to be
58 /// present for this compilation.
59 ///
60 /// Not all lang items are always required for each compilation, particularly in
61 /// the case of panic=abort. In these situations some lang items are injected by
62 /// crates and don't actually need to be defined in libstd.
63 pub fn whitelisted(tcx: TyCtxt<'_>, lang_item: lang_items::LangItem) -> bool {
64     // If we're not compiling with unwinding, we won't actually need these
65     // symbols. Other panic runtimes ensure that the relevant symbols are
66     // available to link things together, but they're never exercised.
67     if tcx.sess.panic_strategy() != PanicStrategy::Unwind {
68         return lang_item == lang_items::EhPersonalityLangItem ||
69             lang_item == lang_items::EhUnwindResumeLangItem
70     }
71
72     false
73 }
74
75 fn verify<'tcx>(tcx: TyCtxt<'tcx>,
76                     items: &lang_items::LanguageItems) {
77     // We only need to check for the presence of weak lang items if we're
78     // emitting something that's not an rlib.
79     let needs_check = tcx.sess.crate_types.borrow().iter().any(|kind| {
80         match *kind {
81             config::CrateType::Dylib |
82             config::CrateType::ProcMacro |
83             config::CrateType::Cdylib |
84             config::CrateType::Executable |
85             config::CrateType::Staticlib => true,
86             config::CrateType::Rlib => false,
87         }
88     });
89     if !needs_check {
90         return
91     }
92
93     let mut missing = FxHashSet::default();
94     for &cnum in tcx.crates().iter() {
95         for &item in tcx.missing_lang_items(cnum).iter() {
96             missing.insert(item);
97         }
98     }
99
100     $(
101         if missing.contains(&lang_items::$item) &&
102            !whitelisted(tcx, lang_items::$item) &&
103            items.$name().is_none() {
104             if lang_items::$item == lang_items::PanicImplLangItem {
105                 tcx.sess.err(&format!("`#[panic_handler]` function required, \
106                                        but not found"));
107             } else if lang_items::$item == lang_items::OomLangItem {
108                 tcx.sess.err(&format!("`#[alloc_error_handler]` function required, \
109                                        but not found"));
110             } else {
111                 tcx.sess.err(&format!("language item required, but not found: `{}`",
112                                       stringify!($name)));
113             }
114         }
115     )*
116 }
117
118 impl<'a, 'tcx> Context<'a, 'tcx> {
119     fn register(&mut self, name: &str, span: Span) {
120         $(if name == stringify!($name) {
121             if self.items.$name().is_none() {
122                 self.items.missing.push(lang_items::$item);
123             }
124         } else)* {
125             span_err!(self.tcx.sess, span, E0264,
126                       "unknown external lang item: `{}`",
127                       name);
128         }
129     }
130 }
131
132 impl<'a, 'tcx, 'v> Visitor<'v> for Context<'a, 'tcx> {
133     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
134         NestedVisitorMap::None
135     }
136
137     fn visit_foreign_item(&mut self, i: &hir::ForeignItem) {
138         if let Some((lang_item, _)) = lang_items::extract(&i.attrs) {
139             self.register(&lang_item.as_str(), i.span);
140         }
141         intravisit::walk_foreign_item(self, i)
142     }
143 }
144
145 impl<'tcx> TyCtxt<'tcx> {
146     pub fn is_weak_lang_item(&self, item_def_id: DefId) -> bool {
147         let lang_items = self.lang_items();
148         let did = Some(item_def_id);
149
150         $(lang_items.$name() == did)||+
151     }
152 }
153
154 ) }
155
156 weak_lang_items! {
157     panic_impl,         PanicImplLangItem,          rust_begin_unwind;
158     eh_personality,     EhPersonalityLangItem,      rust_eh_personality;
159     eh_unwind_resume,   EhUnwindResumeLangItem,     rust_eh_unwind_resume;
160     oom,                OomLangItem,                rust_oom;
161 }