Skip to main content

charon_driver/translate/
translate_meta.rs

1//! Translate information about items: name, attributes, etc.
2use itertools::Itertools;
3use rustc_hash::FxHashSet as HashSet;
4use rustc_middle::{mir, ty};
5use rustc_span::RemapPathScopeComponents;
6use rustc_span::def_id::DefId as RDefId;
7use std::{
8    cmp::Ord,
9    path::{Component, PathBuf},
10    sync::LazyLock,
11};
12
13use super::translate_crate::RustcItem;
14use super::translate_ctx::*;
15use crate::frontend as front;
16use crate::frontend::{BaseState, DefPathItem, SInto};
17use charon_lib::{ast::*, name_matcher::NamePattern};
18
19// Spans
20impl<'tcx> TranslateCtx<'tcx> {
21    /// Register a file if it is a "real" file and was not already registered
22    /// `span` must be a span from which we obtained that filename.
23    fn register_file(&mut self, filename: FileName, span: rustc_span::Span) -> FileId {
24        // Lookup the file if it was already registered
25        match self.file_to_id.get(&filename) {
26            Some(id) => *id,
27            None => {
28                let source_file = self.tcx.sess.source_map().lookup_source_file(span.lo());
29                let crate_name = self.tcx.crate_name(source_file.cnum).to_string();
30                let id = self.translated.files.push_with(|id| File {
31                    id,
32                    name: filename.clone(),
33                    crate_name,
34                    contents: source_file.src.as_deref().cloned(),
35                });
36                self.file_to_id.insert(filename, id);
37                id
38            }
39        }
40    }
41
42    pub fn translate_filename(&mut self, name: rustc_span::FileName) -> meta::FileName {
43        match name {
44            rustc_span::FileName::Real(name) => {
45                match name.local_path() {
46                    Some(path) => {
47                        // Normalize path separators: cross-compiling to Windows uses `\` as path
48                        // separators.
49                        let path: PathBuf = {
50                            let mut normalized = PathBuf::new();
51                            for comp in path.components() {
52                                for segment in comp.as_os_str().to_string_lossy().split("\\") {
53                                    normalized.push(segment);
54                                }
55                            }
56                            normalized
57                        };
58                        // Find the cargo home directory: according to cargo docs and having a
59                        // look at the cargo source, it's either the `$CARGO_HOME` var or
60                        // `$HOME/.cargo`
61                        static CURRENT_DIR: LazyLock<Option<PathBuf>> =
62                            LazyLock::new(|| std::env::current_dir().ok());
63                        static CARGO_HOME: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
64                            std::env::var("CARGO_HOME")
65                                .map(PathBuf::from)
66                                .ok()
67                                .or_else(|| std::env::home_dir().map(|p| p.join(".cargo")))
68                        });
69                        // The path to files in the standard library may be full paths to
70                        // somewhere in the sysroot or in the original toolchain source tree. This
71                        // may depend on how the toolchain is installed (rustup vs nix), so we
72                        // normalize the paths here to avoid inconsistencies in the translation.
73                        let path = if let Some(rust_src) = path
74                            .ancestors()
75                            .find(|ancestor| ancestor.ends_with("lib/rustlib/src/rust"))
76                            && let Ok(path) = path.strip_prefix(rust_src)
77                        {
78                            let mut rewritten_path: PathBuf = "/rustc".into();
79                            rewritten_path.extend(path);
80                            rewritten_path
81                        } else if let Ok(path) = path.strip_prefix(&self.sysroot) {
82                            // Unclear if this can happen, but just in case.
83                            let mut rewritten_path: PathBuf = "/toolchain".into();
84                            rewritten_path.extend(path);
85                            rewritten_path
86                        } else if let Some(cargo_home) = &*CARGO_HOME
87                            && let Ok(path) = path.strip_prefix(cargo_home)
88                        {
89                            let mut rewritten_path: PathBuf = "/cargo".into();
90                            rewritten_path.extend(path);
91                            rewritten_path
92                        } else if let Some(current_dir) = &*CURRENT_DIR
93                            && let Ok(path) = path.strip_prefix(current_dir)
94                        {
95                            path.to_path_buf()
96                        } else {
97                            path
98                        };
99                        FileName::Local(path)
100                    }
101                    None => {
102                        // We use the virtual name because it is always available.
103                        // That name normally starts with `/rustc/<hash>/`. For our purposes we hide
104                        // the hash.
105                        let virtual_name = name.path(RemapPathScopeComponents::MACRO);
106                        let mut components_iter = virtual_name.components();
107                        if let Some(
108                            [
109                                Component::RootDir,
110                                Component::Normal(rustc),
111                                Component::Normal(hash),
112                            ],
113                        ) = components_iter.by_ref().array_chunks().next()
114                            && rustc.to_str() == Some("rustc")
115                            && hash.len() == 40
116                        {
117                            let path_without_hash = [Component::RootDir, Component::Normal(rustc)]
118                                .into_iter()
119                                .chain(components_iter)
120                                .collect();
121                            FileName::Virtual(path_without_hash)
122                        } else {
123                            FileName::Virtual(virtual_name.into())
124                        }
125                    }
126                }
127            }
128            // We use the debug formatter to generate a filename.
129            // This is not ideal, but filenames are for debugging anyway.
130            _ => FileName::NotReal(format!("{name:?}")),
131        }
132    }
133
134    pub fn translate_span_data(&mut self, span: rustc_span::Span) -> meta::SpanData {
135        if let Some(data) = self.cached_span_datas.get(&span) {
136            return *data;
137        }
138        let data = self.translate_span_data_uncached(span);
139        self.cached_span_datas.insert(span, data);
140        data
141    }
142
143    fn translate_span_data_uncached(&mut self, span: rustc_span::Span) -> meta::SpanData {
144        let smap: &rustc_span::source_map::SourceMap = self.tcx.sess.psess.source_map();
145        let source_file = smap.lookup_source_file(span.lo());
146        let file_id = match self.cached_file_ids.get(&source_file.stable_id) {
147            Some(id) => *id,
148            None => {
149                let filename = self.translate_filename(source_file.name.clone());
150                let file_id = match &filename {
151                    FileName::NotReal(_) => {
152                        // For now we forbid not real filenames
153                        unimplemented!();
154                    }
155                    FileName::Virtual(_) | FileName::Local(_) => self.register_file(filename, span),
156                };
157                self.cached_file_ids.insert(source_file.stable_id, file_id);
158                file_id
159            }
160        };
161
162        let convert_loc = |pos: rustc_span::BytePos| -> Loc {
163            let (line, col, _col_display) = source_file.lookup_file_pos_with_col_display(pos);
164            Loc {
165                line: line as u32,
166                col: col.0 as u32,
167            }
168        };
169        let beg = convert_loc(span.lo());
170        let end = convert_loc(span.hi());
171
172        // Put together
173        meta::SpanData { file_id, beg, end }
174    }
175
176    /// Compute span data from a Rust source scope
177    pub fn translate_span_from_source_info(
178        &mut self,
179        source_scopes: &rustc_index::IndexVec<mir::SourceScope, mir::SourceScopeData>,
180        source_info: &mir::SourceInfo,
181    ) -> Span {
182        // Lookup the top-most inlined parent scope.
183        let mut parent_span = None;
184        let mut scope_data = &source_scopes[source_info.scope];
185        while let Some(parent_scope) = scope_data.inlined_parent_scope {
186            scope_data = &source_scopes[parent_scope];
187            parent_span = Some(scope_data.span);
188        }
189
190        if let Some(parent_span) = parent_span {
191            let data = self.translate_span_data(source_info.span);
192            let parent_span = self.translate_span_data(parent_span);
193            Span::new(parent_span, Some(data))
194        } else {
195            self.translate_span(&source_info.span)
196        }
197    }
198
199    pub(crate) fn translate_span(&mut self, span: &rustc_span::Span) -> Span {
200        if let Some(translated) = self.cached_spans.get(span) {
201            return *translated;
202        }
203        let translated = self.translate_span_uncached(span);
204        self.cached_spans.insert(*span, translated);
205        translated
206    }
207
208    fn translate_span_uncached(&mut self, span: &rustc_span::Span) -> Span {
209        // If the span comes from a macro expansion, point to the outermost macro call and record
210        // the span inside the macro as `generated_from_span`. We skip compiler desugarings
211        // `ExpnKind::Desugaring` since their spans already point to user code.
212        let macro_call = if span.from_expansion() {
213            span.macro_backtrace()
214                .filter(|expn| matches!(expn.kind, rustc_span::ExpnKind::Macro(..)))
215                .last()
216        } else {
217            None
218        };
219        let data = self.translate_span_data(*span);
220        match macro_call {
221            Some(expn) => {
222                // Code that already points to the macro call doesn't need a `generated_from_span`.
223                if expn.call_site.lo_hi() == span.lo_hi() {
224                    Span::new(data, None)
225                } else {
226                    Span::new(self.translate_span_data(expn.call_site), Some(data))
227                }
228            }
229            None => Span::new(data, None),
230        }
231    }
232
233    pub(crate) fn def_span(&mut self, def_id: &front::DefId) -> Span {
234        let span = def_id.def_span(&self.frontend_state);
235        self.translate_span(&span)
236    }
237}
238
239// Names
240impl<'tcx> TranslateCtx<'tcx> {
241    /// The path element for a trait impl. This translates the impl generics and implemented trait.
242    fn trait_impl_elem(
243        &mut self,
244        span: Span,
245        item: &TransItemSource<'tcx>,
246    ) -> Result<ImplElem, Error> {
247        let impl_id = self.register_and_enqueue(&None, item.clone()).expect_item();
248        let full_def = self.frontend_def_for_item(item)?;
249        let item_id = ItemOrModuleId::Item(ItemId::TraitImpl(impl_id));
250        let mut bt_ctx = ItemTransCtx::new(item.clone(), item_id, self);
251        bt_ctx.translate_item_generics(span, &full_def)?;
252        let timpl = full_def.kind().as_trait_impl().unwrap();
253        let trait_pred = timpl.trait_pred();
254        let trait_ref = bt_ctx.translate_trait_ref(span, &trait_pred.trait_ref)?;
255        let params = bt_ctx.into_generics();
256        let binder = Binder::new(BinderKind::TraitImplBlock, params, trait_ref);
257        Ok(ImplElem::Trait {
258            impl_id,
259            impl_trait: TraitImplHeader(HashConsed::new(binder)),
260            is_negative: !trait_pred.is_positive,
261        })
262    }
263
264    fn path_elem_for_def(
265        &mut self,
266        span: Span,
267        item: &TransItemSource<'tcx>,
268    ) -> Result<Option<PathElem>, Error> {
269        let def_id = item.def_id();
270        if let Some(synthetic) = def_id.derived_base().as_synthetic(&self.frontend_state) {
271            return Ok(match synthetic {
272                front::SyntheticItem::Tuple(n) => Some(PathElem::Builtin(
273                    BuiltinPathElem::Tuple(n),
274                    Disambiguator::ZERO,
275                )),
276                front::SyntheticItem::Str => {
277                    Some(PathElem::Builtin(BuiltinPathElem::Str, Disambiguator::ZERO))
278                }
279                front::SyntheticItem::Array
280                | front::SyntheticItem::Slice
281                | front::SyntheticItem::FnPtr(_) => None,
282            });
283        }
284        let path_elem = def_id.path_item(&self.frontend_state);
285        // Disambiguator disambiguates identically-named (but distinct) identifiers. This happens
286        // notably with macros and inherent impl blocks.
287        let disambiguator = Disambiguator::new(path_elem.disambiguator as usize);
288        // Match over the key data
289        let path_elem = match path_elem.data {
290            DefPathItem::CrateRoot { name, .. } => {
291                Some(PathElem::Ident(name.as_str().into(), disambiguator))
292            }
293            // We map the three namespaces onto a single one. We can always disambiguate by looking
294            // at the definition.
295            DefPathItem::TypeNs(symbol)
296            | DefPathItem::ValueNs(symbol)
297            | DefPathItem::MacroNs(symbol) => {
298                Some(PathElem::Ident(symbol.as_str().into(), disambiguator))
299            }
300            DefPathItem::Impl => {
301                // Two cases, depending on whether the impl block is
302                // a "regular" impl block (`impl Foo { ... }`) or a trait
303                // implementation (`impl Bar for Foo { ... }`).
304                let impl_elem = match def_id.kind {
305                    // Inherent impl ("regular" impl)
306                    front::DefKind::Impl { of_trait: false } => {
307                        let full_def = self.frontend_def_for_item(item)?;
308                        let i = full_def.kind().as_inherent_impl().unwrap();
309                        // We need to convert the type, which may contain quantified
310                        // substs and bounds. In order to properly do so, we introduce
311                        // a body translation context.
312                        let item_id = ItemOrModuleId::Module(item.def_id().real_rust_def_id());
313                        let mut bt_ctx = ItemTransCtx::new(item.clone(), item_id, self);
314                        bt_ctx.translate_item_generics(span, &full_def)?;
315                        let ty = bt_ctx.translate_ty(span, i.ty())?;
316                        ImplElem::Ty(Box::new(Binder {
317                            kind: BinderKind::InherentImplBlock,
318                            params: bt_ctx.into_generics(),
319                            skip_binder: ty,
320                        }))
321                    }
322                    // Trait implementation
323                    front::DefKind::Impl { of_trait: true } => self.trait_impl_elem(span, item)?,
324                    _ => unreachable!(),
325                };
326
327                Some(PathElem::Impl(impl_elem))
328            }
329            // TODO: do nothing for now
330            DefPathItem::OpaqueTy => None,
331            // TODO: this is not very satisfactory, but on the other hand
332            // we should be able to extract closures in local let-bindings
333            // (i.e., we shouldn't have to introduce top-level let-bindings).
334            DefPathItem::Closure => {
335                Some(PathElem::Builtin(BuiltinPathElem::Closure, disambiguator))
336            }
337            // Do nothing, functions in `extern` blocks are in the same namespace as the
338            // block.
339            DefPathItem::ForeignMod => None,
340            // Do nothing, the constructor of a struct/variant has the same name as the
341            // struct/variant.
342            DefPathItem::Ctor => None,
343            DefPathItem::Use => Some(PathElem::Builtin(BuiltinPathElem::Use, disambiguator)),
344            DefPathItem::AnonConst => {
345                Some(PathElem::Builtin(BuiltinPathElem::AnonConst, disambiguator))
346            }
347            DefPathItem::PromotedConst => Some(PathElem::Builtin(
348                BuiltinPathElem::PromotedConst,
349                disambiguator,
350            )),
351            _ => {
352                raise_error!(
353                    self,
354                    span,
355                    "Unexpected DefPathItem for `{def_id:?}`: {path_elem:?}"
356                );
357            }
358        };
359        Ok(path_elem)
360    }
361
362    /// Retrieve the name for this [`front::DefId`]. Because a given `DefId` may give rise to several
363    /// charon items, prefer to use `translate_name` when possible.
364    ///
365    /// We lookup the path associated to an id, and convert it to a name.
366    /// Paths very precisely identify where an item is. There are important
367    /// subcases, like the items in an `Impl` block:
368    /// ```ignore
369    /// impl<T> List<T> {
370    ///   fn new() ...
371    /// }
372    /// ```
373    ///
374    /// One issue here is that "List" *doesn't appear* in the path, which would
375    /// look like the following:
376    ///
377    ///   `TypeNS("Crate") :: Impl :: ValueNs("new")`
378    ///                       ^^^
379    ///           This is where "List" should be
380    ///
381    /// For this reason, whenever we find an `Impl` path element, we actually
382    /// lookup the type of the sub-path, from which we can derive a name.
383    ///
384    /// Besides, as there may be several "impl" blocks for one type, each impl
385    /// block is identified by a unique number (rustc calls this a
386    /// "disambiguator"), which we grab.
387    ///
388    /// Example:
389    /// ========
390    /// For instance, if we write the following code in crate `test` and module
391    /// `bla`:
392    /// ```ignore
393    /// impl<T> Foo<T> {
394    ///   fn foo() { ... }
395    /// }
396    ///
397    /// impl<T> Foo<T> {
398    ///   fn bar() { ... }
399    /// }
400    /// ```
401    ///
402    /// The names we will generate for `foo` and `bar` are:
403    /// `[Ident("test"), Ident("bla"), Ident("Foo"), Impl(impl<T> Ty<T>, Disambiguator(0)), Ident("foo")]`
404    /// `[Ident("test"), Ident("bla"), Ident("Foo"), Impl(impl<T> Ty<T>, Disambiguator(1)), Ident("bar")]`
405    fn name_for_base_item(&mut self, item: &TransItemSource<'tcx>) -> Result<Name, Error> {
406        if let Some(name) = self.cached_names.get(item) {
407            return Ok(name.clone());
408        }
409        let def_id = item.def_id();
410        trace!("Computing name for `{def_id:?}`");
411
412        let is_builtin = def_id
413            .derived_base()
414            .as_synthetic(&self.frontend_state)
415            .is_some();
416        let parent_name =
417            if !is_builtin && let Some(parent_id) = def_id.parent(&self.frontend_state) {
418                // FIXME: We have lost the real context in which `item_ref` was defined; it may have
419                // trait proofs that refer to it, or conversely `def_id` may have clauses that shadow
420                // some impls. So it's incorrect to use `def_id` as owner here.
421                let s = &self.frontend_state.with_frontend_owner(def_id);
422                if let RustcItem::Mono(item_ref) = &item.item
423                    && let Some(parent_item) = item_ref.typing_parent(s)
424                {
425                    self.name_for_base_item(&TransItemSource::monomorphic(&parent_item))?
426                } else {
427                    self.name_for_base_item(&TransItemSource::polymorphic(&parent_id))?
428                }
429            } else {
430                Name { name: Vec::new() }
431            };
432        let span = self.def_span(def_id);
433        let mut name = parent_name;
434        if let Some(path_elem) = self.path_elem_for_def(span, item)? {
435            name.name.push(path_elem);
436        }
437
438        trace!("Computed name for `{def_id:?}`: `{name:?}`");
439        self.cached_names.insert(item.clone(), name.clone());
440        Ok(name)
441    }
442
443    /// Compute the name for an item.
444    /// Internal function, use `translate_name`.
445    pub fn name_for_item(&mut self, src: &TransItemSource<'tcx>) -> Result<Name, Error> {
446        use front::DerivedItemKind::*;
447        let mut name = if let Some(parent) = src.naming_parent(&self.frontend_state) {
448            self.name_for_item(&parent)?
449        } else {
450            self.name_for_base_item(src)?
451        };
452        match src.def_id().as_derived() {
453            // These items keep the base name.
454            None | Some(Initializer) => {}
455
456            Some(kind @ (TraitAliasImpl | MarkerImpl | DestructImpl | FnImpl(_))) => {
457                if let FnImpl(_) = kind {
458                    let _ = name.name.pop(); // Pop the `{closure}`
459                }
460                let span = self.def_span(src.def_id());
461                let impl_elem = self.trait_impl_elem(span, src)?;
462                name.name.push(PathElem::Impl(impl_elem));
463            }
464            Some(DropGlueMethodDef) => {
465                name.name
466                    .push(PathElem::Ident("drop_glue".into(), Disambiguator::ZERO));
467            }
468            Some(BuiltinAssocItemImpl(item)) => {
469                let elem = if item.as_derived() == Some(&DropGlueMethodDef) {
470                    PathElem::Builtin(BuiltinPathElem::DropGlue, Disambiguator::ZERO)
471                } else {
472                    let span = self.def_span(item);
473                    self.path_elem_for_def(span, &TransItemSource::polymorphic(item))?
474                        .unwrap()
475                };
476                name.name.push(elem);
477            }
478            Some(kind) => {
479                let elem = match kind {
480                    ClosureAsFnCast => BuiltinPathElem::ClosureAsFn,
481                    VTableDef | VTableImpl => BuiltinPathElem::VTable,
482                    VTableMethodShim => BuiltinPathElem::VTableMethod,
483                    VTableDropShim => BuiltinPathElem::VTableDropShim,
484                    IntrinsicFallback => BuiltinPathElem::IntrinsicFallback,
485                    _ => unreachable!("unhandled item source {kind:?}"),
486                };
487                name.name.push(PathElem::Builtin(elem, Disambiguator::ZERO));
488            }
489        }
490        Ok(name)
491    }
492
493    /// Retrieve the name for an item.
494    pub fn translate_name(&mut self, src: &TransItemSource<'tcx>) -> Result<Name, Error> {
495        let mut name = self.name_for_item(src)?;
496        // Push the generics used for monomorphization, if any. We skip mono trait impls as the
497        // generics are already included in the `PathElem::Impl` reference.
498        if let RustcItem::Mono(item_ref) = &src.item
499            && !item_ref.generic_args.is_empty()
500            && !src.kind().is_trait_impl()
501        {
502            let trans_id = self.register_no_enqueue(&None, src);
503            let span = self.def_span(&item_ref.def_id);
504            let mut bt_ctx = ItemTransCtx::new(src.clone(), trans_id, self);
505            let binder = bt_ctx.inside_binder(BinderKind::Other, |bt_ctx| {
506                // We skip the clauses: the args are enough to uniquely identify an item.
507                bt_ctx.translate_generic_args_without_trait_refs(span, item_ref)
508            })?;
509            if !binder.skip_binder.is_empty() {
510                name.name.push(PathElem::Instantiated(Box::new(binder)));
511            }
512        }
513        Ok(name)
514    }
515
516    pub(crate) fn opacity_for_name(&self, name: &Name) -> ItemOpacity {
517        self.options.opacity_for_name(&self.translated, name)
518    }
519}
520
521enum ContractTarget {
522    Parent,
523    Path(String),
524}
525
526// Attributes
527impl<'tcx> TranslateCtx<'tcx> {
528    fn resolve_contract_target(
529        &mut self,
530        def_id: &front::DefId,
531        target: ContractTarget,
532    ) -> Result<MaybeAssocItemId, String> {
533        if !matches!(
534            def_id.kind,
535            front::DefKind::Fn | front::DefKind::AssocFn | front::DefKind::Closure
536        ) {
537            return Err("contract attributes can only be applied to functions".to_string());
538        }
539
540        let parent_id = def_id.parent(&self.frontend_state);
541        let target_def_id = match &target {
542            ContractTarget::Parent => parent_id.ok_or_else(|| {
543                "#[charon::contract(..., parent)] is invalid at the crate root".to_string()
544            })?,
545            ContractTarget::Path(target_name) => {
546                let mut siblings = Vec::new();
547                if let Some(parent_id) = &parent_id {
548                    let parent_def = self.poly_frontend_def(parent_id).map_err(|err| err.msg)?;
549                    siblings.extend(
550                        parent_def
551                            .nameable_children(&self.frontend_state)
552                            .into_iter()
553                            .map(|(_, id)| id),
554                    );
555
556                    // Free items inside a function body aren't in the `nameable_children`.
557                    if matches!(
558                        parent_def.kind(),
559                        front::FullDefKind::Fn(_)
560                            | front::FullDefKind::AssocFn(_)
561                            | front::FullDefKind::Closure(_)
562                    ) && let Some(parent_local_id) =
563                        parent_id.as_real_def_id().and_then(|id| id.as_local())
564                        && let Some(body_id) =
565                            self.tcx.hir_node_by_def_id(parent_local_id).body_id()
566                    {
567                        use rustc_hir::intravisit;
568
569                        struct NestedItems(Vec<rustc_hir::def_id::LocalDefId>);
570                        impl<'tcx> intravisit::Visitor<'tcx> for NestedItems {
571                            fn visit_nested_item(&mut self, id: rustc_hir::ItemId) {
572                                self.0.push(id.owner_id.def_id);
573                            }
574                        }
575
576                        let mut nested_items = NestedItems(Vec::new());
577                        intravisit::walk_body(&mut nested_items, self.tcx.hir_body(body_id));
578                        siblings.extend(
579                            nested_items
580                                .0
581                                .into_iter()
582                                .map(|id| id.to_def_id().sinto(&self.frontend_state)),
583                        );
584                    }
585                }
586                let siblings = siblings
587                    .into_iter()
588                    .filter(|sibling| sibling != def_id)
589                    .filter(
590                        |sibling| match sibling.path_item(&self.frontend_state).data {
591                            DefPathItem::ValueNs(name)
592                            | DefPathItem::TypeNs(name)
593                            | DefPathItem::MacroNs(name) => name.as_str() == target_name.as_str(),
594                            _ => false,
595                        },
596                    )
597                    .collect_vec();
598                match siblings.as_slice() {
599                    [sibling] => sibling.clone(),
600                    [] => {
601                        // Fall back to full path search.
602                        let path = NamePattern::parse(target_name)
603                            .map_err(|err| format!("invalid item path `{target_name}`: {err}"))?;
604                        let targets = super::resolve_path::def_path_def_ids(
605                            &self.frontend_state,
606                            &path,
607                            true,
608                        )
609                        .map_err(|err| {
610                            format!("failed to resolve item path `{target_name}`: {err}")
611                        })?;
612                        let [target] = targets.as_slice() else {
613                            return Err(format!(
614                                "item path `{target_name}` resolved to {} items; expected exactly one",
615                                targets.len()
616                            ));
617                        };
618                        target.sinto(&self.frontend_state)
619                    }
620                    _ => {
621                        return Err(format!(
622                            "found several sibling items named `{target_name}`; expected exactly one"
623                        ));
624                    }
625                }
626            }
627        };
628
629        let target_def = self
630            .poly_frontend_def(&target_def_id)
631            .map_err(|err| err.msg)?;
632        if self.options.monomorphize_with_frontend && target_def.this().mentions_non_lt_param {
633            return Err("contracts on generic items are not supported \
634                with `--monomorphize`"
635                .to_string());
636        }
637
638        if let ContractTarget::Path(_) = target
639            && let Some(associated_item) = target_def.associated_item()
640            && let front::AssocItemContainer::TraitContainer { trait_ref } =
641                &associated_item.container
642        {
643            let trait_src =
644                TransItemSource::from_item(trait_ref, self.options.monomorphize_with_frontend);
645            let trait_id = self.register_and_enqueue(&None, trait_src).expect_item();
646            let item_id = self
647                .translate_assoc_item_id(trait_id, &target_def_id)
648                .map_err(|err| err.msg)?;
649            Ok(MaybeAssocItemId::Assoc(trait_id, item_id))
650        } else {
651            let target_item = match target_def.kind() {
652                // Point at the method that contains the closure code.
653                front::FullDefKind::Closure(c) => &target_def.this().make_derived_fn_call_method(
654                    &self.frontend_state.with_frontend_owner(&target_def_id),
655                    c.kind().clone(),
656                ),
657                _ => target_def.this(),
658            };
659            if !TransItemSource::is_translatable(&target_item.def_id) {
660                return Err(format!("`{target_def_id:?}` is not a translatable item"));
661            }
662            let target_src =
663                TransItemSource::from_item(target_item, self.options.monomorphize_with_frontend);
664            let item_id: ItemId = self.register_and_enqueue(&None, target_src).expect_item();
665            Ok(MaybeAssocItemId::Free(item_id))
666        }
667    }
668
669    /// Parse a raw attribute to recognize our special `charon::*`, `aeneas::*` and `verify::*` attributes.
670    fn parse_attr_from_raw(
671        &mut self,
672        def_id: &front::DefId,
673        raw_attr: RawAttribute,
674    ) -> Result<Attribute, String> {
675        // If the attribute path has two components, the first of which is `charon` or `aeneas`, we
676        // try to parse it. Otherwise we return `Unknown`.
677        let path = raw_attr.path.split("::").collect_vec();
678        let attr_name = if let &[path_start, attr_name] = path.as_slice()
679            && (path_start == "charon" || path_start == "aeneas" || path_start == "verify")
680        {
681            attr_name
682        } else {
683            return Ok(Attribute::Unknown(raw_attr));
684        };
685
686        match self.parse_special_attr(def_id, attr_name, &raw_attr)? {
687            Some(parsed) => Ok(parsed),
688            None => Err(format!("Unrecognized attribute: `{}`", raw_attr)),
689        }
690    }
691
692    /// Parse a `charon::*`, `aeneas::*` or `verify::*` attribute.
693    fn parse_special_attr(
694        &mut self,
695        def_id: &front::DefId,
696        attr_name: &str,
697        raw_attr: &RawAttribute,
698    ) -> Result<Option<Attribute>, String> {
699        let args = raw_attr.args.as_deref();
700        let parsed = match attr_name {
701            // `#[charon::opaque]`
702            "opaque" if args.is_none() => Attribute::Opaque,
703            // `#[charon::opaque]`
704            "exclude" if args.is_none() => Attribute::Exclude,
705            // `#[charon::transparent]`
706            "transparent" if args.is_none() => Attribute::Transparent,
707            // `#[charon::contract(kind = "...", parent)]` or
708            // `#[charon::contract(kind = "...", for = "path")]`
709            "contract" if let Some(args) = args => {
710                use syn::{ext::IdentExt, parse::Parser};
711
712                let parser = |input: syn::parse::ParseStream<'_>| {
713                    let mut kind = None;
714                    let mut target = None;
715                    while !input.is_empty() {
716                        let key = input.call(syn::Ident::parse_any)?;
717                        let key_name = key.to_string();
718                        if key_name == "parent" && !input.peek(syn::Token![=]) {
719                            if target.is_some() {
720                                return Err(syn::Error::new(
721                                    key.span(),
722                                    "duplicate contract target",
723                                ));
724                            }
725                            target = Some(ContractTarget::Parent);
726                        } else {
727                            input.parse::<syn::Token![=]>()?;
728                            let value = input.parse::<syn::LitStr>()?.value();
729                            match key_name.as_str() {
730                                "kind" => {
731                                    if kind.is_some() {
732                                        return Err(syn::Error::new(
733                                            key.span(),
734                                            "duplicate contract argument `kind`",
735                                        ));
736                                    }
737                                    kind = Some(value);
738                                }
739                                "for" => {
740                                    if target.is_some() {
741                                        return Err(syn::Error::new(
742                                            key.span(),
743                                            "duplicate contract target",
744                                        ));
745                                    }
746                                    target = Some(ContractTarget::Path(value));
747                                }
748                                "parent" => {
749                                    return Err(syn::Error::new(
750                                        key.span(),
751                                        "contract argument `parent` does not take a value",
752                                    ));
753                                }
754                                _ => {
755                                    return Err(syn::Error::new(
756                                        key.span(),
757                                        format!("unknown contract argument `{key}`"),
758                                    ));
759                                }
760                            }
761                        }
762                        if !input.is_empty() {
763                            input.parse::<syn::Token![,]>()?;
764                        }
765                    }
766                    let kind =
767                        kind.ok_or_else(|| input.error("missing contract argument `kind`"))?;
768                    let target = target
769                        .ok_or_else(|| input.error("missing contract target `parent` or `for`"))?;
770                    Ok((kind, target))
771                };
772                let (kind, target) = parser.parse_str(args).map_err(|err| {
773                    format!(
774                        "invalid contract syntax: {err}; expected \
775                         `#[charon::contract(kind = \"...\", parent)]` or \
776                         `#[charon::contract(kind = \"...\", for = \"item path\")]`"
777                    )
778                })?;
779                Attribute::IsContract {
780                    kind,
781                    target: self.resolve_contract_target(def_id, target)?,
782                }
783            }
784            // `#[charon::rename("new_name")]`
785            "rename" if let Some(attr) = args => {
786                let Some(attr) = attr
787                    .strip_prefix("\"")
788                    .and_then(|attr| attr.strip_suffix("\""))
789                else {
790                    return Err(format!(
791                        "the new name should be between quotes: `rename(\"{attr}\")`."
792                    ));
793                };
794
795                if attr.is_empty() {
796                    return Err(format!("attribute `rename` should not be empty"));
797                }
798
799                let first_char = attr.chars().nth(0).unwrap();
800                let is_identifier = (first_char.is_alphabetic() || first_char == '_')
801                    && attr.chars().all(|c| c.is_alphanumeric() || c == '_');
802                if !is_identifier {
803                    return Err(format!(
804                        "attribute `rename` should contain a valid identifier"
805                    ));
806                }
807
808                Attribute::Rename(attr.to_string())
809            }
810            // `#[charon::variants_prefix("T")]`
811            "variants_prefix" if let Some(attr) = args => {
812                let Some(attr) = attr
813                    .strip_prefix("\"")
814                    .and_then(|attr| attr.strip_suffix("\""))
815                else {
816                    return Err(format!(
817                        "the name should be between quotes: `variants_prefix(\"{attr}\")`."
818                    ));
819                };
820
821                Attribute::VariantsPrefix(attr.to_string())
822            }
823            // `#[charon::variants_suffix("T")]`
824            "variants_suffix" if let Some(attr) = args => {
825                let Some(attr) = attr
826                    .strip_prefix("\"")
827                    .and_then(|attr| attr.strip_suffix("\""))
828                else {
829                    return Err(format!(
830                        "the name should be between quotes: `variants_suffix(\"{attr}\")`."
831                    ));
832                };
833
834                Attribute::VariantsSuffix(attr.to_string())
835            }
836            // `#[verify::start_from]`
837            "start_from" => {
838                if matches!(def_id.kind, front::DefKind::Mod) {
839                    return Err("`start_from` on modules has no effect".to_string());
840                }
841                Attribute::Unknown(raw_attr.clone())
842            }
843            // `#[verify::test]`: mark a function for test extraction
844            "test" if args.is_none() => Attribute::Unknown(raw_attr.clone()),
845            _ => return Ok(None),
846        };
847        Ok(Some(parsed))
848    }
849
850    /// Translates a rust attribute. Returns `None` if the attribute is a doc comment (rustc
851    /// encodes them as attributes). For now we use `String`s for `Attributes`.
852    pub(crate) fn translate_attribute(
853        &mut self,
854        def_id: &front::DefId,
855        attr: &rustc_attr_ir::Attribute,
856    ) -> Option<Attribute> {
857        use rustc_attr_ir as hir_attrs;
858        match attr {
859            hir_attrs::Attribute::Parsed(hir_attrs::AttributeKind::DocComment {
860                comment, ..
861            }) => {
862                (!self.options.no_doc_comments).then(|| Attribute::DocComment(comment.to_string()))
863            }
864            hir_attrs::Attribute::Parsed(attr) => self
865                .translate_rustc_attribute_kind(attr)
866                .ok()
867                .map(Attribute::Builtin),
868            hir_attrs::Attribute::Tool { item: attr, .. }
869            | hir_attrs::Attribute::DeriveHelper(attr) => {
870                let raw_attr = RawAttribute {
871                    path: attr.path.to_string(),
872                    args: match &attr.args {
873                        hir_attrs::AttrArgs::Empty => None,
874                        hir_attrs::AttrArgs::Delimited(args) => {
875                            Some(rustc_ast_pretty::pprust::tts_to_string(&args.tokens))
876                        }
877                        hir_attrs::AttrArgs::Eq { expr, .. } => {
878                            self.tcx.sess.source_map().span_to_snippet(expr.span).ok()
879                        }
880                    },
881                };
882                match self.parse_attr_from_raw(def_id, raw_attr) {
883                    Ok(a) => Some(a),
884                    Err(msg) => {
885                        let span = self.translate_span(&attr.span.sinto(&self.frontend_state));
886                        register_error!(self, span, "Error parsing attribute: {msg}");
887                        None
888                    }
889                }
890            }
891        }
892    }
893
894    pub(crate) fn translate_inline(&self, def: &front::FullDef<'tcx>) -> Option<InlineAttr> {
895        let inline = match def.kind() {
896            front::FullDefKind::Fn(f) => f.inline(),
897            front::FullDefKind::AssocFn(f) => f.inline(),
898            front::FullDefKind::Closure(c) => c.inline(),
899            _ => return None,
900        };
901        match inline {
902            front::InlineAttr::None => None,
903            front::InlineAttr::Hint => Some(InlineAttr::Hint),
904            front::InlineAttr::Never => Some(InlineAttr::Never),
905            front::InlineAttr::Always => Some(InlineAttr::Always),
906            front::InlineAttr::Force { .. } => Some(InlineAttr::Always),
907        }
908    }
909
910    /// Whether this item can be named from outside its crate.
911    pub(crate) fn frontend_def_id_is_exported(&mut self, def_id: &front::DefId) -> bool {
912        match &def_id.base {
913            front::DefIdBase::Real(def_id) => self.is_exported(*def_id),
914            front::DefIdBase::DerivedItem(def_id, _) => self.frontend_def_id_is_exported(def_id),
915            front::DefIdBase::Synthetic(_) => true,
916            front::DefIdBase::Promoted(..)
917            | front::DefIdBase::ImplAssocItem(_)
918            | front::DefIdBase::Alloc(_) => false,
919        }
920    }
921
922    /// Whether this item can be named from outside its crate.
923    pub(crate) fn is_exported(&mut self, def_id: RDefId) -> bool {
924        use rustc_hir::def::DefKind;
925        let tcx = self.tcx;
926        // rustc only stores whether items are exported for local crates.
927        if let Some(local_def_id) = def_id.as_local() {
928            return tcx.effective_visibilities(()).is_exported(local_def_id);
929        }
930        // otherwise, we compute it ourselves! this mirrors rustc's `effective_visibilities` query:
931        // https://github.com/rust-lang/rust/blob/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_privacy/src/lib.rs#L1789
932        let parent = tcx.opt_parent(def_id);
933        let parent_kind = parent.map(|parent| tcx.def_kind(parent));
934        match tcx.def_kind(def_id) {
935            DefKind::Field => {
936                // the field is exported if it's `pub` and its parent is exported.
937                return tcx.visibility(def_id).is_public() && self.is_exported(parent.unwrap());
938            }
939            DefKind::Impl { of_trait } => {
940                // an impl is exported if the "shallow" versions of its self type and trait are.
941                let self_ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
942                // so we collect all referenced DefIds
943                let mut def_ids = match *self_ty.kind() {
944                    ty::Adt(adt_def, _) => vec![adt_def.did()],
945                    ty::Foreign(id)
946                    | ty::FnDef(id, _)
947                    | ty::Closure(id, _)
948                    | ty::CoroutineClosure(id, _)
949                    | ty::Coroutine(id, _) => vec![id],
950                    ty::Dynamic(preds, ..) => preds
951                        .iter()
952                        .map(|pred| match pred.skip_binder() {
953                            ty::ExistentialPredicate::Trait(tref) => tref.def_id,
954                            ty::ExistentialPredicate::Projection(proj) => {
955                                proj.trait_ref(tcx).def_id
956                            }
957                            ty::ExistentialPredicate::AutoTrait(id) => id,
958                        })
959                        .collect(),
960                    _ => vec![],
961                };
962                if of_trait {
963                    def_ids.push(tcx.impl_trait_id(def_id));
964                }
965                // ... and check that all referenced items are exported or in another crate.
966                // this is also what rustc does!
967                // https://github.com/rust-lang/rust/blob/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_privacy/src/lib.rs#L376
968                return def_ids
969                    .into_iter()
970                    .all(|id| id.krate != def_id.krate || self.is_exported(id));
971            }
972            DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy
973                if let Some(DefKind::Impl { of_trait }) = parent_kind =>
974            {
975                // items of trait impls follow the impl, and for inherent impls they must be pub
976                return (of_trait || tcx.visibility(def_id).is_public())
977                    && self.is_exported(parent.unwrap());
978            }
979            _ => {}
980        };
981
982        let krate = def_id.krate;
983        self.exported_foreign_items
984            .entry(krate)
985            .or_insert_with(|| {
986                // no easy way out: we recursively traverse the crate for all
987                // its public exported items
988                let mut exported = HashSet::default();
989                let mut stack = vec![krate.as_def_id()];
990                while let Some(id) = stack.pop() {
991                    // mod/enum/traits are the only items with "module" children
992                    if exported.insert(id)
993                        && matches!(
994                            tcx.def_kind(id),
995                            DefKind::Mod | DefKind::Enum | DefKind::Trait
996                        )
997                    {
998                        stack.extend(
999                            tcx.module_children(id)
1000                                .iter()
1001                                .filter(|c| c.vis.is_public())
1002                                .filter_map(|c| c.res.opt_def_id())
1003                                .filter(|c| c.krate == krate),
1004                        );
1005                    }
1006                }
1007                exported
1008            })
1009            .contains(&def_id)
1010    }
1011
1012    pub(crate) fn translate_attr_info(&mut self, def: &front::FullDef<'tcx>) -> AttrInfo {
1013        // Default to `false` for impl blocks and closures.
1014        let public = def.visibility.unwrap_or(false);
1015        let exported = self.frontend_def_id_is_exported(def.def_id());
1016        let inline = self.translate_inline(def);
1017        let attributes = def
1018            .attributes
1019            .iter()
1020            .filter_map(|attr| self.translate_attribute(def.def_id().derived_base(), attr))
1021            .collect_vec();
1022
1023        let rename = {
1024            let mut renames = attributes.iter().filter_map(|a| a.as_rename()).cloned();
1025            let rename = renames.next();
1026            if renames.next().is_some() {
1027                let span = self.translate_span(&def.span);
1028                register_error!(
1029                    self,
1030                    span,
1031                    "There should be at most one `charon::rename(\"...\")` \
1032                    or `aeneas::rename(\"...\")` attribute per declaration",
1033                );
1034            }
1035            rename
1036        };
1037
1038        AttrInfo {
1039            attributes,
1040            inline,
1041            public,
1042            exported,
1043            rename,
1044        }
1045    }
1046}
1047
1048// `ItemMeta`
1049impl<'tcx> TranslateCtx<'tcx> {
1050    /// Whether this item is in an `extern { .. }` block, in which case it has no body.
1051    pub(crate) fn is_extern_item(&mut self, def: &front::FullDef<'tcx>) -> bool {
1052        def.def_id()
1053            .parent(&self.frontend_state)
1054            .is_some_and(|parent| matches!(parent.kind, front::DefKind::ForeignMod))
1055    }
1056
1057    /// If this is an item declared in an `extern { .. }` block, return its symbol name.
1058    pub(crate) fn extern_item_symbol_name(&mut self, def: &front::FullDef<'tcx>) -> Option<String> {
1059        if !self.is_extern_item(def) {
1060            return None;
1061        }
1062        let def_id = def.def_id().derived_base().as_real_def_id()?;
1063        let instance = rustc_middle::ty::Instance::mono(self.tcx, def_id);
1064        Some(self.tcx.symbol_name(instance).name.to_string())
1065    }
1066
1067    /// Compute the meta information for a Rust item.
1068    pub(crate) fn translate_item_meta(
1069        &mut self,
1070        def: &front::FullDef<'tcx>,
1071        item_src: &TransItemSource<'tcx>,
1072        name: Name,
1073        name_opacity: ItemOpacity,
1074    ) -> ItemMeta {
1075        let span = def.source_span.as_ref().unwrap_or(&def.span);
1076        let span = self.translate_span(span);
1077        let is_local = def.def_id().is_local();
1078        let (attr_info, lang_item, diagnostic_item) = if item_src.use_base_attr_info() {
1079            let attr_info = self.translate_attr_info(def);
1080            let lang_item = def
1081                .def_id()
1082                .derived_base()
1083                .as_real_def_id()
1084                .and_then(|id| self.tcx.as_lang_item(id))
1085                .or_else(|| {
1086                    // For weak lang items (e.g. `panic_impl`), rustc only maps the lang item to its
1087                    // definition, so we look at the `#[lang]` attribute of their `extern` declaration.
1088                    self.is_extern_item(def)
1089                        .then(|| rustc_attr_ir::find_attr!(def.attributes, Lang(item, _) => *item))
1090                        .flatten()
1091                })
1092                .map(|lang_item| {
1093                    self.translate_rustc_lang_item(&lang_item)
1094                        .expect("all rustc LangItem variants should be translated")
1095                });
1096            let diagnostic_item = def.diagnostic_item.map(|s| s.to_string());
1097            (attr_info, lang_item, diagnostic_item)
1098        } else {
1099            (AttrInfo::default(), None, None)
1100        };
1101
1102        let opacity = if attr_info.attributes.iter().any(|attr| attr.is_exclude()) {
1103            ItemOpacity::Invisible.max(name_opacity)
1104        } else if self.is_poly_in_mono(item_src) {
1105            if item_src.kind().is_trait_impl() {
1106                ItemOpacity::Opaque.max(name_opacity)
1107            } else {
1108                ItemOpacity::Invisible.max(name_opacity)
1109            }
1110        } else if self.is_extern_item(def)
1111            || attr_info.attributes.iter().any(|attr| attr.is_opaque())
1112        {
1113            // Force opaque in these cases.
1114            ItemOpacity::Opaque.max(name_opacity)
1115        } else {
1116            name_opacity
1117        };
1118
1119        ItemMeta {
1120            name,
1121            span,
1122            source_text: def.source_text(self.tcx),
1123            attr_info,
1124            is_local,
1125            // Computed by `compute_started_from` after translation.
1126            started_from: false,
1127            is_extern: self.is_extern_item(def),
1128            opacity,
1129            lang_item,
1130            diagnostic_item,
1131            has_errors: false,
1132        }
1133    }
1134}