ast/
lib.rs

1//! # Abstract Syntax Tree (AST) Module
2//!
3//! The AST module contains the definitions for the abstract syntax tree (AST) nodes
4//! generated by the parser. The AST nodes are used to represent the structure of the
5//! source code in a tree-like format, which can be used to perform various analysis
6//! and evaluation tasks on the code.
7//!
8//! The AST nodes are defined as Rust structs, and are serialisable to JSON using the
9//! `serde` library. This allows the AST to be easily converted to a JSON string for
10//! debugging and analysis purposes.
11//!
12//! The AST module is divided into sub-modules, each of which contains the definitions
13//! for a specific type of AST node, such as expressions, statements, and literals.
14//!
15//! The AST module also contains a `Program` struct, which is the root node for all
16//! syntax trees generated by the parser. The `Program` struct contains a list of
17//! statements, which represent the top-level statements in the source code.
18pub mod expression;
19pub mod literal;
20pub mod statement;
21pub mod tostring;
22
23use serde::Serialize;
24use shared::span::Span;
25use statement::Statement;
26
27/// Converts an AST node to a JSON string representation.
28///
29/// # Arguments
30///
31/// * `node` - The AST node to convert.
32///
33/// # Returns
34///
35/// Returns a Result containing the JSON string representation of the AST node, or an
36/// error if the conversion fails.
37pub fn ast_to_json<T>(node: &T) -> Result<String, serde_json::error::Error>
38where
39    T: ?Sized + Serialize,
40{
41    serde_json::to_string_pretty(&node)
42}
43
44/// Represents a whole program source file in the SAP language. It is the root node for
45/// all syntax trees generated by the parser.
46#[derive(Debug, Serialize)]
47#[serde(tag = "type")]
48pub struct Program {
49    pub statements: Vec<Statement>,
50    pub span: Span,
51}
52
53impl Program {
54    /// Creates a new instance of the Program struct.
55    ///
56    /// Note: `span.end` is set to 0
57    pub fn new() -> Self {
58        Self {
59            statements: vec![],
60            span: Span { start: 0, end: 0 },
61        }
62    }
63}
64
65/// Represents a list of statements. It is used to store a list of statements for an
66/// entire program, or for a block of code within a function or selection statement.
67#[derive(Debug, Serialize, PartialEq, Clone)]
68pub struct StatementList {
69    pub statements: Vec<Statement>,
70    pub span: Span,
71}
72
73impl StatementList {
74    /// Creates a new instance of the Block struct.
75    ///
76    /// Note: `span.end` is set to 0
77    pub fn new() -> Self {
78        Self {
79            statements: vec![],
80            span: Span { start: 0, end: 0 },
81        }
82    }
83}