Skip to main content

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;
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, Symbol, sym};
20
21use crate::errors::{
22    DuplicateLangItem, IncorrectCrateType, IncorrectTarget, LangItemOnIncorrectTarget,
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_ast(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().delayed_bug("unknown lang item");
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 = None;
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 = None;
116            let mut orig_dependency_of = None;
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 = Some(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 = Some(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 = Some(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        if self.tcx.crate_types().contains(&rustc_session::config::CrateType::Sdylib) {
240            self.tcx.dcx().emit_err(IncorrectCrateType { span: attr_span });
241        }
242
243        self.collect_item(lang_item, item_def_id.to_def_id(), Some(item_span));
244    }
245}
246
247/// Traverses and collects all the lang items in all crates.
248fn get_lang_items(tcx: TyCtxt<'_>, (): ()) -> LanguageItems {
249    let resolver = tcx.resolver_for_lowering().borrow();
250    let (resolver, krate) = &*resolver;
251
252    // Initialize the collector.
253    let mut collector = LanguageItemCollector::new(tcx, resolver);
254
255    // Collect lang items in other crates.
256    for &cnum in tcx.used_crates(()).iter() {
257        for &(def_id, lang_item) in tcx.defined_lang_items(cnum).iter() {
258            collector.collect_item(lang_item, def_id, None);
259        }
260    }
261
262    // Collect lang items local to this crate.
263    visit::Visitor::visit_crate(&mut collector, krate);
264
265    // Find all required but not-yet-defined lang items.
266    weak_lang_items::check_crate(tcx, &mut collector.items, krate);
267
268    // Return all the lang items that were found.
269    collector.items
270}
271
272impl<'ast, 'tcx> visit::Visitor<'ast> for LanguageItemCollector<'ast, 'tcx> {
273    fn visit_item(&mut self, i: &'ast ast::Item) {
274        let target = match &i.kind {
275            ast::ItemKind::ExternCrate(..) => Target::ExternCrate,
276            ast::ItemKind::Use(_) => Target::Use,
277            ast::ItemKind::Static(_) => Target::Static,
278            ast::ItemKind::Const(_) | ast::ItemKind::ConstBlock(_) => Target::Const,
279            ast::ItemKind::Fn(_) | ast::ItemKind::Delegation(..) => Target::Fn,
280            ast::ItemKind::Mod(..) => Target::Mod,
281            ast::ItemKind::ForeignMod(_) => Target::ForeignFn,
282            ast::ItemKind::GlobalAsm(_) => Target::GlobalAsm,
283            ast::ItemKind::TyAlias(_) => Target::TyAlias,
284            ast::ItemKind::Enum(..) => Target::Enum,
285            ast::ItemKind::Struct(..) => Target::Struct,
286            ast::ItemKind::Union(..) => Target::Union,
287            ast::ItemKind::Trait(_) => Target::Trait,
288            ast::ItemKind::TraitAlias(..) => Target::TraitAlias,
289            ast::ItemKind::Impl(imp_) => Target::Impl { of_trait: imp_.of_trait.is_some() },
290            ast::ItemKind::MacroDef(..) => Target::MacroDef,
291            ast::ItemKind::MacCall(_) | ast::ItemKind::DelegationMac(_) => {
292                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("macros should have been expanded")));
}unreachable!("macros should have been expanded")
293            }
294        };
295
296        self.check_for_lang(
297            target,
298            self.resolver.node_id_to_def_id[&i.id],
299            &i.attrs,
300            i.span,
301            i.opt_generics(),
302        );
303
304        let parent_item = self.parent_item.replace(i);
305        visit::walk_item(self, i);
306        self.parent_item = parent_item;
307    }
308
309    fn visit_variant(&mut self, variant: &'ast ast::Variant) {
310        self.check_for_lang(
311            Target::Variant,
312            self.resolver.node_id_to_def_id[&variant.id],
313            &variant.attrs,
314            variant.span,
315            None,
316        );
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::TraitImpl)
332                            } else {
333                                Target::Method(MethodKind::Inherent)
334                            }
335                        }
336                        ast::ItemKind::Trait(_) => Target::Method(MethodKind::Trait { body }),
337                        _ => ::core::panicking::panic("internal error: entered unreachable code")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                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("macros should have been expanded")));
}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
361/// Extracts the first `lang = "$name"` out of a list of attributes.
362/// The `#[panic_handler]` attribute is also extracted out when found.
363///
364/// This function is used for `ast::Attribute`, for `hir::Attribute` use the `find_attr!` macro with `AttributeKind::Lang`
365pub(crate) fn extract_ast(attrs: &[rustc_ast::ast::Attribute]) -> Option<(Symbol, Span)> {
366    attrs.iter().find_map(|attr| {
367        Some(match attr {
368            _ if attr.has_name(sym::lang) => (attr.value_str()?, attr.span()),
369            _ if attr.has_name(sym::panic_handler) => (sym::panic_impl, attr.span()),
370            _ => return None,
371        })
372    })
373}
374
375pub(crate) fn provide(providers: &mut Providers) {
376    providers.get_lang_items = get_lang_items;
377}