charon_lib/ast/
names_utils.rs

1//! Defines some utilities for [crate::names]
2//!
3//! For now, we have one function per object kind (type, trait, function,
4//! module): many of them could be factorized (will do).
5use crate::ast::*;
6
7impl PathElem {
8    fn equals_ident(&self, id: &str) -> bool {
9        match self {
10            PathElem::Ident(s, d) => s == id && d.is_zero(),
11            _ => false,
12        }
13    }
14}
15
16impl Name {
17    /// Convert a path like `["std", "alloc", "Box"]` to a name. Needed on occasion when crafting
18    /// names that were not present in the original code.
19    pub(crate) fn from_path(path: &[&str]) -> Name {
20        Name {
21            name: path
22                .iter()
23                .map(|elem| PathElem::Ident(elem.to_string(), Disambiguator::ZERO))
24                .collect(),
25        }
26    }
27
28    #[allow(clippy::len_without_is_empty)]
29    pub fn len(&self) -> usize {
30        self.name.len()
31    }
32
33    /// If this item comes from monomorphization, return the arguments used.
34    pub fn mono_args(&self) -> Option<&GenericArgs> {
35        Some(self.name.last()?.as_monomorphized()?.as_ref())
36    }
37
38    /// Compare the name to a constant array.
39    /// This ignores disambiguators.
40    ///
41    /// `equal`: if `true`, check that the name is equal to the ref. If `false`:
42    /// only check if the ref is a prefix of the name.
43    pub fn compare_with_ref_name(&self, equal: bool, ref_name: &[&str]) -> bool {
44        let name: Vec<&PathElem> = self.name.iter().filter(|e| e.is_ident()).collect();
45
46        if name.len() < ref_name.len() || (equal && name.len() != ref_name.len()) {
47            return false;
48        }
49
50        for i in 0..ref_name.len() {
51            if !name[i].equals_ident(ref_name[i]) {
52                return false;
53            }
54        }
55        true
56    }
57
58    /// Compare the name to a constant array.
59    /// This ignores disambiguators.
60    pub fn equals_ref_name(&self, ref_name: &[&str]) -> bool {
61        self.compare_with_ref_name(true, ref_name)
62    }
63}