cuda_rust_wasm/transpiler/
ast.rs

1//! AST types for CUDA to Rust transpilation
2
3use std::fmt;
4
5/// For loop initialization type
6#[derive(Debug, Clone, PartialEq)]
7pub enum ForInit {
8    /// Variable declaration: int i = 0
9    VarDecl { name: String, ty: String, init: Box<Expr> },
10    /// Expression: i = 0
11    Expr(Box<Expr>),
12}
13
14/// Expression type
15#[derive(Debug, Clone, PartialEq)]
16pub enum Expr {
17    Literal(String),
18    Identifier(String),
19    Binary { op: String, left: Box<Expr>, right: Box<Expr> },
20    Unary { op: String, expr: Box<Expr> },
21    Call { name: String, args: Vec<Expr> },
22    Index { expr: Box<Expr>, index: Box<Expr> },
23    Member { expr: Box<Expr>, member: String },
24}
25
26/// Statement type
27#[derive(Debug, Clone, PartialEq)]
28pub enum Stmt {
29    Expression(Expr),
30    Assignment { lhs: Expr, rhs: Expr },
31    VarDecl { name: String, ty: String, init: Option<Expr> },
32    If { cond: Expr, then_stmt: Box<Stmt>, else_stmt: Option<Box<Stmt>> },
33    For { init: ForInit, cond: Expr, update: Expr, body: Box<Stmt> },
34    While { cond: Expr, body: Box<Stmt> },
35    Block(Vec<Stmt>),
36    Return(Option<Expr>),
37    Break,
38    Continue,
39}
40
41/// Function definition
42#[derive(Debug, Clone, PartialEq)]
43pub struct Function {
44    pub name: String,
45    pub params: Vec<(String, String)>,
46    pub return_type: String,
47    pub body: Vec<Stmt>,
48    pub is_kernel: bool,
49}
50
51/// AST root
52#[derive(Debug, Clone, PartialEq)]
53pub struct Program {
54    pub functions: Vec<Function>,
55    pub globals: Vec<Stmt>,
56}
57
58impl fmt::Display for ForInit {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        match self {
61            ForInit::VarDecl { name, ty, init } => write!(f, "{ty} {name} = {init:?}"),
62            ForInit::Expr(expr) => write!(f, "{expr:?}"),
63        }
64    }
65}