cairo_lang_syntax/node/
ids.rs

1use cairo_lang_filesystem::ids::{FileId, SpanInFile};
2use cairo_lang_filesystem::span::TextWidth;
3use cairo_lang_utils::define_short_id;
4use salsa::Database;
5
6use super::SyntaxNode;
7use super::green::GreenNode;
8use super::kind::SyntaxKind;
9
10define_short_id!(GreenId, GreenNode<'db>);
11impl<'a> GreenId<'a> {
12    /// Returns the width of the node of this green id.
13    pub fn width(&self, db: &dyn Database) -> TextWidth {
14        match &self.long(db).details {
15            super::green::GreenNodeDetails::Token(text) => TextWidth::from_str(text.long(db)),
16            super::green::GreenNodeDetails::Node { width, .. } => *width,
17        }
18    }
19}
20
21#[derive(Copy, Debug, Clone, PartialEq, Eq, Hash, salsa::Update)]
22pub struct SyntaxStablePtrId<'a>(pub SyntaxNode<'a>);
23
24impl<'a> SyntaxStablePtrId<'a> {
25    /// Lookups a syntax node using a stable syntax pointer.
26    /// Should only be called on the root from which the stable pointer was generated.
27    pub fn lookup(&self, _db: &'a dyn Database) -> SyntaxNode<'a> {
28        self.0
29    }
30    pub fn file_id(&self, db: &'a dyn Database) -> FileId<'a> {
31        self.0.file_id(db)
32    }
33    /// Returns the stable pointer of the parent of this stable pointer.
34    /// Assumes that the parent exists (that is, `self` is not the root). Panics otherwise.
35    pub fn parent<'r: 'a>(&self, db: &'r dyn Database) -> SyntaxStablePtrId<'a> {
36        SyntaxStablePtrId(self.0.parent(db).unwrap())
37    }
38    /// Returns the stable pointer of the `n`th parent of this stable pointer.
39    /// n = 0: returns itself.
40    /// n = 1: return the parent.
41    /// n = 2: return the grandparent.
42    /// And so on...
43    /// Assumes that the `n`th parent exists. Panics otherwise.
44    pub fn nth_parent<'r: 'a>(&self, db: &'r dyn Database, n: usize) -> SyntaxStablePtrId<'a> {
45        SyntaxStablePtrId(self.0.nth_parent(db, n))
46    }
47    /// Returns the kind of this stable pointer.
48    /// Assumes that `self` is not the root. Panics otherwise.
49    pub fn kind(&self, db: &'a dyn Database) -> SyntaxKind {
50        self.0.kind(db)
51    }
52    /// Returns the span in file of this stable pointer without trivia.
53    pub fn span_in_file(&self, db: &'a dyn Database) -> SpanInFile<'a> {
54        SpanInFile { file_id: self.file_id(db), span: self.lookup(db).span_without_trivia(db) }
55    }
56}