Skip to main content

charon_driver/translate/
translate_meta.rs

1//! Translate information about items: name, attributes, etc.
2use itertools::Itertools;
3use rustc_middle::mir;
4use rustc_span::RemapPathScopeComponents;
5use std::cmp::Ord;
6use std::path::{Component, PathBuf};
7
8use super::translate_crate::RustcItem;
9use super::translate_ctx::*;
10use crate::hax;
11use crate::hax::{DefPathItem, SInto};
12use charon_lib::ast::*;
13
14// Spans
15impl<'tcx> TranslateCtx<'tcx> {
16    /// Register a file if it is a "real" file and was not already registered
17    /// `span` must be a span from which we obtained that filename.
18    fn register_file(&mut self, filename: FileName, span: rustc_span::Span) -> FileId {
19        // Lookup the file if it was already registered
20        match self.file_to_id.get(&filename) {
21            Some(id) => *id,
22            None => {
23                let source_file = self.tcx.sess.source_map().lookup_source_file(span.lo());
24                let crate_name = self.tcx.crate_name(source_file.cnum).to_string();
25                let id = self.translated.files.push_with(|id| File {
26                    id,
27                    name: filename.clone(),
28                    crate_name,
29                    contents: source_file.src.as_deref().cloned(),
30                });
31                self.file_to_id.insert(filename, id);
32                id
33            }
34        }
35    }
36
37    pub fn translate_filename(&mut self, name: rustc_span::FileName) -> meta::FileName {
38        match name {
39            rustc_span::FileName::Real(name) => {
40                match name.local_path() {
41                    Some(path) => {
42                        // Normalize path separators: cross-compiling to Windows uses `\` as path
43                        // separators.
44                        let path: PathBuf = {
45                            let mut normalized = PathBuf::new();
46                            for comp in path.components() {
47                                for segment in comp.as_os_str().to_string_lossy().split("\\") {
48                                    normalized.push(segment);
49                                }
50                            }
51                            normalized
52                        };
53                        // The path to files in the standard library may be full paths to
54                        // somewhere in the sysroot or in the original toolchain source tree. This
55                        // may depend on how the toolchain is installed (rustup vs nix), so we
56                        // normalize the paths here to avoid inconsistencies in the translation.
57                        let path = if let Some(rust_src) = path
58                            .ancestors()
59                            .find(|ancestor| ancestor.ends_with("lib/rustlib/src/rust"))
60                            && let Ok(path) = path.strip_prefix(rust_src)
61                        {
62                            let mut rewritten_path: PathBuf = "/rustc".into();
63                            rewritten_path.extend(path);
64                            rewritten_path
65                        } else if let Ok(path) = path.strip_prefix(&self.sysroot) {
66                            // Unclear if this can happen, but just in case.
67                            let mut rewritten_path: PathBuf = "/toolchain".into();
68                            rewritten_path.extend(path);
69                            rewritten_path
70                        } else {
71                            // Find the cargo home directory: according to cargo docs and having a
72                            // look at the cargo source, it's either the `$CARGO_HOME` var or
73                            // `$HOME/.cargo`
74                            let cargo_home = std::env::var("CARGO_HOME")
75                                .map(PathBuf::from)
76                                .ok()
77                                .or_else(|| std::env::home_dir().map(|p| p.join(".cargo")));
78                            if let Some(cargo_home) = cargo_home
79                                && let Ok(path) = path.strip_prefix(cargo_home)
80                            {
81                                // Avoid some more machine-dependent paths in the llbc output.
82                                let mut rewritten_path: PathBuf = "/cargo".into();
83                                rewritten_path.extend(path);
84                                rewritten_path
85                            } else {
86                                path
87                            }
88                        };
89                        FileName::Local(path)
90                    }
91                    None => {
92                        // We use the virtual name because it is always available.
93                        // That name normally starts with `/rustc/<hash>/`. For our purposes we hide
94                        // the hash.
95                        let virtual_name = name.path(RemapPathScopeComponents::MACRO);
96                        let mut components_iter = virtual_name.components();
97                        if let Some(
98                            [
99                                Component::RootDir,
100                                Component::Normal(rustc),
101                                Component::Normal(hash),
102                            ],
103                        ) = components_iter.by_ref().array_chunks().next()
104                            && rustc.to_str() == Some("rustc")
105                            && hash.len() == 40
106                        {
107                            let path_without_hash = [Component::RootDir, Component::Normal(rustc)]
108                                .into_iter()
109                                .chain(components_iter)
110                                .collect();
111                            FileName::Virtual(path_without_hash)
112                        } else {
113                            FileName::Virtual(virtual_name.into())
114                        }
115                    }
116                }
117            }
118            // We use the debug formatter to generate a filename.
119            // This is not ideal, but filenames are for debugging anyway.
120            _ => FileName::NotReal(format!("{name:?}")),
121        }
122    }
123
124    pub fn translate_span_data(&mut self, span: rustc_span::Span) -> meta::SpanData {
125        let smap: &rustc_span::source_map::SourceMap = self.tcx.sess.psess.source_map();
126        let filename = smap.span_to_filename(span);
127        let filename = self.translate_filename(filename);
128        let file_id = match &filename {
129            FileName::NotReal(_) => {
130                // For now we forbid not real filenames
131                unimplemented!();
132            }
133            FileName::Virtual(_) | FileName::Local(_) => self.register_file(filename, span),
134        };
135
136        let convert_loc = |pos: rustc_span::BytePos| -> Loc {
137            let loc = smap.lookup_char_pos(pos);
138            Loc {
139                line: loc.line,
140                col: loc.col_display,
141            }
142        };
143        let beg = convert_loc(span.lo());
144        let end = convert_loc(span.hi());
145
146        // Put together
147        meta::SpanData { file_id, beg, end }
148    }
149
150    /// Compute span data from a Rust source scope
151    pub fn translate_span_from_source_info(
152        &mut self,
153        source_scopes: &rustc_index::IndexVec<mir::SourceScope, mir::SourceScopeData>,
154        source_info: &mir::SourceInfo,
155    ) -> Span {
156        // Translate the span
157        let data = self.translate_span_data(source_info.span);
158
159        // Lookup the top-most inlined parent scope.
160        let mut parent_span = None;
161        let mut scope_data = &source_scopes[source_info.scope];
162        while let Some(parent_scope) = scope_data.inlined_parent_scope {
163            scope_data = &source_scopes[parent_scope];
164            parent_span = Some(scope_data.span);
165        }
166
167        if let Some(parent_span) = parent_span {
168            let parent_span = self.translate_span_data(parent_span);
169            Span {
170                data: parent_span,
171                generated_from_span: Some(data),
172            }
173        } else {
174            Span {
175                data,
176                generated_from_span: None,
177            }
178        }
179    }
180
181    pub(crate) fn translate_span(&mut self, span: &rustc_span::Span) -> Span {
182        Span {
183            data: self.translate_span_data(*span),
184            generated_from_span: None,
185        }
186    }
187
188    pub(crate) fn def_span(&mut self, def_id: &hax::DefId) -> Span {
189        let span = def_id.def_span(&self.hax_state);
190        self.translate_span(&span)
191    }
192}
193
194// Names
195impl<'tcx> TranslateCtx<'tcx> {
196    fn path_elem_for_def(
197        &mut self,
198        span: Span,
199        item: &RustcItem,
200    ) -> Result<Option<PathElem>, Error> {
201        let def_id = item.def_id();
202        let path_elem = def_id.path_item(&self.hax_state);
203        // Disambiguator disambiguates identically-named (but distinct) identifiers. This happens
204        // notably with macros and inherent impl blocks.
205        let disambiguator = Disambiguator::new(path_elem.disambiguator as usize);
206        // Match over the key data
207        let path_elem = match path_elem.data {
208            DefPathItem::CrateRoot { name, .. } => {
209                Some(PathElem::Ident(name.to_string(), disambiguator))
210            }
211            // We map the three namespaces onto a single one. We can always disambiguate by looking
212            // at the definition.
213            DefPathItem::TypeNs(symbol)
214            | DefPathItem::ValueNs(symbol)
215            | DefPathItem::MacroNs(symbol) => {
216                Some(PathElem::Ident(symbol.to_string(), disambiguator))
217            }
218            DefPathItem::Impl => {
219                let full_def = self.hax_def_for_item(item)?;
220                // Two cases, depending on whether the impl block is
221                // a "regular" impl block (`impl Foo { ... }`) or a trait
222                // implementation (`impl Bar for Foo { ... }`).
223                let impl_elem = match full_def.kind() {
224                    // Inherent impl ("regular" impl)
225                    hax::FullDefKind::InherentImpl { ty, .. } => {
226                        // We need to convert the type, which may contain quantified
227                        // substs and bounds. In order to properly do so, we introduce
228                        // a body translation context.
229                        let item_src =
230                            TransItemSource::new(item.clone(), TransItemSourceKind::InherentImpl);
231                        let mut bt_ctx = ItemTransCtx::new(item_src, None, self);
232                        bt_ctx.translate_item_generics(
233                            span,
234                            &full_def,
235                            &TransItemSourceKind::InherentImpl,
236                        )?;
237                        let ty = bt_ctx.translate_ty(span, ty)?;
238                        ImplElem::Ty(Box::new(Binder {
239                            kind: BinderKind::InherentImplBlock,
240                            params: bt_ctx.into_generics(),
241                            skip_binder: ty,
242                        }))
243                    }
244                    // Trait implementation
245                    hax::FullDefKind::TraitImpl { .. } => {
246                        let impl_id = {
247                            let item_src = TransItemSource::new(
248                                item.clone(),
249                                TransItemSourceKind::TraitImpl(TraitImplSource::Normal),
250                            );
251                            self.register_and_enqueue(&None, item_src).unwrap()
252                        };
253                        ImplElem::Trait(impl_id)
254                    }
255                    _ => unreachable!(),
256                };
257
258                Some(PathElem::Impl(impl_elem))
259            }
260            // TODO: do nothing for now
261            DefPathItem::OpaqueTy => None,
262            // TODO: this is not very satisfactory, but on the other hand
263            // we should be able to extract closures in local let-bindings
264            // (i.e., we shouldn't have to introduce top-level let-bindings).
265            DefPathItem::Closure => Some(PathElem::Ident("closure".to_string(), disambiguator)),
266            // Do nothing, functions in `extern` blocks are in the same namespace as the
267            // block.
268            DefPathItem::ForeignMod => None,
269            // Do nothing, the constructor of a struct/variant has the same name as the
270            // struct/variant.
271            DefPathItem::Ctor => None,
272            DefPathItem::Use => Some(PathElem::Ident("{use}".to_string(), disambiguator)),
273            DefPathItem::AnonConst => Some(PathElem::Ident("{const}".to_string(), disambiguator)),
274            DefPathItem::PromotedConst => Some(PathElem::Ident(
275                "{promoted_const}".to_string(),
276                disambiguator,
277            )),
278            _ => {
279                raise_error!(
280                    self,
281                    span,
282                    "Unexpected DefPathItem for `{def_id:?}`: {path_elem:?}"
283                );
284            }
285        };
286        Ok(path_elem)
287    }
288
289    /// Retrieve the name for this [`hax::DefId`]. Because a given `DefId` may give rise to several
290    /// charon items, prefer to use `translate_name` when possible.
291    ///
292    /// We lookup the path associated to an id, and convert it to a name.
293    /// Paths very precisely identify where an item is. There are important
294    /// subcases, like the items in an `Impl` block:
295    /// ```ignore
296    /// impl<T> List<T> {
297    ///   fn new() ...
298    /// }
299    /// ```
300    ///
301    /// One issue here is that "List" *doesn't appear* in the path, which would
302    /// look like the following:
303    ///
304    ///   `TypeNS("Crate") :: Impl :: ValueNs("new")`
305    ///                       ^^^
306    ///           This is where "List" should be
307    ///
308    /// For this reason, whenever we find an `Impl` path element, we actually
309    /// lookup the type of the sub-path, from which we can derive a name.
310    ///
311    /// Besides, as there may be several "impl" blocks for one type, each impl
312    /// block is identified by a unique number (rustc calls this a
313    /// "disambiguator"), which we grab.
314    ///
315    /// Example:
316    /// ========
317    /// For instance, if we write the following code in crate `test` and module
318    /// `bla`:
319    /// ```ignore
320    /// impl<T> Foo<T> {
321    ///   fn foo() { ... }
322    /// }
323    ///
324    /// impl<T> Foo<T> {
325    ///   fn bar() { ... }
326    /// }
327    /// ```
328    ///
329    /// The names we will generate for `foo` and `bar` are:
330    /// `[Ident("test"), Ident("bla"), Ident("Foo"), Impl(impl<T> Ty<T>, Disambiguator(0)), Ident("foo")]`
331    /// `[Ident("test"), Ident("bla"), Ident("Foo"), Impl(impl<T> Ty<T>, Disambiguator(1)), Ident("bar")]`
332    fn name_for_item(&mut self, item: &RustcItem) -> Result<Name, Error> {
333        if let Some(name) = self.cached_names.get(item) {
334            return Ok(name.clone());
335        }
336        let def_id = item.def_id();
337        trace!("Computing name for `{def_id:?}`");
338
339        let parent_name = if let Some(parent_id) = def_id.parent(&self.hax_state) {
340            let def = self.hax_def_for_item(item)?;
341            if matches!(item, RustcItem::Mono(..))
342                && let Some(parent_item) = def.typing_parent(&self.hax_state)
343            {
344                self.name_for_item(&RustcItem::Mono(parent_item.clone()))?
345            } else {
346                self.name_for_item(&RustcItem::Poly(parent_id.clone()))?
347            }
348        } else {
349            Name { name: Vec::new() }
350        };
351        let span = self.def_span(def_id);
352        let mut name = parent_name;
353        if let Some(path_elem) = self.path_elem_for_def(span, item)? {
354            name.name.push(path_elem);
355        }
356
357        trace!("Computed name for `{def_id:?}`: `{name:?}`");
358        self.cached_names.insert(item.clone(), name.clone());
359        Ok(name)
360    }
361
362    /// Compute the name for an item.
363    /// Internal function, use `translate_name`.
364    pub fn name_for_src(&mut self, src: &TransItemSource) -> Result<Name, Error> {
365        let mut name = if let Some(parent) = src.parent() {
366            self.name_for_src(&parent)?
367        } else {
368            self.name_for_item(&src.item)?
369        };
370        match &src.kind {
371            // Nothing to do for the real items.
372            TransItemSourceKind::Type
373            | TransItemSourceKind::Fun
374            | TransItemSourceKind::Global
375            | TransItemSourceKind::TraitImpl(TraitImplSource::Normal)
376            | TransItemSourceKind::TraitDecl
377            | TransItemSourceKind::InherentImpl
378            | TransItemSourceKind::Module => {}
379
380            TransItemSourceKind::TraitImpl(
381                kind @ (TraitImplSource::Closure(..)
382                | TraitImplSource::ImplicitDestruct
383                | TraitImplSource::TraitAlias),
384            ) => {
385                if let TraitImplSource::Closure(..) = kind {
386                    let _ = name.name.pop(); // Pop the `{closure}`
387                }
388                let impl_id = self.register_and_enqueue(&None, src.clone()).unwrap();
389                name.name.push(PathElem::Impl(ImplElem::Trait(impl_id)));
390            }
391            TransItemSourceKind::ClosureMethod(kind) => {
392                let fn_name = kind.method_name().to_string();
393                name.name
394                    .push(PathElem::Ident(fn_name, Disambiguator::ZERO));
395            }
396            TransItemSourceKind::DropGlueMethod(..) => {
397                name.name.push(PathElem::Ident(
398                    "drop_glue".to_string(),
399                    Disambiguator::ZERO,
400                ));
401            }
402            TransItemSourceKind::ClosureAsFnCast => {
403                name.name
404                    .push(PathElem::Ident("as_fn".into(), Disambiguator::ZERO));
405            }
406            TransItemSourceKind::VTable
407            | TransItemSourceKind::VTableInstance(..)
408            | TransItemSourceKind::VTableInstanceInitializer(..) => {
409                name.name
410                    .push(PathElem::Ident("{vtable}".into(), Disambiguator::ZERO));
411            }
412            TransItemSourceKind::VTableMethod => {
413                name.name.push(PathElem::Ident(
414                    "{vtable_method}".into(),
415                    Disambiguator::ZERO,
416                ));
417            }
418            TransItemSourceKind::VTableDropShim => {
419                name.name.push(PathElem::Ident(
420                    "{vtable_drop_shim}".into(),
421                    Disambiguator::ZERO,
422                ));
423            }
424        }
425        Ok(name)
426    }
427
428    /// Retrieve the name for an item.
429    pub fn translate_name(&mut self, src: &TransItemSource) -> Result<Name, Error> {
430        let mut name = self.name_for_src(src)?;
431        // Push the generics used for monomorphization, if any. We skip mono trait impls as the
432        // generics are already included in the `PathElem::Impl` reference.
433        if let RustcItem::Mono(item_ref) = &src.item
434            && !item_ref.generic_args.is_empty()
435            && !matches!(src.kind, TransItemSourceKind::TraitImpl(..))
436        {
437            let trans_id = self.register_no_enqueue(&None, src).unwrap();
438            let span = self.def_span(&item_ref.def_id);
439            let mut bt_ctx = ItemTransCtx::new(src.clone(), trans_id, self);
440            let binder = bt_ctx.inside_binder(BinderKind::Other, |bt_ctx| {
441                // We skip the clauses: the args are enough to uniquely identify an ite.
442                bt_ctx.translate_generic_args(span, &item_ref.generic_args, &[])
443            })?;
444            if !binder.skip_binder.is_empty() {
445                name.name.push(PathElem::Instantiated(Box::new(binder)));
446            }
447        }
448        Ok(name)
449    }
450
451    pub(crate) fn opacity_for_name(&self, name: &Name) -> ItemOpacity {
452        self.options.opacity_for_name(&self.translated, name)
453    }
454}
455
456// Attributes
457impl<'tcx> TranslateCtx<'tcx> {
458    /// Parse a raw attribute to recognize our special `charon::*`, `aeneas::*` and `verify::*` attributes.
459    fn parse_attr_from_raw(
460        &mut self,
461        def_id: &hax::DefId,
462        raw_attr: RawAttribute,
463    ) -> Result<Attribute, String> {
464        // If the attribute path has two components, the first of which is `charon` or `aeneas`, we
465        // try to parse it. Otherwise we return `Unknown`.
466        let path = raw_attr.path.split("::").collect_vec();
467        let attr_name = if let &[path_start, attr_name] = path.as_slice()
468            && (path_start == "charon" || path_start == "aeneas" || path_start == "verify")
469        {
470            attr_name
471        } else {
472            return Ok(Attribute::Unknown(raw_attr));
473        };
474
475        match self.parse_special_attr(def_id, attr_name, &raw_attr)? {
476            Some(parsed) => Ok(parsed),
477            None => Err(format!("Unrecognized attribute: `{}`", raw_attr)),
478        }
479    }
480
481    /// Parse a `charon::*`, `aeneas::*` or `verify::*` attribute.
482    fn parse_special_attr(
483        &mut self,
484        def_id: &hax::DefId,
485        attr_name: &str,
486        raw_attr: &RawAttribute,
487    ) -> Result<Option<Attribute>, String> {
488        let args = raw_attr.args.as_deref();
489        let parsed = match attr_name {
490            // `#[charon::opaque]`
491            "opaque" if args.is_none() => Attribute::Opaque,
492            // `#[charon::opaque]`
493            "exclude" if args.is_none() => Attribute::Exclude,
494            // `#[charon::transparent]`
495            "transparent" if args.is_none() => Attribute::Transparent,
496            // `#[charon::rename("new_name")]`
497            "rename" if let Some(attr) = args => {
498                let Some(attr) = attr
499                    .strip_prefix("\"")
500                    .and_then(|attr| attr.strip_suffix("\""))
501                else {
502                    return Err(format!(
503                        "the new name should be between quotes: `rename(\"{attr}\")`."
504                    ));
505                };
506
507                if attr.is_empty() {
508                    return Err(format!("attribute `rename` should not be empty"));
509                }
510
511                let first_char = attr.chars().nth(0).unwrap();
512                let is_identifier = (first_char.is_alphabetic() || first_char == '_')
513                    && attr.chars().all(|c| c.is_alphanumeric() || c == '_');
514                if !is_identifier {
515                    return Err(format!(
516                        "attribute `rename` should contain a valid identifier"
517                    ));
518                }
519
520                Attribute::Rename(attr.to_string())
521            }
522            // `#[charon::variants_prefix("T")]`
523            "variants_prefix" if let Some(attr) = args => {
524                let Some(attr) = attr
525                    .strip_prefix("\"")
526                    .and_then(|attr| attr.strip_suffix("\""))
527                else {
528                    return Err(format!(
529                        "the name should be between quotes: `variants_prefix(\"{attr}\")`."
530                    ));
531                };
532
533                Attribute::VariantsPrefix(attr.to_string())
534            }
535            // `#[charon::variants_suffix("T")]`
536            "variants_suffix" if let Some(attr) = args => {
537                let Some(attr) = attr
538                    .strip_prefix("\"")
539                    .and_then(|attr| attr.strip_suffix("\""))
540                else {
541                    return Err(format!(
542                        "the name should be between quotes: `variants_suffix(\"{attr}\")`."
543                    ));
544                };
545
546                Attribute::VariantsSuffix(attr.to_string())
547            }
548            // `#[verify::start_from]`
549            "start_from" => {
550                if matches!(def_id.kind, hax::DefKind::Mod) {
551                    return Err("`start_from` on modules has no effect".to_string());
552                }
553                Attribute::Unknown(raw_attr.clone())
554            }
555            // `#[verify::test]`: mark a function for test extraction
556            "test" if args.is_none() => Attribute::Unknown(raw_attr.clone()),
557            _ => return Ok(None),
558        };
559        Ok(Some(parsed))
560    }
561
562    /// Translates a rust attribute. Returns `None` if the attribute is a doc comment (rustc
563    /// encodes them as attributes). For now we use `String`s for `Attributes`.
564    pub(crate) fn translate_attribute(
565        &mut self,
566        def_id: &hax::DefId,
567        attr: &rustc_hir::Attribute,
568    ) -> Option<Attribute> {
569        use rustc_hir as hir;
570        use rustc_hir::attrs as hir_attrs;
571        match attr {
572            hir::Attribute::Parsed(hir_attrs::AttributeKind::DocComment { comment, .. }) => {
573                Some(Attribute::DocComment(comment.to_string()))
574            }
575            hir::Attribute::Parsed(_) => None,
576            hir::Attribute::Unparsed(attr) => {
577                let raw_attr = RawAttribute {
578                    path: attr.path.to_string(),
579                    args: match &attr.args {
580                        hir::AttrArgs::Empty => None,
581                        hir::AttrArgs::Delimited(args) => {
582                            Some(rustc_ast_pretty::pprust::tts_to_string(&args.tokens))
583                        }
584                        hir::AttrArgs::Eq { expr, .. } => {
585                            self.tcx.sess.source_map().span_to_snippet(expr.span).ok()
586                        }
587                    },
588                };
589                match self.parse_attr_from_raw(def_id, raw_attr) {
590                    Ok(a) => Some(a),
591                    Err(msg) => {
592                        let span = self.translate_span(&attr.span.sinto(&self.hax_state));
593                        register_error!(self, span, "Error parsing attribute: {msg}");
594                        None
595                    }
596                }
597            }
598        }
599    }
600
601    pub(crate) fn translate_inline(&self, def: &hax::FullDef<'tcx>) -> Option<InlineAttr> {
602        match def.kind() {
603            hax::FullDefKind::Fn { inline, .. }
604            | hax::FullDefKind::AssocFn { inline, .. }
605            | hax::FullDefKind::Closure { inline, .. } => match inline {
606                hax::InlineAttr::None => None,
607                hax::InlineAttr::Hint => Some(InlineAttr::Hint),
608                hax::InlineAttr::Never => Some(InlineAttr::Never),
609                hax::InlineAttr::Always => Some(InlineAttr::Always),
610                hax::InlineAttr::Force { .. } => Some(InlineAttr::Always),
611            },
612            _ => None,
613        }
614    }
615
616    pub(crate) fn translate_attr_info(&mut self, def: &hax::FullDef<'tcx>) -> AttrInfo {
617        // Default to `false` for impl blocks and closures.
618        let public = def.visibility.unwrap_or(false);
619        let inline = self.translate_inline(def);
620        let attributes = def
621            .attributes
622            .iter()
623            .filter_map(|attr| self.translate_attribute(def.def_id(), attr))
624            .collect_vec();
625
626        let rename = {
627            let mut renames = attributes.iter().filter_map(|a| a.as_rename()).cloned();
628            let rename = renames.next();
629            if renames.next().is_some() {
630                let span = self.translate_span(&def.span);
631                register_error!(
632                    self,
633                    span,
634                    "There should be at most one `charon::rename(\"...\")` \
635                    or `aeneas::rename(\"...\")` attribute per declaration",
636                );
637            }
638            rename
639        };
640
641        AttrInfo {
642            attributes,
643            inline,
644            public,
645            rename,
646        }
647    }
648}
649
650// `ItemMeta`
651impl<'tcx> TranslateCtx<'tcx> {
652    /// Whether this item is in an `extern { .. }` block, in which case it has no body.
653    pub(crate) fn is_extern_item(&mut self, def: &hax::FullDef<'tcx>) -> bool {
654        def.def_id()
655            .parent(&self.hax_state)
656            .is_some_and(|parent| matches!(parent.kind, hax::DefKind::ForeignMod))
657    }
658
659    /// If this is an item declared in an `extern { .. }` block, return its symbol name.
660    pub(crate) fn extern_item_symbol_name(&mut self, def: &hax::FullDef<'tcx>) -> Option<String> {
661        if !self.is_extern_item(def) {
662            return None;
663        }
664        let path_item = def.def_id().path_item(&self.hax_state);
665        match path_item.data {
666            hax::DefPathItem::ValueNs(name) | hax::DefPathItem::TypeNs(name) => {
667                Some(name.to_string())
668            }
669            _ => None,
670        }
671    }
672
673    /// Compute the meta information for a Rust item.
674    pub(crate) fn translate_item_meta(
675        &mut self,
676        def: &hax::FullDef<'tcx>,
677        item_src: &TransItemSource,
678        name: Name,
679        name_opacity: ItemOpacity,
680    ) -> ItemMeta {
681        if let Some(item_meta) = self.cached_item_metas.get(item_src) {
682            return item_meta.clone();
683        }
684        let span = def.source_span.as_ref().unwrap_or(&def.span);
685        let span = self.translate_span(span);
686        let is_local = def.def_id().is_local();
687        let (attr_info, lang_item) = if !item_src.is_derived_item()
688            || matches!(item_src.kind, TransItemSourceKind::ClosureMethod(..))
689        {
690            let attr_info = self.translate_attr_info(def);
691            let lang_item = def.lang_item.or(def.diagnostic_item).map(|s| s.to_string());
692            (attr_info, lang_item)
693        } else {
694            (AttrInfo::default(), None)
695        };
696
697        let opacity = if attr_info.attributes.iter().any(|attr| attr.is_exclude()) {
698            ItemOpacity::Invisible.max(name_opacity)
699        } else if self.is_extern_item(def)
700            || attr_info.attributes.iter().any(|attr| attr.is_opaque())
701        {
702            // Force opaque in these cases.
703            ItemOpacity::Opaque.max(name_opacity)
704        } else {
705            name_opacity
706        };
707
708        let item_meta = ItemMeta {
709            name,
710            span,
711            source_text: def.source_text.clone(),
712            attr_info,
713            is_local,
714            opacity,
715            lang_item,
716        };
717        self.cached_item_metas
718            .insert(item_src.clone(), item_meta.clone());
719        item_meta
720    }
721}