rustc_passes/
lang_items.rs

1//! Detecting lang items.
2//!
3//! Language items are items that represent concepts intrinsic to the language
4//! itself. Examples are:
5//!
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.
9
10use rustc_ast as ast;
11use rustc_ast::visit;
12use rustc_data_structures::fx::FxHashMap;
13use rustc_hir::def_id::{DefId, LocalDefId};
14use rustc_hir::lang_items::{GenericRequirement, extract};
15use rustc_hir::{LangItem, LanguageItems, MethodKind, Target};
16use rustc_middle::query::Providers;
17use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
18use rustc_session::cstore::ExternCrate;
19use rustc_span::{Span, kw};
20
21use crate::errors::{
22    DuplicateLangItem, IncorrectTarget, LangItemOnIncorrectTarget, UnknownLangItem,
23};
24use crate::weak_lang_items;
25
26pub(crate) enum Duplicate {
27    Plain,
28    Crate,
29    CrateDepends,
30}
31
32struct LanguageItemCollector<'ast, 'tcx> {
33    items: LanguageItems,
34    tcx: TyCtxt<'tcx>,
35    resolver: &'ast ResolverAstLowering,
36    // FIXME(#118552): We should probably feed def_span eagerly on def-id creation
37    // so we can avoid constructing this map for local def-ids.
38    item_spans: FxHashMap<DefId, Span>,
39    parent_item: Option<&'ast ast::Item>,
40}
41
42impl<'ast, 'tcx> LanguageItemCollector<'ast, 'tcx> {
43    fn new(
44        tcx: TyCtxt<'tcx>,
45        resolver: &'ast ResolverAstLowering,
46    ) -> LanguageItemCollector<'ast, 'tcx> {
47        LanguageItemCollector {
48            tcx,
49            resolver,
50            items: LanguageItems::new(),
51            item_spans: FxHashMap::default(),
52            parent_item: None,
53        }
54    }
55
56    fn check_for_lang(
57        &mut self,
58        actual_target: Target,
59        def_id: LocalDefId,
60        attrs: &'ast [ast::Attribute],
61        item_span: Span,
62        generics: Option<&'ast ast::Generics>,
63    ) {
64        if let Some((name, attr_span)) = extract(attrs) {
65            match LangItem::from_name(name) {
66                // Known lang item with attribute on correct target.
67                Some(lang_item) if actual_target == lang_item.target() => {
68                    self.collect_item_extended(
69                        lang_item,
70                        def_id,
71                        item_span,
72                        attr_span,
73                        generics,
74                        actual_target,
75                    );
76                }
77                // Known lang item with attribute on incorrect target.
78                Some(lang_item) => {
79                    self.tcx.dcx().emit_err(LangItemOnIncorrectTarget {
80                        span: attr_span,
81                        name,
82                        expected_target: lang_item.target(),
83                        actual_target,
84                    });
85                }
86                // Unknown lang item.
87                _ => {
88                    self.tcx.dcx().emit_err(UnknownLangItem { span: attr_span, name });
89                }
90            }
91        }
92    }
93
94    fn collect_item(&mut self, lang_item: LangItem, item_def_id: DefId, item_span: Option<Span>) {
95        // Check for duplicates.
96        if let Some(original_def_id) = self.items.get(lang_item)
97            && original_def_id != item_def_id
98        {
99            let lang_item_name = lang_item.name();
100            let crate_name = self.tcx.crate_name(item_def_id.krate);
101            let mut dependency_of = kw::Empty;
102            let is_local = item_def_id.is_local();
103            let path = if is_local {
104                String::new()
105            } else {
106                self.tcx
107                    .crate_extern_paths(item_def_id.krate)
108                    .iter()
109                    .map(|p| p.display().to_string())
110                    .collect::<Vec<_>>()
111                    .join(", ")
112            };
113
114            let first_defined_span = self.item_spans.get(&original_def_id).copied();
115            let mut orig_crate_name = kw::Empty;
116            let mut orig_dependency_of = kw::Empty;
117            let orig_is_local = original_def_id.is_local();
118            let orig_path = if orig_is_local {
119                String::new()
120            } else {
121                self.tcx
122                    .crate_extern_paths(original_def_id.krate)
123                    .iter()
124                    .map(|p| p.display().to_string())
125                    .collect::<Vec<_>>()
126                    .join(", ")
127            };
128
129            if first_defined_span.is_none() {
130                orig_crate_name = self.tcx.crate_name(original_def_id.krate);
131                if let Some(ExternCrate { dependency_of: inner_dependency_of, .. }) =
132                    self.tcx.extern_crate(original_def_id.krate)
133                {
134                    orig_dependency_of = self.tcx.crate_name(*inner_dependency_of);
135                }
136            }
137
138            let duplicate = if item_span.is_some() {
139                Duplicate::Plain
140            } else {
141                match self.tcx.extern_crate(item_def_id.krate) {
142                    Some(ExternCrate { dependency_of: inner_dependency_of, .. }) => {
143                        dependency_of = self.tcx.crate_name(*inner_dependency_of);
144                        Duplicate::CrateDepends
145                    }
146                    _ => Duplicate::Crate,
147                }
148            };
149
150            // When there's a duplicate lang item, something went very wrong and there's no value
151            // in recovering or doing anything. Give the user the one message to let them debug the
152            // mess they created and then wish them farewell.
153            self.tcx.dcx().emit_fatal(DuplicateLangItem {
154                local_span: item_span,
155                lang_item_name,
156                crate_name,
157                dependency_of,
158                is_local,
159                path,
160                first_defined_span,
161                orig_crate_name,
162                orig_dependency_of,
163                orig_is_local,
164                orig_path,
165                duplicate,
166            });
167        } else {
168            // Matched.
169            self.items.set(lang_item, item_def_id);
170            // Collect span for error later
171            if let Some(item_span) = item_span {
172                self.item_spans.insert(item_def_id, item_span);
173            }
174        }
175    }
176
177    // Like collect_item() above, but also checks whether the lang item is declared
178    // with the right number of generic arguments.
179    fn collect_item_extended(
180        &mut self,
181        lang_item: LangItem,
182        item_def_id: LocalDefId,
183        item_span: Span,
184        attr_span: Span,
185        generics: Option<&'ast ast::Generics>,
186        target: Target,
187    ) {
188        let name = lang_item.name();
189
190        if let Some(generics) = generics {
191            // Now check whether the lang_item has the expected number of generic
192            // arguments. Generally speaking, binary and indexing operations have
193            // one (for the RHS/index), unary operations have none, the closure
194            // traits have one for the argument list, coroutines have one for the
195            // resume argument, and ordering/equality relations have one for the RHS
196            // Some other types like Box and various functions like drop_in_place
197            // have minimum requirements.
198
199            // FIXME: This still doesn't count, e.g., elided lifetimes and APITs.
200            let mut actual_num = generics.params.len();
201            if target.is_associated_item() {
202                actual_num += self
203                    .parent_item
204                    .unwrap()
205                    .opt_generics()
206                    .map_or(0, |generics| generics.params.len());
207            }
208
209            let mut at_least = false;
210            let required = match lang_item.required_generics() {
211                GenericRequirement::Exact(num) if num != actual_num => Some(num),
212                GenericRequirement::Minimum(num) if actual_num < num => {
213                    at_least = true;
214                    Some(num)
215                }
216                // If the number matches, or there is no requirement, handle it normally
217                _ => None,
218            };
219
220            if let Some(num) = required {
221                // We are issuing E0718 "incorrect target" here, because while the
222                // item kind of the target is correct, the target is still wrong
223                // because of the wrong number of generic arguments.
224                self.tcx.dcx().emit_err(IncorrectTarget {
225                    span: attr_span,
226                    generics_span: generics.span,
227                    name: name.as_str(),
228                    kind: target.name(),
229                    num,
230                    actual_num,
231                    at_least,
232                });
233
234                // return early to not collect the lang item
235                return;
236            }
237        }
238
239        self.collect_item(lang_item, item_def_id.to_def_id(), Some(item_span));
240    }
241}
242
243/// Traverses and collects all the lang items in all crates.
244fn get_lang_items(tcx: TyCtxt<'_>, (): ()) -> LanguageItems {
245    let resolver = tcx.resolver_for_lowering().borrow();
246    let (resolver, krate) = &*resolver;
247
248    // Initialize the collector.
249    let mut collector = LanguageItemCollector::new(tcx, resolver);
250
251    // Collect lang items in other crates.
252    for &cnum in tcx.used_crates(()).iter() {
253        for &(def_id, lang_item) in tcx.defined_lang_items(cnum).iter() {
254            collector.collect_item(lang_item, def_id, None);
255        }
256    }
257
258    // Collect lang items local to this crate.
259    visit::Visitor::visit_crate(&mut collector, krate);
260
261    // Find all required but not-yet-defined lang items.
262    weak_lang_items::check_crate(tcx, &mut collector.items, krate);
263
264    // Return all the lang items that were found.
265    collector.items
266}
267
268impl<'ast, 'tcx> visit::Visitor<'ast> for LanguageItemCollector<'ast, 'tcx> {
269    fn visit_item(&mut self, i: &'ast ast::Item) {
270        let target = match &i.kind {
271            ast::ItemKind::ExternCrate(_) => Target::ExternCrate,
272            ast::ItemKind::Use(_) => Target::Use,
273            ast::ItemKind::Static(_) => Target::Static,
274            ast::ItemKind::Const(_) => Target::Const,
275            ast::ItemKind::Fn(_) | ast::ItemKind::Delegation(..) => Target::Fn,
276            ast::ItemKind::Mod(_, _) => Target::Mod,
277            ast::ItemKind::ForeignMod(_) => Target::ForeignFn,
278            ast::ItemKind::GlobalAsm(_) => Target::GlobalAsm,
279            ast::ItemKind::TyAlias(_) => Target::TyAlias,
280            ast::ItemKind::Enum(_, _) => Target::Enum,
281            ast::ItemKind::Struct(_, _) => Target::Struct,
282            ast::ItemKind::Union(_, _) => Target::Union,
283            ast::ItemKind::Trait(_) => Target::Trait,
284            ast::ItemKind::TraitAlias(_, _) => Target::TraitAlias,
285            ast::ItemKind::Impl(_) => Target::Impl,
286            ast::ItemKind::MacroDef(_) => Target::MacroDef,
287            ast::ItemKind::MacCall(_) | ast::ItemKind::DelegationMac(_) => {
288                unreachable!("macros should have been expanded")
289            }
290        };
291
292        self.check_for_lang(
293            target,
294            self.resolver.node_id_to_def_id[&i.id],
295            &i.attrs,
296            i.span,
297            i.opt_generics(),
298        );
299
300        let parent_item = self.parent_item.replace(i);
301        visit::walk_item(self, i);
302        self.parent_item = parent_item;
303    }
304
305    fn visit_enum_def(&mut self, enum_definition: &'ast ast::EnumDef) {
306        for variant in &enum_definition.variants {
307            self.check_for_lang(
308                Target::Variant,
309                self.resolver.node_id_to_def_id[&variant.id],
310                &variant.attrs,
311                variant.span,
312                None,
313            );
314        }
315
316        visit::walk_enum_def(self, enum_definition);
317    }
318
319    fn visit_assoc_item(&mut self, i: &'ast ast::AssocItem, ctxt: visit::AssocCtxt) {
320        let (target, generics) = match &i.kind {
321            ast::AssocItemKind::Fn(..) | ast::AssocItemKind::Delegation(..) => {
322                let (body, generics) = if let ast::AssocItemKind::Fn(fun) = &i.kind {
323                    (fun.body.is_some(), Some(&fun.generics))
324                } else {
325                    (true, None)
326                };
327                (
328                    match &self.parent_item.unwrap().kind {
329                        ast::ItemKind::Impl(i) => {
330                            if i.of_trait.is_some() {
331                                Target::Method(MethodKind::Trait { body })
332                            } else {
333                                Target::Method(MethodKind::Inherent)
334                            }
335                        }
336                        ast::ItemKind::Trait(_) => Target::Method(MethodKind::Trait { body }),
337                        _ => unreachable!(),
338                    },
339                    generics,
340                )
341            }
342            ast::AssocItemKind::Const(ct) => (Target::AssocConst, Some(&ct.generics)),
343            ast::AssocItemKind::Type(ty) => (Target::AssocTy, Some(&ty.generics)),
344            ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(_) => {
345                unreachable!("macros should have been expanded")
346            }
347        };
348
349        self.check_for_lang(
350            target,
351            self.resolver.node_id_to_def_id[&i.id],
352            &i.attrs,
353            i.span,
354            generics,
355        );
356
357        visit::walk_assoc_item(self, i, ctxt);
358    }
359}
360
361pub(crate) fn provide(providers: &mut Providers) {
362    providers.get_lang_items = get_lang_items;
363}