Skip to main content

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        self.long(db).width(db)
16    }
17}
18
19#[derive(Copy, Debug, Clone, PartialEq, Eq, Hash, salsa::Update, HeapSize)]
20pub struct SyntaxStablePtrId<'a>(pub SyntaxNode<'a>);
21
22impl<'a> SyntaxStablePtrId<'a> {
23    /// Looks up a syntax node using a stable syntax pointer.
24    /// Should only be called on the root from which the stable pointer was generated.
25    pub fn lookup(&self, _db: &'a dyn Database) -> SyntaxNode<'a> {
26        self.0
27    }
28    pub fn file_id(&self, db: &'a dyn Database) -> FileId<'a> {
29        self.0.file_id(db)
30    }
31    /// Returns the stable pointer of the parent of this stable pointer.
32    /// Assumes that the parent exists (that is, `self` is not the root). Panics otherwise.
33    pub fn parent<'r: 'a>(&self, db: &'r dyn Database) -> SyntaxStablePtrId<'a> {
34        SyntaxStablePtrId(self.0.parent(db).unwrap())
35    }
36    /// Returns the stable pointer of the `n`th parent of this stable pointer.
37    /// n = 0: returns itself.
38    /// n = 1: returns the parent.
39    /// n = 2: returns the grandparent.
40    /// And so on...
41    /// Assumes that the `n`th parent exists. Panics otherwise.
42    pub fn nth_parent<'r: 'a>(&self, db: &'r dyn Database, n: usize) -> SyntaxStablePtrId<'a> {
43        SyntaxStablePtrId(self.0.nth_parent(db, n))
44    }
45    /// Returns the kind of this stable pointer.
46    /// Assumes that `self` is not the root. Panics otherwise.
47    pub fn kind(&self, db: &'a dyn Database) -> SyntaxKind {
48        self.0.kind(db)
49    }
50    /// Returns the span in file of this stable pointer without trivia.
51    pub fn span_in_file(&self, db: &'a dyn Database) -> SpanInFile<'a> {
52        SpanInFile { file_id: self.file_id(db), span: self.lookup(db).span_without_trivia(db) }
53    }
54}