From 8f4d626968f51ba7193fbf1b2c6f313a48b7732c Mon Sep 17 00:00:00 2001 From: janis Date: Wed, 29 Oct 2025 22:10:34 +0100 Subject: [PATCH] ast tests --- lang/tests/ast.rs | 69 +++++++++++++++++++++++++++-------------------- 1 file changed, 40 insertions(+), 29 deletions(-) diff --git a/lang/tests/ast.rs b/lang/tests/ast.rs index 7a008d4..1f00627 100644 --- a/lang/tests/ast.rs +++ b/lang/tests/ast.rs @@ -1,40 +1,14 @@ #[path = "shared/shared.rs"] mod util; -#[repr(C)] -struct Ast { - nodes: util::vec::Vec, -} - -#[repr(C)] -struct Argument { - name: *const u8, - name_len: usize, - arg_type: u8, -} - -#[repr(C)] -#[derive(Debug)] -struct AstNode { - node_type: u8, - data: usize, -} - -use util::FFISlice; - unsafe extern "C" { unsafe fn bump_init(); - unsafe fn parse_func(ast: *mut Ast) -> u64; - unsafe fn parse_args(ast: *mut Ast) -> FFISlice; - unsafe fn parse_expr(ast: *mut Ast) -> u64; - unsafe fn parse_binary_expr(ast: *mut Ast) -> u64; - unsafe fn parse_primary_expr(ast: *mut Ast) -> u64; - unsafe fn parse_statement(ast: *mut Ast) -> u64; - unsafe fn parse_block(ast: *mut Ast) -> u64; unsafe fn tokeniser_init_buf(bytes: *const u8, len: usize) -> (); } +use util::defs::{parse_expr, Ast, AstNode}; + fn main() { unsafe { bump_init(); @@ -50,6 +24,43 @@ fn main() { }; let expr_id = parse_expr(&mut ast); println!("Parsed expression with ID: {}", expr_id); - println!("{:#?}", ast.nodes.as_slice()); + println!("{:#}", &ast); + } +} + +impl std::fmt::Display for AstNode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + use util::defs::{BinaryExpr, AST_BINARY_OP, AST_NUMBER}; + match self.kind as u32 { + AST_NUMBER => { + write!(f, "Number({})", self.data as usize) + } + AST_BINARY_OP => { + let BinaryExpr { + left, + operator, + right, + } = unsafe { self.data.cast::().read() }; + write!( + f, + "BinaryOp(op: {}, left: {}, right: {})", + operator, left, right + ) + } + _ => write!(f, "UnknownNode"), + } + } +} + +impl core::fmt::Display for Ast { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + writeln!(f, "[")?; + for (i, item) in self.nodes.as_slice().iter().enumerate() { + if i > 0 { + writeln!(f, ", ")?; + } + write!(f, "\t{i}: {}", item)?; + } + writeln!(f, "\n]") } }