lemma/
ast.rs

1//! AST infrastructure types
2//!
3//! This module contains metadata types used throughout the parser and compiler:
4//! - `Span` for tracking source code locations
5//! - `ExpressionId` for uniquely identifying AST nodes
6//! - `ExpressionIdGenerator` for generating unique IDs during parsing
7
8use std::fmt;
9
10/// Span representing a location in source code
11#[derive(Debug, Clone, PartialEq, Eq, Hash)]
12pub struct Span {
13    pub start: usize,
14    pub end: usize,
15    pub line: usize,
16    pub col: usize,
17}
18
19impl Span {
20    pub fn from_pest_span(span: pest::Span) -> Self {
21        let (line, col) = span.start_pos().line_col();
22        Self {
23            start: span.start(),
24            end: span.end(),
25            line,
26            col,
27        }
28    }
29}
30
31/// Unique identifier for each expression in the AST
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33pub struct ExpressionId(u64);
34
35impl ExpressionId {
36    pub fn new(id: u64) -> Self {
37        Self(id)
38    }
39}
40
41impl fmt::Display for ExpressionId {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        write!(f, "expr_{}", self.0)
44    }
45}
46
47/// Counter for generating unique expression IDs
48pub struct ExpressionIdGenerator {
49    next_id: u64,
50}
51
52impl ExpressionIdGenerator {
53    pub fn new() -> Self {
54        Self { next_id: 0 }
55    }
56
57    pub fn next_id(&mut self) -> ExpressionId {
58        let id = ExpressionId(self.next_id);
59        self.next_id += 1;
60        id
61    }
62}
63
64impl Default for ExpressionIdGenerator {
65    fn default() -> Self {
66        Self::new()
67    }
68}