Skip to main content

wright/ast/
path.rs

1//! [Path]s are used in import statements, and can take the place of an [Identifier] in many places.
2
3use super::{AstNode, identifier::Identifier};
4use crate::source_tracking::fragment::Fragment;
5
6/// A double-colon separated path/reference to a module/function. This can be used in an `import` declaration and
7/// some other places. [Path]s with length of 1 are just [Identifier]s -- [Identifier]s can be considered paths in some
8/// instances.
9#[derive(Debug, Clone, PartialEq)]
10pub struct Path {
11    /// The [Fragment] of source code containing the full source of this path (including the double-colon separators).
12    pub full_path: Fragment,
13
14    /// The first (left-most) identifier in this [Path]. This can also be considered the "root" of the path --
15    /// the module that the following item/identifier can be found in.
16    pub head: Identifier,
17
18    /// The rest of the [Path], following the first separator.
19    pub tail: Vec<Identifier>,
20}
21
22impl Path {
23    /// Iterate over all the segments of this path, starting with [Path::head].
24    pub fn segments(&self) -> impl Iterator<Item = &Identifier> {
25        std::iter::once(&self.head).chain(self.tail.iter())
26    }
27
28    /// Get the last segment of this path (the name of the item it refers to).
29    pub fn last(&self) -> &Identifier {
30        self.tail.last().unwrap_or(&self.head)
31    }
32
33    /// If this path is a single identifier, get it.
34    pub fn as_identifier(&self) -> Option<&Identifier> {
35        self.tail.is_empty().then_some(&self.head)
36    }
37}
38
39impl AstNode for Path {
40    fn matching_source(&self) -> &Fragment {
41        &self.full_path
42    }
43}