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::names::*;
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            PathElem::Impl(..) => 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    /// Compare the name to a constant array.
34    /// This ignores disambiguators.
35    ///
36    /// `equal`: if `true`, check that the name is equal to the ref. If `false`:
37    /// only check if the ref is a prefix of the name.
38    pub fn compare_with_ref_name(&self, equal: bool, ref_name: &[&str]) -> bool {
39        let name: Vec<&PathElem> = self.name.iter().filter(|e| e.is_ident()).collect();
40
41        if name.len() < ref_name.len() || (equal && name.len() != ref_name.len()) {
42            return false;
43        }
44
45        for i in 0..ref_name.len() {
46            if !name[i].equals_ident(ref_name[i]) {
47                return false;
48            }
49        }
50        true
51    }
52
53    /// Compare the name to a constant array.
54    /// This ignores disambiguators.
55    pub fn equals_ref_name(&self, ref_name: &[&str]) -> bool {
56        self.compare_with_ref_name(true, ref_name)
57    }
58}