1 //! Detecting language items.
3 //! Language items are items that represent concepts intrinsic to the language
4 //! itself. Examples are:
6 //! * Traits that specify "kinds"; e.g., `Sync`, `Send`.
7 //! * Traits that represent operators; e.g., `Add`, `Sub`, `Index`.
8 //! * Functions called by the compiler itself.
10 use crate::check_attr::target_from_impl_item;
11 use crate::weak_lang_items;
13 use rustc_middle::middle::cstore::ExternCrate;
14 use rustc_middle::ty::TyCtxt;
16 use rustc_ast::Attribute;
17 use rustc_errors::{pluralize, struct_span_err};
19 use rustc_hir::def_id::DefId;
20 use rustc_hir::itemlikevisit::ItemLikeVisitor;
21 use rustc_hir::lang_items::{extract, GenericRequirement, ITEM_REFS};
22 use rustc_hir::{HirId, LangItem, LanguageItems, Target};
25 use rustc_middle::ty::query::Providers;
27 struct LanguageItemCollector<'tcx> {
32 impl ItemLikeVisitor<'v> for LanguageItemCollector<'tcx> {
33 fn visit_item(&mut self, item: &hir::Item<'_>) {
34 self.check_for_lang(Target::from_item(item), item.hir_id());
36 if let hir::ItemKind::Enum(def, ..) = &item.kind {
37 for variant in def.variants {
38 self.check_for_lang(Target::Variant, variant.id);
43 fn visit_trait_item(&mut self, trait_item: &hir::TraitItem<'_>) {
44 self.check_for_lang(Target::from_trait_item(trait_item), trait_item.hir_id())
47 fn visit_impl_item(&mut self, impl_item: &hir::ImplItem<'_>) {
48 self.check_for_lang(target_from_impl_item(self.tcx, impl_item), impl_item.hir_id())
51 fn visit_foreign_item(&mut self, _: &hir::ForeignItem<'_>) {}
54 impl LanguageItemCollector<'tcx> {
55 fn new(tcx: TyCtxt<'tcx>) -> LanguageItemCollector<'tcx> {
56 LanguageItemCollector { tcx, items: LanguageItems::new() }
59 fn check_for_lang(&mut self, actual_target: Target, hir_id: HirId) {
60 let attrs = self.tcx.hir().attrs(hir_id);
61 let check_name = |attr: &Attribute, sym| attr.has_name(sym);
62 if let Some((value, span)) = extract(check_name, &attrs) {
63 match ITEM_REFS.get(&value).cloned() {
64 // Known lang item with attribute on correct target.
65 Some((item_index, expected_target)) if actual_target == expected_target => {
66 self.collect_item_extended(item_index, hir_id, span);
68 // Known lang item with attribute on incorrect target.
69 Some((_, expected_target)) => {
74 "`{}` language item must be applied to a {}",
81 "attribute should be applied to a {}, not a {}",
82 expected_target, actual_target,
93 "definition of an unknown language item: `{}`",
96 .span_label(span, format!("definition of unknown language item `{}`", value))
103 fn collect_item(&mut self, item_index: usize, item_def_id: DefId) {
104 // Check for duplicates.
105 if let Some(original_def_id) = self.items.items[item_index] {
106 if original_def_id != item_def_id {
107 let lang_item = LangItem::from_u32(item_index as u32).unwrap();
108 let name = lang_item.name();
109 let mut err = match self.tcx.hir().span_if_local(item_def_id) {
110 Some(span) => struct_span_err!(
114 "found duplicate lang item `{}`",
117 None => match self.tcx.extern_crate(item_def_id) {
118 Some(ExternCrate { dependency_of, .. }) => {
119 self.tcx.sess.struct_err(&format!(
120 "duplicate lang item in crate `{}` (which `{}` depends on): `{}`.",
121 self.tcx.crate_name(item_def_id.krate),
122 self.tcx.crate_name(*dependency_of),
126 _ => self.tcx.sess.struct_err(&format!(
127 "duplicate lang item in crate `{}`: `{}`.",
128 self.tcx.crate_name(item_def_id.krate),
133 if let Some(span) = self.tcx.hir().span_if_local(original_def_id) {
134 err.span_note(span, "the lang item is first defined here");
136 match self.tcx.extern_crate(original_def_id) {
137 Some(ExternCrate { dependency_of, .. }) => {
139 "the lang item is first defined in crate `{}` (which `{}` depends on)",
140 self.tcx.crate_name(original_def_id.krate),
141 self.tcx.crate_name(*dependency_of)
146 "the lang item is first defined in crate `{}`.",
147 self.tcx.crate_name(original_def_id.krate)
151 let mut note_def = |which, def_id: DefId| {
152 let crate_name = self.tcx.crate_name(def_id.krate);
153 let note = if def_id.is_local() {
154 format!("{} definition in the local crate (`{}`)", which, crate_name)
156 let paths: Vec<_> = self
158 .crate_extern_paths(def_id.krate)
160 .map(|p| p.display().to_string())
163 "{} definition in `{}` loaded from {}",
171 note_def("first", original_def_id);
172 note_def("second", item_def_id);
179 self.items.items[item_index] = Some(item_def_id);
180 if let Some(group) = LangItem::from_u32(item_index as u32).unwrap().group() {
181 self.items.groups[group as usize].push(item_def_id);
185 // Like collect_item() above, but also checks whether the lang item is declared
186 // with the right number of generic arguments.
187 fn collect_item_extended(&mut self, item_index: usize, hir_id: HirId, span: Span) {
188 let item_def_id = self.tcx.hir().local_def_id(hir_id).to_def_id();
189 let lang_item = LangItem::from_u32(item_index as u32).unwrap();
190 let name = lang_item.name();
192 // Now check whether the lang_item has the expected number of generic
193 // arguments. Generally speaking, binary and indexing operations have
194 // one (for the RHS/index), unary operations have none, the closure
195 // traits have one for the argument list, generators have one for the
196 // resume argument, and ordering/equality relations have one for the RHS
197 // Some other types like Box and various functions like drop_in_place
198 // have minimum requirements.
200 if let hir::Node::Item(hir::Item { kind, span: item_span, .. }) = self.tcx.hir().get(hir_id)
202 let (actual_num, generics_span) = match kind.generics() {
203 Some(generics) => (generics.params.len(), generics.span),
204 None => (0, *item_span),
207 let required = match lang_item.required_generics() {
208 GenericRequirement::Exact(num) if num != actual_num => {
209 Some((format!("{}", num), pluralize!(num)))
211 GenericRequirement::Minimum(num) if actual_num < num => {
212 Some((format!("at least {}", num), pluralize!(num)))
214 // If the number matches, or there is no requirement, handle it normally
218 if let Some((range_str, pluralized)) = required {
219 // We are issuing E0718 "incorrect target" here, because while the
220 // item kind of the target is correct, the target is still wrong
221 // because of the wrong number of generic arguments.
226 "`{}` language item must be applied to a {} with {} generic argument{}",
235 "this {} has {} generic argument{}",
238 pluralize!(actual_num),
243 // return early to not collect the lang item
248 self.collect_item(item_index, item_def_id);
252 /// Traverses and collects all the lang items in all crates.
253 fn get_lang_items(tcx: TyCtxt<'_>, (): ()) -> LanguageItems {
254 // Initialize the collector.
255 let mut collector = LanguageItemCollector::new(tcx);
257 // Collect lang items in other crates.
258 for &cnum in tcx.crates(()).iter() {
259 for &(def_id, item_index) in tcx.defined_lang_items(cnum).iter() {
260 collector.collect_item(item_index, def_id);
264 // Collect lang items in this crate.
265 tcx.hir().krate().visit_all_item_likes(&mut collector);
267 // Extract out the found lang items.
268 let LanguageItemCollector { mut items, .. } = collector;
270 // Find all required but not-yet-defined lang items.
271 weak_lang_items::check_crate(tcx, &mut items);
276 pub fn provide(providers: &mut Providers) {
277 providers.get_lang_items = get_lang_items;