cairo_lang_syntax/node/
ids.rs

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