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::diagnostics::{DuplicateLangItem, IncorrectCrateType, IncorrectTarget};
22use crate::weak_lang_items;
23
24pub(crate) enum Duplicate {
25    Plain,
26    Crate,
27    CrateDepends,
28}
29
30struct LanguageItemCollector<'ast, 'tcx> {
31    items: LanguageItems,
32    tcx: TyCtxt<'tcx>,
33    resolver: &'ast ResolverAstLowering<'tcx>,
34    // FIXME(#118552): We should probably feed def_span eagerly on def-id creation
35    // so we can avoid constructing this map for local def-ids.
36    item_spans: FxHashMap<DefId, Span>,
37    parent_item: Option<&'ast ast::Item>,
38}
39
40impl<'ast, 'tcx> LanguageItemCollector<'ast, 'tcx> {
41    fn new(
42        tcx: TyCtxt<'tcx>,
43        resolver: &'ast ResolverAstLowering<'tcx>,
44    ) -> LanguageItemCollector<'ast, 'tcx> {
45        LanguageItemCollector {
46            tcx,
47            resolver,
48            items: LanguageItems::new(),
49            item_spans: FxHashMap::default(),
50            parent_item: None,
51        }
52    }
53
54    fn check_for_lang(
55        &mut self,
56        actual_target: Target,
57        def_id: LocalDefId,
58        attrs: &'ast [ast::Attribute],
59        item_span: Span,
60        generics: Option<&'ast ast::Generics>,
61    ) {
62        if let Some((name, attr_span)) = extract_ast(attrs) {
63            match LangItem::from_name(name) {
64                // Known lang item
65                Some(lang_item) => {
66                    if actual_target != lang_item.target() {
67                        self.tcx
68                            .dcx()
69                            .delayed_bug("lang item target is checked in attribute parser");
70                        return;
71                    }
72                    self.collect_item_extended(
73                        lang_item,
74                        def_id,
75                        item_span,
76                        attr_span,
77                        generics,
78                        actual_target,
79                    );
80                }
81                // Unknown lang item.
82                _ => {
83                    self.tcx.dcx().delayed_bug("unknown lang item");
84                }
85            }
86        }
87    }
88
89    fn collect_item(&mut self, lang_item: LangItem, item_def_id: DefId, item_span: Option<Span>) {
90        // Check for duplicates.
91        if let Some(original_def_id) = self.items.get(lang_item)
92            && original_def_id != item_def_id
93        {
94            let lang_item_name = lang_item.name();
95            let crate_name = self.tcx.crate_name(item_def_id.krate);
96            let mut dependency_of = None;
97            let is_local = item_def_id.is_local();
98            let path = if is_local {
99                String::new()
100            } else {
101                self.tcx
102                    .crate_extern_paths(item_def_id.krate)
103                    .iter()
104                    .map(|p| p.display().to_string())
105                    .collect::<Vec<_>>()
106                    .join(", ")
107            };
108
109            let first_defined_span = self.item_spans.get(&original_def_id).copied();
110            let mut orig_crate_name = None;
111            let mut orig_dependency_of = None;
112            let orig_is_local = original_def_id.is_local();
113            let orig_path = if orig_is_local {
114                String::new()
115            } else {
116                self.tcx
117                    .crate_extern_paths(original_def_id.krate)
118                    .iter()
119                    .map(|p| p.display().to_string())
120                    .collect::<Vec<_>>()
121                    .join(", ")
122            };
123
124            if first_defined_span.is_none() {
125                orig_crate_name = Some(self.tcx.crate_name(original_def_id.krate));
126                if let Some(ExternCrate { dependency_of: inner_dependency_of, .. }) =
127                    self.tcx.extern_crate(original_def_id.krate)
128                {
129                    orig_dependency_of = Some(self.tcx.crate_name(*inner_dependency_of));
130                }
131            }
132
133            let duplicate = if item_span.is_some() {
134                Duplicate::Plain
135            } else {
136                match self.tcx.extern_crate(item_def_id.krate) {
137                    Some(ExternCrate { dependency_of: inner_dependency_of, .. }) => {
138                        dependency_of = Some(self.tcx.crate_name(*inner_dependency_of));
139                        Duplicate::CrateDepends
140                    }
141                    _ => Duplicate::Crate,
142                }
143            };
144
145            // When there's a duplicate lang item, something went very wrong and there's no value
146            // in recovering or doing anything. Give the user the one message to let them debug the
147            // mess they created and then wish them farewell.
148            self.tcx.dcx().emit_fatal(DuplicateLangItem {
149                local_span: item_span,
150                lang_item_name,
151                crate_name,
152                dependency_of,
153                is_local,
154                path,
155                first_defined_span,
156                orig_crate_name,
157                orig_dependency_of,
158                orig_is_local,
159                orig_path,
160                duplicate,
161            });
162        } else {
163            // Matched.
164            self.items.set(lang_item, item_def_id);
165            // Collect span for error later
166            if let Some(item_span) = item_span {
167                self.item_spans.insert(item_def_id, item_span);
168            }
169        }
170    }
171
172    // Like collect_item() above, but also checks whether the lang item is declared
173    // with the right number of generic arguments.
174    fn collect_item_extended(
175        &mut self,
176        lang_item: LangItem,
177        item_def_id: LocalDefId,
178        item_span: Span,
179        attr_span: Span,
180        generics: Option<&'ast ast::Generics>,
181        target: Target,
182    ) {
183        let name = lang_item.name();
184
185        if let Some(generics) = generics {
186            // Now check whether the lang_item has the expected number of generic
187            // arguments. Generally speaking, binary and indexing operations have
188            // one (for the RHS/index), unary operations have none, the closure
189            // traits have one for the argument list, coroutines have one for the
190            // resume argument, and ordering/equality relations have one for the RHS
191            // Some other types like Box and various unsizing-related traits
192            // have minimum requirements.
193
194            // FIXME: This still doesn't count, e.g., elided lifetimes and APITs.
195            let mut actual_num = generics.params.len();
196            if target.is_associated_item() {
197                actual_num += self
198                    .parent_item
199                    .unwrap()
200                    .opt_generics()
201                    .map_or(0, |generics| generics.params.len());
202            }
203
204            let mut at_least = false;
205            let required = match lang_item.required_generics() {
206                GenericRequirement::Exact(num) if num != actual_num => Some(num),
207                GenericRequirement::Minimum(num) if actual_num < num => {
208                    at_least = true;
209                    Some(num)
210                }
211                // If the number matches, or there is no requirement, handle it normally
212                _ => None,
213            };
214
215            if let Some(num) = required {
216                // We are issuing E0718 "incorrect target" here, because while the
217                // item kind of the target is correct, the target is still wrong
218                // because of the wrong number of generic arguments.
219                self.tcx.dcx().emit_err(IncorrectTarget {
220                    span: attr_span,
221                    generics_span: generics.span,
222                    name: name.as_str(),
223                    kind: target.name(),
224                    num,
225                    actual_num,
226                    at_least,
227                });
228
229                // return early to not collect the lang item
230                return;
231            }
232        }
233
234        if self.tcx.crate_types().contains(&rustc_session::config::CrateType::Sdylib) {
235            self.tcx.dcx().emit_err(IncorrectCrateType { span: attr_span });
236        }
237
238        self.collect_item(lang_item, item_def_id.to_def_id(), Some(item_span));
239    }
240}
241
242/// Traverses and collects all the lang items in all crates.
243fn get_lang_items(tcx: TyCtxt<'_>, (): ()) -> LanguageItems {
244    let (resolver, krate) = tcx.resolver_for_lowering();
245    let resolver = &*resolver.borrow();
246    let krate = &*krate.borrow();
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(_) | ast::ItemKind::ConstBlock(_) => 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(imp_) => Target::Impl { of_trait: imp_.of_trait.is_some() },
286            ast::ItemKind::MacroDef(..) => Target::MacroDef,
287            ast::ItemKind::MacCall(_) | ast::ItemKind::DelegationMac(_) => {
288                {
    ::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")
289            }
290        };
291
292        self.check_for_lang(
293            target,
294            self.resolver.owners[&i.id].def_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_variant(&mut self, variant: &'ast ast::Variant) {
306        self.check_for_lang(
307            Target::Variant,
308            self.resolver.owners[&self.parent_item.unwrap().id].node_id_to_def_id[&variant.id],
309            &variant.attrs,
310            variant.span,
311            None,
312        );
313    }
314
315    fn visit_assoc_item(&mut self, i: &'ast ast::AssocItem, ctxt: visit::AssocCtxt) {
316        let (target, generics) = match &i.kind {
317            ast::AssocItemKind::Fn(..) | ast::AssocItemKind::Delegation(..) => {
318                let (body, generics) = if let ast::AssocItemKind::Fn(fun) = &i.kind {
319                    (fun.body.is_some(), Some(&fun.generics))
320                } else {
321                    (true, None)
322                };
323                (
324                    match &self.parent_item.unwrap().kind {
325                        ast::ItemKind::Impl(i) => {
326                            if i.of_trait.is_some() {
327                                Target::Method(MethodKind::TraitImpl)
328                            } else {
329                                Target::Method(MethodKind::Inherent)
330                            }
331                        }
332                        ast::ItemKind::Trait(_) => Target::Method(MethodKind::Trait { body }),
333                        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
334                    },
335                    generics,
336                )
337            }
338            ast::AssocItemKind::Const(ct) => (Target::AssocConst, Some(&ct.generics)),
339            ast::AssocItemKind::Type(ty) => (Target::AssocTy, Some(&ty.generics)),
340            ast::AssocItemKind::MacCall(_) | ast::AssocItemKind::DelegationMac(_) => {
341                {
    ::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")
342            }
343        };
344
345        self.check_for_lang(target, self.resolver.owners[&i.id].def_id, &i.attrs, i.span, generics);
346
347        visit::walk_assoc_item(self, i, ctxt);
348    }
349}
350
351/// Extracts the first `lang = "$name"` out of a list of attributes.
352/// The `#[panic_handler]` attribute is also extracted out when found.
353///
354/// This function is used for `ast::Attribute`, for `hir::Attribute` use the `find_attr!` macro with `AttributeKind::Lang`
355pub(crate) fn extract_ast(attrs: &[rustc_ast::ast::Attribute]) -> Option<(Symbol, Span)> {
356    attrs.iter().find_map(|attr| {
357        Some(match attr {
358            _ if attr.has_name(sym::lang) => (attr.value_str()?, attr.span()),
359            _ if attr.has_name(sym::panic_handler) => (sym::panic_impl, attr.span()),
360            _ => return None,
361        })
362    })
363}
364
365pub(crate) fn provide(providers: &mut Providers) {
366    providers.get_lang_items = get_lang_items;
367}