charon_lib/ast/meta/names.rs
1//! User-visible names of items.
2use crate::ast::*;
3use derive_generic_visitor::{Drive, DriveMut, DriveTwo};
4use enum_as_inner::EnumAsInner;
5use itertools::Itertools;
6use serde::{Deserialize, Serialize};
7use serde_state::{DeserializeState, SerializeState};
8
9generate_index_type!(Disambiguator);
10
11// Some known names we may refer to.
12/// We treat this one specially in the `inline_local_panic_functions` pass. See there for details.
13pub static EXPLICIT_PANIC_NAME: &[&str] = &["core", "panicking", "panic_explicit"];
14pub static BOX_ASSUME_INIT_INTO_VEC_UNSAFE: &str = "box_assume_init_into_vec_unsafe";
15pub static BOX_NEW: &str = "alloc::boxed::Box::new";
16pub static BOX_WRITE: &str = "alloc::boxed::Box::write";
17pub static BOX_WRITE_PATTERN: &str = "alloc::boxed::_::write"; // `_` matches an impl block
18
19/// See the comments for [Name]
20#[derive(Debug, Clone, PartialEq, Eq, Hash)]
21#[derive(EnumAsInner)]
22#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
23#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("Pe"))]
24pub enum PathElem {
25 #[serde_state(stateless)]
26 Ident(String, Disambiguator),
27 Impl(ImplElem),
28 /// This item was obtained by instantiating its parent with the given args. The binder binds
29 /// the parameters of the new items. If the binder binds nothing then this is a
30 /// monomorphization.
31 Instantiated(Box<Binder<GenericArgs>>),
32 /// This item is only available on the given target. Only appears in multi-target mode.
33 #[serde_state(stateless)]
34 Target(TargetTriple),
35 /// A path element that doesn't come from the source code: either a builtin type such as
36 /// tuples, or an item that has no name of its own such as a closure or a vtable.
37 #[serde_state(stateless)]
38 Builtin(BuiltinPathElem, Disambiguator),
39}
40
41/// Used for builtin items, rather than hardcoding these as strings.
42#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
43#[derive(EnumAsInner)]
44#[derive(Serialize, Deserialize)]
45#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("Pe"))]
46pub enum BuiltinPathElem {
47 /// The tuple of the given arity.
48 Tuple(usize),
49 /// `str`, which is a struct containing a `[u8]` the standard library expects
50 /// to be valid UTF-8.
51 Str,
52 /// A closure.
53 Closure,
54 /// A `use` declaration.
55 Use,
56 /// An anonymous constant.
57 AnonConst,
58 /// A constant that rustc promoted out of a body.
59 PromotedConst,
60 /// The function item we generate for a closure that is cast to a function pointer.
61 ClosureAsFn,
62 /// The method we add to the `Destruct` trait to hold the drop glue.
63 DropGlue,
64 /// The vtable struct of a trait, or the vtable global of a trait impl.
65 VTable,
66 /// The version of a method that is stored in a vtable.
67 VTableMethod,
68 /// The `drop_in_place` shim stored in a vtable.
69 VTableDropShim,
70 /// The fallback body of an intrinsic.
71 IntrinsicFallback,
72}
73
74/// There are two kinds of `impl` blocks:
75/// - impl blocks linked to a type ("inherent" impl blocks following Rust terminology):
76/// ```text
77/// impl<T> List<T> { ...}
78/// ```
79/// - trait impl blocks:
80/// ```text
81/// impl<T> PartialEq for List<T> { ...}
82/// ```
83/// We distinguish the two.
84#[derive(Debug, Clone, PartialEq, Eq, Hash)]
85#[derive(EnumAsInner)]
86#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
87#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("ImplElem"))]
88pub enum ImplElem {
89 Ty(Box<Binder<Ty>>),
90 Trait(TraitImplId),
91}
92
93/// An item name/path
94///
95/// A name really is a list of strings. However, we sometimes need to
96/// introduce unique indices to disambiguate. This mostly happens because
97/// of "impl" blocks:
98/// ```text
99/// impl<T> List<T> {
100/// ...
101/// }
102/// ```
103///
104/// A type in Rust can have several "impl" blocks, and those blocks can
105/// contain items with similar names. For this reason, we need to disambiguate
106/// them with unique indices. Rustc calls those "disambiguators". In rustc, this
107/// gives names like this:
108/// - `betree_main::betree::NodeIdCounter{impl#0}::new`
109/// - note that impl blocks can be nested, and macros sometimes generate
110/// weird names (which require disambiguation):
111/// `betree_main::betree_utils::_#1::{impl#0}::deserialize::{impl#0}`
112///
113/// Finally, the paths used by rustc are a lot more precise and explicit than
114/// those we expose in LLBC: for instance, every identifier belongs to a specific
115/// namespace (value namespace, type namespace, etc.), and is coupled with a
116/// disambiguator.
117///
118/// On our side, we want to stay high-level and simple: we use string identifiers
119/// as much as possible, insert disambiguators only when necessary (for instance
120/// when we find an "impl" block or when two loaded crates have the same name)
121/// and check that the disambiguator is useless in the other situations (i.e.,
122/// the disambiguator is always equal to 0).
123///
124/// Moreover, the items are uniquely disambiguated by their (integer) ids
125/// (`TypeDeclId`, etc.), and when extracting the code we have to deal with
126/// name clashes anyway. Still, we might want to be more precise in the future.
127///
128/// Also note that the first path element in the name is always the crate name.
129#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
130#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
131#[serde(transparent)]
132#[cfg_attr(feature = "charon_on_charon", charon::transparent)]
133pub struct Name {
134 pub name: Vec<PathElem>,
135}
136
137impl PathElem {
138 fn equals_ident(&self, id: &str) -> bool {
139 match self {
140 PathElem::Ident(s, d) => s == id && d.is_zero(),
141 _ => false,
142 }
143 }
144
145 pub fn as_monomorphized(&self) -> Option<&GenericArgs> {
146 let binder = self.as_instantiated()?;
147 binder.params.is_empty().then_some(&binder.skip_binder)
148 }
149 pub fn as_monomorphized_mut(&mut self) -> Option<&mut GenericArgs> {
150 let binder = self.as_instantiated_mut()?;
151 binder.params.is_empty().then_some(&mut binder.skip_binder)
152 }
153 pub fn is_monomorphized(&self) -> bool {
154 self.as_monomorphized().is_some()
155 }
156}
157
158impl Name {
159 /// Convert a path like `["std", "alloc", "Box"]` to a name. Needed on occasion when crafting
160 /// names that were not present in the original code.
161 pub fn from_path(path: &[&str]) -> Name {
162 Name {
163 name: path
164 .iter()
165 .map(|elem| PathElem::Ident(elem.to_string(), Disambiguator::ZERO))
166 .collect(),
167 }
168 }
169
170 #[allow(clippy::len_without_is_empty)]
171 pub fn len(&self) -> usize {
172 self.name.len()
173 }
174
175 /// If this item comes from monomorphization, return the arguments used.
176 pub fn mono_args(&self) -> Option<&GenericArgs> {
177 self.name.last()?.as_monomorphized()
178 }
179 /// If this item comes from monomorphization, return the arguments used.
180 pub fn mono_args_mut(&mut self) -> Option<&mut GenericArgs> {
181 self.name.last_mut()?.as_monomorphized_mut()
182 }
183
184 /// Strip the trailing `PathElem::Target` from a name, if any.
185 pub fn strip_target_suffix(&self) -> Option<(Name, TargetTriple)> {
186 match self.name.last() {
187 Some(PathElem::Target(target)) => {
188 let target = target.clone();
189 let mut base = self.clone();
190 base.name.pop();
191 Some((base, target))
192 }
193 _ => None,
194 }
195 }
196
197 /// Returns this name with the `PathElem::Instantiated` part removed, if it has one.
198 pub fn as_slice_uninstantiated(&self) -> &[PathElem] {
199 match self.name.as_slice() {
200 [name @ .., PathElem::Instantiated(_)] => name,
201 name => name,
202 }
203 }
204
205 /// Compare the name to a constant array.
206 /// This ignores disambiguators.
207 ///
208 /// `equal`: if `true`, check that the name is equal to the ref. If `false`:
209 /// only check if the ref is a prefix of the name.
210 pub fn compare_with_ref_name(&self, equal: bool, ref_name: &[&str]) -> bool {
211 let name: Vec<&PathElem> = self.name.iter().filter(|e| e.is_ident()).collect();
212
213 if name.len() < ref_name.len() || (equal && name.len() != ref_name.len()) {
214 return false;
215 }
216
217 for i in 0..ref_name.len() {
218 if !name[i].equals_ident(ref_name[i]) {
219 return false;
220 }
221 }
222 true
223 }
224
225 /// Compare the name to a constant array.
226 /// This ignores disambiguators.
227 pub fn equals_ref_name(&self, ref_name: &[&str]) -> bool {
228 self.compare_with_ref_name(true, ref_name)
229 }
230
231 /// Created an instantiated version of this name by putting a `PathElem::Instantiated` last. If
232 /// the item was already instantiated, this merges the two instantiations.
233 pub fn instantiate(mut self, binder: Binder<GenericArgs>) -> Self {
234 if let [.., PathElem::Instantiated(x)] = self.name.as_mut_slice() {
235 // Put the new args in place; the params are what we want but the args are wrong.
236 let old_args = std::mem::replace(x.as_mut(), binder);
237 // Apply the new args to the old binder to get correct args.
238 x.skip_binder = old_args.apply(&x.skip_binder);
239 } else {
240 self.name.push(PathElem::Instantiated(Box::new(binder)));
241 }
242 self
243 }
244
245 /// Whether this names one of the items Rust builds into the language (tuples, `str`, arrays,
246 /// slices) or an item we generate for one, such as its drop glue. They belong to no crate, so
247 /// their name starts either with the builtin itself or with the `impl` block we generated for them.
248 pub fn is_builtin(&self) -> bool {
249 matches!(
250 self.name.first(),
251 Some(PathElem::Builtin(..) | PathElem::Impl(_))
252 )
253 }
254
255 /// Get the last identifier of the name, if any. This is useful for error messages and such.
256 /// Returns `None` if the name is empty or if the last element has no identifier to give.
257 pub fn short_str(&self) -> Option<&str> {
258 match self.name.last()? {
259 PathElem::Builtin(builtin, _) => Some(builtin.ident()),
260 PathElem::Ident(str, _) => Some(str),
261 _ => None,
262 }
263 }
264
265 /// `Name` is a complex datastructure; to inspect it we serialize it a little bit.
266 /// This must only be used for debug printing; it is not reliable or exact.
267 pub fn debug_repr(&self, crate_data: &TranslatedCrate) -> String {
268 // Small helper
269 let trait_name = |impl_id: TraitImplId| {
270 let timpl = crate_data.trait_impls.get(impl_id)?;
271 let (name, _) = crate_data
272 .trait_decls
273 .get(timpl.impl_trait.id)?
274 .item_meta
275 .name
276 .name
277 .last()?
278 .as_ident()?;
279 let negative = if timpl.is_negative { "!" } else { "" };
280 Some(format!("{negative}{name}"))
281 };
282
283 self.name
284 .iter()
285 .map(|path_elem| match path_elem {
286 PathElem::Ident(i, _) => i.clone(),
287 PathElem::Impl(elem) => match elem {
288 ImplElem::Trait(impl_id) => match trait_name(*impl_id) {
289 None => format!("<trait impl#{impl_id}>"),
290 Some(name) => format!("<impl {name} for ??>"),
291 },
292 ImplElem::Ty(..) => "<inherent impl>".to_string(),
293 },
294 PathElem::Instantiated(..) => "<mono>".to_string(),
295 PathElem::Target(target) => target.clone(),
296 PathElem::Builtin(builtin, _) => format!("<{}>", builtin.ident()),
297 })
298 .join("::")
299 }
300}
301
302impl BuiltinPathElem {
303 /// If this builtin name is also how Rust refers to the item, in which case we don't
304 /// need to put braces around the name, as it is part of the actual path of the item.
305 pub fn is_rust_name(self) -> bool {
306 matches!(
307 self,
308 BuiltinPathElem::Str | BuiltinPathElem::Tuple(_) | BuiltinPathElem::DropGlue
309 )
310 }
311
312 /// The identifier we use to refer to this element.
313 pub fn ident(self) -> &'static str {
314 match self {
315 BuiltinPathElem::Tuple(0) => "unit",
316 BuiltinPathElem::Tuple(_) => "tuple",
317 BuiltinPathElem::Str => "str",
318 BuiltinPathElem::Closure => "closure",
319 BuiltinPathElem::Use => "use",
320 BuiltinPathElem::AnonConst => "const",
321 BuiltinPathElem::PromotedConst => "promoted_const",
322 BuiltinPathElem::ClosureAsFn => "as_fn",
323 BuiltinPathElem::DropGlue => "drop_glue",
324 BuiltinPathElem::VTable => "vtable",
325 BuiltinPathElem::VTableMethod => "vtable_method",
326 BuiltinPathElem::VTableDropShim => "vtable_drop_shim",
327 BuiltinPathElem::IntrinsicFallback => "fallback",
328 }
329 }
330}