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