Skip to main content

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    pub fn as_monomorphized(&self) -> Option<&GenericArgs> {
16        let binder = self.as_instantiated()?;
17        binder.params.is_empty().then_some(&binder.skip_binder)
18    }
19    pub fn is_monomorphized(&self) -> bool {
20        self.as_monomorphized().is_some()
21    }
22}
23
24impl Name {
25    /// Convert a path like `["std", "alloc", "Box"]` to a name. Needed on occasion when crafting
26    /// names that were not present in the original code.
27    pub fn from_path(path: &[&str]) -> Name {
28        Name {
29            name: path
30                .iter()
31                .map(|elem| PathElem::Ident(elem.to_string(), Disambiguator::ZERO))
32                .collect(),
33        }
34    }
35
36    #[allow(clippy::len_without_is_empty)]
37    pub fn len(&self) -> usize {
38        self.name.len()
39    }
40
41    /// If this item comes from monomorphization, return the arguments used.
42    pub fn mono_args(&self) -> Option<&GenericArgs> {
43        self.name.last()?.as_monomorphized()
44    }
45
46    /// Strip the trailing `PathElem::Target` from a name, if any.
47    pub fn strip_target_suffix(&self) -> Option<(Name, TargetTriple)> {
48        match self.name.last() {
49            Some(PathElem::Target(target)) => {
50                let target = target.clone();
51                let mut base = self.clone();
52                base.name.pop();
53                Some((base, target))
54            }
55            _ => None,
56        }
57    }
58
59    /// Compare the name to a constant array.
60    /// This ignores disambiguators.
61    ///
62    /// `equal`: if `true`, check that the name is equal to the ref. If `false`:
63    /// only check if the ref is a prefix of the name.
64    pub fn compare_with_ref_name(&self, equal: bool, ref_name: &[&str]) -> bool {
65        let name: Vec<&PathElem> = self.name.iter().filter(|e| e.is_ident()).collect();
66
67        if name.len() < ref_name.len() || (equal && name.len() != ref_name.len()) {
68            return false;
69        }
70
71        for i in 0..ref_name.len() {
72            if !name[i].equals_ident(ref_name[i]) {
73                return false;
74            }
75        }
76        true
77    }
78
79    /// Compare the name to a constant array.
80    /// This ignores disambiguators.
81    pub fn equals_ref_name(&self, ref_name: &[&str]) -> bool {
82        self.compare_with_ref_name(true, ref_name)
83    }
84
85    /// Created an instantiated version of this name by putting a `PathElem::Instantiated` last. If
86    /// the item was already instantiated, this merges the two instantiations.
87    pub fn instantiate(mut self, binder: Binder<GenericArgs>) -> Self {
88        if let [.., PathElem::Instantiated(box x)] = self.name.as_mut_slice() {
89            // Put the new args in place; the params are what we want but the args are wrong.
90            let old_args = std::mem::replace(x, binder);
91            // Apply the new args to the old binder to get correct args.
92            x.skip_binder = old_args.apply(&x.skip_binder);
93        } else {
94            self.name.push(PathElem::Instantiated(Box::new(binder)));
95        }
96        self
97    }
98
99    /// Get the last identifier of the name, if any. This is useful for error messages and such.
100    /// Panics if the name is empty or if the last element is not an identifier.
101    pub fn short_str(&self) -> &String {
102        self.name.last().unwrap().as_ident().unwrap().0
103    }
104}