cl_ast/ast_impl/
path.rs

1//! Utils for [Path]
2use crate::{PathPart, Sym, ast::Path};
3
4impl Path {
5    /// Appends a [PathPart] to this [Path]
6    pub fn push(&mut self, part: PathPart) {
7        self.parts.push(part);
8    }
9    /// Removes a [PathPart] from this [Path]
10    pub fn pop(&mut self) -> Option<PathPart> {
11        self.parts.pop()
12    }
13    /// Concatenates `self::other`. If `other` is an absolute [Path],
14    /// this replaces `self` with `other`
15    pub fn concat(mut self, other: &Self) -> Self {
16        if other.absolute {
17            other.clone()
18        } else {
19            self.parts.extend(other.parts.iter().cloned());
20            self
21        }
22    }
23
24    /// Gets the defining [Sym] of this path
25    pub fn as_sym(&self) -> Option<Sym> {
26        match self.parts.as_slice() {
27            [.., PathPart::Ident(name)] => Some(*name),
28            _ => None,
29        }
30    }
31
32    /// Checks whether this path ends in the given [Sym]
33    pub fn ends_with(&self, name: &str) -> bool {
34        match self.parts.as_slice() {
35            [.., PathPart::Ident(last)] => name == &**last,
36            _ => false,
37        }
38    }
39
40    /// Checks whether this path refers to the sinkhole identifier, `_`
41    pub fn is_sinkhole(&self) -> bool {
42        if let [PathPart::Ident(id)] = self.parts.as_slice() {
43            if let "_" = id.to_ref() {
44                return true;
45            }
46        }
47        false
48    }
49}
50impl PathPart {
51    pub fn from_sym(ident: Sym) -> Self {
52        Self::Ident(ident)
53    }
54}
55
56impl From<Sym> for Path {
57    fn from(value: Sym) -> Self {
58        Self { parts: vec![PathPart::Ident(value)], absolute: false }
59    }
60}