dev/prometeuc-improvements (#5)
Co-authored-by: Nilton Constantino <nilton.constantino@visma.com> Reviewed-on: #5
This commit was merged in pull request #5.
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
use oxc_ast::ast::*;
|
||||
use anyhow::{Result, anyhow};
|
||||
|
||||
pub fn get_callee_name(expr: &Expression) -> Result<String> {
|
||||
get_member_expr_name(expr)
|
||||
}
|
||||
|
||||
pub fn get_member_expr_name(expr: &Expression) -> Result<String> {
|
||||
match expr {
|
||||
Expression::Identifier(ident) => {
|
||||
let name = ident.name.to_string();
|
||||
// Remove prefix 'P' if it's followed by an uppercase letter (e.g., PGfx -> Gfx)
|
||||
if name.len() > 1 && name.starts_with('P') && name.chars().nth(1).unwrap().is_uppercase() {
|
||||
Ok(name[1..].to_string())
|
||||
} else {
|
||||
Ok(name)
|
||||
}
|
||||
}
|
||||
Expression::StaticMemberExpression(member) => {
|
||||
let obj = get_member_expr_name(&member.object)?;
|
||||
let prop = member.property.name.to_string();
|
||||
Ok(format!("{}.{}", obj, prop))
|
||||
}
|
||||
_ => Err(anyhow!("Unsupported expression")),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,507 @@
|
||||
use anyhow::{Result, anyhow};
|
||||
use oxc_ast::ast::*;
|
||||
use oxc_span::{Span, GetSpan};
|
||||
use prometeu_bytecode::opcode::OpCode;
|
||||
use prometeu_bytecode::asm::{Asm, Operand, assemble};
|
||||
use prometeu_bytecode::pbc::{ConstantPoolEntry, PbcFile, write_pbc};
|
||||
use crate::compiler::Symbol;
|
||||
use crate::syscall_map;
|
||||
use crate::codegen::ast_util;
|
||||
use prometeu_core::prometeu_os::Syscall;
|
||||
use std::collections::HashMap;
|
||||
use prometeu_bytecode::asm;
|
||||
use prometeu_core::model::Color;
|
||||
|
||||
pub struct Codegen {
|
||||
file_name: String,
|
||||
source_text: String,
|
||||
pub symbols: Vec<Symbol>,
|
||||
instructions: Vec<(Asm, bool)>, // (Asm, has_symbol)
|
||||
locals: HashMap<String, u32>,
|
||||
constant_pool: Vec<ConstantPoolEntry>,
|
||||
next_local: u32,
|
||||
label_count: u32,
|
||||
}
|
||||
|
||||
impl Codegen {
|
||||
pub fn new(file_name: String, source_text: String) -> Self {
|
||||
Self {
|
||||
file_name,
|
||||
source_text,
|
||||
symbols: Vec::new(),
|
||||
instructions: Vec::new(),
|
||||
locals: HashMap::new(),
|
||||
constant_pool: vec![ConstantPoolEntry::Null], // Index 0 is always Null
|
||||
next_local: 0,
|
||||
label_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn add_constant(&mut self, entry: ConstantPoolEntry) -> u32 {
|
||||
if let Some(pos) = self.constant_pool.iter().position(|e| e == &entry) {
|
||||
pos as u32
|
||||
} else {
|
||||
let pos = self.constant_pool.len();
|
||||
self.constant_pool.push(entry);
|
||||
pos as u32
|
||||
}
|
||||
}
|
||||
|
||||
pub fn compile_program(&mut self, program: &Program) -> Result<Vec<u8>> {
|
||||
self.compile_programs(vec![(self.file_name.clone(), self.source_text.clone(), program)])
|
||||
}
|
||||
|
||||
pub fn compile_programs(&mut self, programs: Vec<(String, String, &Program)>) -> Result<Vec<u8>> {
|
||||
// First pass: collect all functions and their indices
|
||||
let mut all_functions = Vec::new();
|
||||
for (file, source, program) in &programs {
|
||||
for item in &program.body {
|
||||
match item {
|
||||
Statement::FunctionDeclaration(f) => {
|
||||
all_functions.push((file.clone(), source.clone(), f.as_ref()));
|
||||
}
|
||||
Statement::ExportNamedDeclaration(decl) => {
|
||||
if let Some(Declaration::FunctionDeclaration(f)) = &decl.declaration {
|
||||
all_functions.push((file.clone(), source.clone(), f.as_ref()));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Find tick function (should be in the first program, which is the entry)
|
||||
let mut tick_fn_name = None;
|
||||
if let Some((_, _, entry_program)) = programs.first() {
|
||||
for item in &entry_program.body {
|
||||
let f_opt = match item {
|
||||
Statement::FunctionDeclaration(f) => Some(f.as_ref()),
|
||||
Statement::ExportNamedDeclaration(decl) => {
|
||||
if let Some(Declaration::FunctionDeclaration(f)) = &decl.declaration {
|
||||
Some(f.as_ref())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(f) = f_opt {
|
||||
if let Some(ident) = &f.id {
|
||||
if ident.name == "tick" {
|
||||
tick_fn_name = Some(ident.name.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let tick_fn_name = tick_fn_name.ok_or_else(|| anyhow!("export function tick() not found in entry file"))?;
|
||||
|
||||
// Entry point: loop calling tick
|
||||
self.emit_label("entry".to_string());
|
||||
self.emit_op(OpCode::Call, vec![Operand::Label(tick_fn_name), Operand::U32(0)], Span::default());
|
||||
self.emit_op(OpCode::Pop, vec![], Span::default());
|
||||
self.emit_op(OpCode::FrameSync, vec![], Span::default());
|
||||
self.emit_op(OpCode::Jmp, vec![Operand::Label("entry".to_string())], Span::default());
|
||||
|
||||
// Compile all functions
|
||||
for (file, source, f) in all_functions {
|
||||
self.file_name = file;
|
||||
self.source_text = source;
|
||||
if let Some(ident) = &f.id {
|
||||
let name = ident.name.to_string();
|
||||
self.emit_label(name);
|
||||
self.compile_function(f)?;
|
||||
self.emit_op(OpCode::Ret, vec![], Span::default());
|
||||
}
|
||||
}
|
||||
|
||||
let asm_vec: Vec<Asm> = self.instructions.iter().map(|(a, _)| a.clone()).collect();
|
||||
let bytecode = assemble(&asm_vec).map_err(|e| anyhow!("Assemble error: {}", e))?;
|
||||
|
||||
// Finalize symbols (associate PC)
|
||||
self.finalize_symbols();
|
||||
|
||||
let pbc = PbcFile {
|
||||
cp: self.constant_pool.clone(),
|
||||
rom: bytecode,
|
||||
};
|
||||
|
||||
write_pbc(&pbc).map_err(|e| anyhow!("PBC Write error: {}", e))
|
||||
}
|
||||
|
||||
fn compile_function(&mut self, f: &Function) -> Result<()> {
|
||||
self.locals.clear();
|
||||
self.next_local = 0;
|
||||
|
||||
// Start scope for parameters and local variables
|
||||
self.emit_op(OpCode::PushScope, vec![], f.span);
|
||||
|
||||
// Map parameters to locals
|
||||
for param in &f.params.items {
|
||||
if let BindingPattern::BindingIdentifier(ident) = ¶m.pattern {
|
||||
let name = ident.name.to_string();
|
||||
let id = self.next_local;
|
||||
self.locals.insert(name, id);
|
||||
self.next_local += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(body) = &f.body {
|
||||
for stmt in &body.statements {
|
||||
self.compile_stmt(stmt)?;
|
||||
}
|
||||
}
|
||||
|
||||
// ABI Rule: Every function MUST leave exactly one value on the stack before RET.
|
||||
// If the function doesn't have a return statement, we push Null.
|
||||
// For now, we always push Null at the end if it's not a return.
|
||||
// In a more complex compiler, we would check if all paths return.
|
||||
self.emit_op(OpCode::PopScope, vec![], Span::default());
|
||||
self.emit_op(OpCode::PushConst, vec![Operand::U32(0)], Span::default()); // Index 0 is Null in PBC
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn compile_stmt(&mut self, stmt: &Statement) -> Result<()> {
|
||||
match stmt {
|
||||
Statement::VariableDeclaration(var) => {
|
||||
for decl in &var.declarations {
|
||||
if let BindingPattern::BindingIdentifier(ident) = &decl.id {
|
||||
let name = ident.name.to_string();
|
||||
if let Some(init) = &decl.init {
|
||||
self.compile_expr(init)?;
|
||||
} else {
|
||||
self.emit_op(OpCode::PushI32, vec![Operand::I32(0)], decl.span);
|
||||
}
|
||||
let id = self.next_local;
|
||||
self.locals.insert(name, id);
|
||||
self.next_local += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::ExpressionStatement(expr_stmt) => {
|
||||
self.compile_expr(&expr_stmt.expression)?;
|
||||
self.emit_op(OpCode::Pop, vec![], expr_stmt.span);
|
||||
}
|
||||
Statement::IfStatement(if_stmt) => {
|
||||
let else_label = self.new_label("else");
|
||||
let end_label = self.new_label("end_if");
|
||||
|
||||
self.compile_expr(&if_stmt.test)?;
|
||||
self.emit_op(OpCode::JmpIfFalse, vec![Operand::Label(else_label.clone())], if_stmt.span);
|
||||
|
||||
self.compile_stmt(&if_stmt.consequent)?;
|
||||
self.emit_op(OpCode::Jmp, vec![Operand::Label(end_label.clone())], Span::default());
|
||||
|
||||
self.emit_label(else_label);
|
||||
if let Some(alt) = &if_stmt.alternate {
|
||||
self.compile_stmt(alt)?;
|
||||
}
|
||||
|
||||
self.emit_label(end_label);
|
||||
}
|
||||
Statement::BlockStatement(block) => {
|
||||
self.emit_op(OpCode::PushScope, vec![], block.span);
|
||||
for stmt in &block.body {
|
||||
self.compile_stmt(stmt)?;
|
||||
}
|
||||
self.emit_op(OpCode::PopScope, vec![], block.span);
|
||||
}
|
||||
_ => return Err(anyhow!("Unsupported statement type at {:?}", stmt.span())),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn compile_expr(&mut self, expr: &Expression) -> Result<()> {
|
||||
match expr {
|
||||
Expression::NumericLiteral(n) => {
|
||||
let val = n.value;
|
||||
if val.fract() == 0.0 && val >= i32::MIN as f64 && val <= i32::MAX as f64 {
|
||||
self.emit_op(OpCode::PushI32, vec![Operand::I32(val as i32)], n.span);
|
||||
} else {
|
||||
self.emit_op(OpCode::PushI64, vec![Operand::I64(val as i64)], n.span);
|
||||
}
|
||||
}
|
||||
Expression::BooleanLiteral(b) => {
|
||||
self.emit_op(OpCode::PushBool, vec![Operand::Bool(b.value)], b.span);
|
||||
}
|
||||
Expression::StringLiteral(s) => {
|
||||
let idx = self.add_constant(ConstantPoolEntry::String(s.value.to_string()));
|
||||
self.emit_op(OpCode::PushConst, vec![Operand::U32(idx)], s.span);
|
||||
}
|
||||
Expression::NullLiteral(n) => {
|
||||
self.emit_op(OpCode::PushConst, vec![Operand::U32(0)], n.span);
|
||||
}
|
||||
Expression::Identifier(ident) => {
|
||||
let name = ident.name.to_string();
|
||||
if let Some(&id) = self.locals.get(&name) {
|
||||
self.emit_op(OpCode::GetLocal, vec![Operand::U32(id)], ident.span);
|
||||
} else {
|
||||
return Err(anyhow!("Undefined variable: {} at {:?}", name, ident.span));
|
||||
}
|
||||
}
|
||||
Expression::AssignmentExpression(assign) => {
|
||||
if let AssignmentTarget::AssignmentTargetIdentifier(ident) = &assign.left {
|
||||
let name = ident.name.to_string();
|
||||
self.compile_expr(&assign.right)?;
|
||||
if let Some(&id) = self.locals.get(&name) {
|
||||
self.emit_op(OpCode::SetLocal, vec![Operand::U32(id)], assign.span);
|
||||
self.emit_op(OpCode::GetLocal, vec![Operand::U32(id)], assign.span);
|
||||
} else {
|
||||
return Err(anyhow!("Undefined variable: {} at {:?}", name, ident.span));
|
||||
}
|
||||
} else {
|
||||
return Err(anyhow!("Unsupported assignment target at {:?}", assign.span));
|
||||
}
|
||||
}
|
||||
Expression::BinaryExpression(bin) => {
|
||||
self.compile_expr(&bin.left)?;
|
||||
self.compile_expr(&bin.right)?;
|
||||
let op = match bin.operator {
|
||||
BinaryOperator::Addition => OpCode::Add,
|
||||
BinaryOperator::Subtraction => OpCode::Sub,
|
||||
BinaryOperator::Multiplication => OpCode::Mul,
|
||||
BinaryOperator::Division => OpCode::Div,
|
||||
BinaryOperator::Equality => OpCode::Eq,
|
||||
BinaryOperator::Inequality => OpCode::Neq,
|
||||
BinaryOperator::LessThan => OpCode::Lt,
|
||||
BinaryOperator::GreaterThan => OpCode::Gt,
|
||||
BinaryOperator::LessEqualThan => OpCode::Lte,
|
||||
BinaryOperator::GreaterEqualThan => OpCode::Gte,
|
||||
_ => return Err(anyhow!("Unsupported binary operator {:?} at {:?}", bin.operator, bin.span)),
|
||||
};
|
||||
self.emit_op(op, vec![], bin.span);
|
||||
}
|
||||
Expression::LogicalExpression(log) => {
|
||||
self.compile_expr(&log.left)?;
|
||||
self.compile_expr(&log.right)?;
|
||||
let op = match log.operator {
|
||||
LogicalOperator::And => OpCode::And,
|
||||
LogicalOperator::Or => OpCode::Or,
|
||||
_ => return Err(anyhow!("Unsupported logical operator {:?} at {:?}", log.operator, log.span)),
|
||||
};
|
||||
self.emit_op(op, vec![], log.span);
|
||||
}
|
||||
Expression::UnaryExpression(unary) => {
|
||||
self.compile_expr(&unary.argument)?;
|
||||
let op = match unary.operator {
|
||||
UnaryOperator::UnaryNegation => OpCode::Neg,
|
||||
UnaryOperator::UnaryPlus => return Ok(()),
|
||||
UnaryOperator::LogicalNot => OpCode::Not,
|
||||
_ => return Err(anyhow!("Unsupported unary operator {:?} at {:?}", unary.operator, unary.span)),
|
||||
};
|
||||
self.emit_op(op, vec![], unary.span);
|
||||
}
|
||||
Expression::CallExpression(call) => {
|
||||
let name = ast_util::get_callee_name(&call.callee)?;
|
||||
if let Some(syscall_id) = syscall_map::map_syscall(&name) {
|
||||
if syscall_id == 0xFFFF_FFFF {
|
||||
// Color.rgb(r, g, b)
|
||||
if call.arguments.len() != 3 {
|
||||
return Err(anyhow!("Color.rgb expects 3 arguments at {:?}", call.span));
|
||||
}
|
||||
// We'll emit the bit manipulation logic here or just a special syscall if we had one.
|
||||
// Since we have bitwise opcodes, let's use them!
|
||||
// ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3)
|
||||
|
||||
// Argument 0: r
|
||||
if let Some(expr) = call.arguments[0].as_expression() {
|
||||
self.compile_expr(expr)?;
|
||||
self.emit_op(OpCode::PushI32, vec![Operand::I32(3)], call.span);
|
||||
self.emit_op(OpCode::Shr, vec![], call.span);
|
||||
self.emit_op(OpCode::PushI32, vec![Operand::I32(11)], call.span);
|
||||
self.emit_op(OpCode::Shl, vec![], call.span);
|
||||
}
|
||||
|
||||
// Argument 1: g
|
||||
if let Some(expr) = call.arguments[1].as_expression() {
|
||||
self.compile_expr(expr)?;
|
||||
self.emit_op(OpCode::PushI32, vec![Operand::I32(2)], call.span);
|
||||
self.emit_op(OpCode::Shr, vec![], call.span);
|
||||
self.emit_op(OpCode::PushI32, vec![Operand::I32(5)], call.span);
|
||||
self.emit_op(OpCode::Shl, vec![], call.span);
|
||||
}
|
||||
|
||||
self.emit_op(OpCode::BitOr, vec![], call.span);
|
||||
|
||||
// Argument 2: b
|
||||
if let Some(expr) = call.arguments[2].as_expression() {
|
||||
self.compile_expr(expr)?;
|
||||
self.emit_op(OpCode::PushI32, vec![Operand::I32(3)], call.span);
|
||||
self.emit_op(OpCode::Shr, vec![], call.span);
|
||||
}
|
||||
|
||||
self.emit_op(OpCode::BitOr, vec![], call.span);
|
||||
|
||||
} else {
|
||||
for arg in &call.arguments {
|
||||
if let Some(expr) = arg.as_expression() {
|
||||
self.compile_expr(expr)?;
|
||||
}
|
||||
}
|
||||
self.emit_op(OpCode::Syscall, vec![Operand::U32(syscall_id)], call.span);
|
||||
}
|
||||
} else {
|
||||
// Local function call
|
||||
for arg in &call.arguments {
|
||||
if let Some(expr) = arg.as_expression() {
|
||||
self.compile_expr(expr)?;
|
||||
}
|
||||
}
|
||||
self.emit_op(OpCode::Call, vec![Operand::Label(name), Operand::U32(call.arguments.len() as u32)], call.span);
|
||||
}
|
||||
}
|
||||
Expression::StaticMemberExpression(member) => {
|
||||
let full_name = ast_util::get_member_expr_name(expr)?;
|
||||
|
||||
if full_name.to_lowercase().starts_with("color.") {
|
||||
match full_name.to_lowercase().as_str() {
|
||||
"color.black" => self.emit_op(OpCode::PushI32, vec![Operand::I32(Color::BLACK.raw() as i32)], member.span),
|
||||
"color.white" => self.emit_op(OpCode::PushI32, vec![Operand::I32(Color::WHITE.raw() as i32)], member.span),
|
||||
"color.red" => self.emit_op(OpCode::PushI32, vec![Operand::I32(Color::RED.raw() as i32)], member.span),
|
||||
"color.green" => self.emit_op(OpCode::PushI32, vec![Operand::I32(Color::GREEN.raw() as i32)], member.span),
|
||||
"color.blue" => self.emit_op(OpCode::PushI32, vec![Operand::I32(Color::BLUE.raw() as i32)], member.span),
|
||||
"color.yellow" => self.emit_op(OpCode::PushI32, vec![Operand::I32(Color::YELLOW.raw() as i32)], member.span),
|
||||
"color.cyan" => self.emit_op(OpCode::PushI32, vec![Operand::I32(Color::CYAN.raw() as i32)], member.span),
|
||||
"color.gray" | "color.grey" => self.emit_op(OpCode::PushI32, vec![Operand::I32(Color::GRAY.raw() as i32)], member.span),
|
||||
"color.orange" => self.emit_op(OpCode::PushI32, vec![Operand::I32(Color::ORANGE.raw() as i32)], member.span),
|
||||
"color.indigo" => self.emit_op(OpCode::PushI32, vec![Operand::I32(Color::INDIGO.raw() as i32)], member.span),
|
||||
"color.magenta" => self.emit_op(OpCode::PushI32, vec![Operand::I32(Color::MAGENTA.raw() as i32)], member.span),
|
||||
"color.colorKey" | "color.color_key" => self.emit_op(OpCode::PushI32, vec![Operand::I32(Color::COLOR_KEY.raw() as i32)], member.span),
|
||||
_ => return Err(anyhow!("Unsupported color constant: {} at {:?}", full_name, member.span)),
|
||||
}
|
||||
} else if full_name.to_lowercase().starts_with("pad.") {
|
||||
let parts: Vec<&str> = full_name.split('.').collect();
|
||||
if parts.len() == 3 {
|
||||
let btn_name = parts[1];
|
||||
let state_name = parts[2];
|
||||
let btn_id = self.map_btn_name(btn_name)?;
|
||||
let syscall_id = match state_name {
|
||||
"down" => Syscall::InputGetPad as u32,
|
||||
"pressed" => Syscall::InputGetPadPressed as u32,
|
||||
"released" => Syscall::InputGetPadReleased as u32,
|
||||
"holdFrames" => Syscall::InputGetPadHold as u32,
|
||||
_ => return Err(anyhow!("Unsupported button state: {} at {:?}", state_name, member.span)),
|
||||
};
|
||||
self.emit_op(OpCode::PushI32, vec![Operand::I32(btn_id as i32)], member.span);
|
||||
self.emit_op(OpCode::Syscall, vec![Operand::U32(syscall_id)], member.span);
|
||||
} else {
|
||||
return Err(anyhow!("Partial Pad access not supported: {} at {:?}", full_name, member.span));
|
||||
}
|
||||
} else if full_name.to_lowercase().starts_with("touch.") {
|
||||
let parts: Vec<&str> = full_name.split('.').collect();
|
||||
match parts.len() {
|
||||
2 => {
|
||||
let prop = parts[1];
|
||||
let syscall_id = match prop {
|
||||
"x" => Syscall::TouchGetX as u32,
|
||||
"y" => Syscall::TouchGetY as u32,
|
||||
_ => return Err(anyhow!("Unsupported touch property: {} at {:?}", prop, member.span)),
|
||||
};
|
||||
self.emit_op(OpCode::Syscall, vec![Operand::U32(syscall_id)], member.span);
|
||||
}
|
||||
3 if parts[1] == "button" => {
|
||||
let state_name = parts[2];
|
||||
let syscall_id = match state_name {
|
||||
"down" => Syscall::TouchIsDown as u32,
|
||||
"pressed" => Syscall::TouchIsPressed as u32,
|
||||
"released" => Syscall::TouchIsReleased as u32,
|
||||
"holdFrames" => Syscall::TouchGetHold as u32,
|
||||
_ => return Err(anyhow!("Unsupported touch button state: {} at {:?}", state_name, member.span)),
|
||||
};
|
||||
self.emit_op(OpCode::Syscall, vec![Operand::U32(syscall_id)], member.span);
|
||||
}
|
||||
_ => return Err(anyhow!("Unsupported touch access: {} at {:?}", full_name, member.span)),
|
||||
}
|
||||
} else {
|
||||
return Err(anyhow!("Member expression outside call not supported: {} at {:?}", full_name, member.span));
|
||||
}
|
||||
}
|
||||
_ => return Err(anyhow!("Unsupported expression type at {:?}", expr.span())),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map_btn_name(&self, btn_name: &str) -> Result<u32> {
|
||||
match btn_name.to_lowercase().as_str() {
|
||||
"up" => Ok(syscall_map::BTN_UP),
|
||||
"down" => Ok(syscall_map::BTN_DOWN),
|
||||
"left" => Ok(syscall_map::BTN_LEFT),
|
||||
"right" => Ok(syscall_map::BTN_RIGHT),
|
||||
"a" => Ok(syscall_map::BTN_A),
|
||||
"b" => Ok(syscall_map::BTN_B),
|
||||
"x" => Ok(syscall_map::BTN_X),
|
||||
"y" => Ok(syscall_map::BTN_Y),
|
||||
"l" => Ok(syscall_map::BTN_L),
|
||||
"r" => Ok(syscall_map::BTN_R),
|
||||
"start" => Ok(syscall_map::BTN_START),
|
||||
"select" => Ok(syscall_map::BTN_SELECT),
|
||||
_ => Err(anyhow!("Unsupported button: {}", btn_name)),
|
||||
}
|
||||
}
|
||||
|
||||
fn new_label(&mut self, prefix: &str) -> String {
|
||||
let label = format!("{}_{}", prefix, self.label_count);
|
||||
self.label_count += 1;
|
||||
label
|
||||
}
|
||||
|
||||
fn emit_label(&mut self, name: String) {
|
||||
self.instructions.push((Asm::Label(name), false));
|
||||
}
|
||||
|
||||
fn emit_op(&mut self, opcode: OpCode, operands: Vec<Operand>, span: Span) {
|
||||
let has_symbol = if !span.is_unspanned() {
|
||||
let (line, col) = self.lookup_pos(span.start);
|
||||
self.symbols.push(Symbol {
|
||||
pc: 0,
|
||||
file: self.file_name.clone(),
|
||||
line,
|
||||
col,
|
||||
});
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
self.instructions.push((Asm::Op(opcode, operands), has_symbol));
|
||||
}
|
||||
|
||||
fn lookup_pos(&self, pos: u32) -> (usize, usize) {
|
||||
let mut line = 1;
|
||||
let mut col = 1;
|
||||
for (i, c) in self.source_text.char_indices() {
|
||||
if i as u32 == pos {
|
||||
break;
|
||||
}
|
||||
if c == '\n' {
|
||||
line += 1;
|
||||
col = 1;
|
||||
} else {
|
||||
col += 1;
|
||||
}
|
||||
}
|
||||
(line, col)
|
||||
}
|
||||
|
||||
fn finalize_symbols(&mut self) {
|
||||
let mut current_pc = 0u32;
|
||||
let mut symbol_ptr = 0;
|
||||
|
||||
for (instr, has_symbol) in &self.instructions {
|
||||
match instr {
|
||||
Asm::Label(_) => {}
|
||||
Asm::Op(_opcode, operands) => {
|
||||
if *has_symbol && symbol_ptr < self.symbols.len() {
|
||||
self.symbols[symbol_ptr].pc = current_pc;
|
||||
symbol_ptr += 1;
|
||||
}
|
||||
|
||||
current_pc += 2;
|
||||
current_pc = asm::update_pc_by_operand(current_pc, operands);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod codegen;
|
||||
pub mod validator;
|
||||
pub mod ast_util;
|
||||
|
||||
pub use codegen::Codegen;
|
||||
@@ -0,0 +1,163 @@
|
||||
use oxc_ast::ast::*;
|
||||
use oxc_ast_visit::{Visit, walk};
|
||||
use oxc_span::GetSpan;
|
||||
use anyhow::{Result, anyhow};
|
||||
use crate::syscall_map;
|
||||
use crate::codegen::ast_util;
|
||||
|
||||
pub struct Validator {
|
||||
errors: Vec<String>,
|
||||
local_functions: std::collections::HashSet<String>,
|
||||
}
|
||||
|
||||
impl Validator {
|
||||
pub fn validate(program: &Program) -> Result<()> {
|
||||
let mut validator = Self {
|
||||
errors: Vec::new(),
|
||||
local_functions: std::collections::HashSet::new(),
|
||||
};
|
||||
|
||||
// 1. Collect all local function names
|
||||
for item in &program.body {
|
||||
match item {
|
||||
Statement::FunctionDeclaration(f) => {
|
||||
if let Some(ident) = &f.id {
|
||||
validator.local_functions.insert(ident.name.to_string());
|
||||
}
|
||||
}
|
||||
Statement::ExportNamedDeclaration(decl) => {
|
||||
if let Some(Declaration::FunctionDeclaration(f)) = &decl.declaration {
|
||||
if let Some(ident) = &f.id {
|
||||
validator.local_functions.insert(ident.name.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
Statement::ImportDeclaration(decl) => {
|
||||
if let Some(specifiers) = &decl.specifiers {
|
||||
for specifier in specifiers {
|
||||
match specifier {
|
||||
ImportDeclarationSpecifier::ImportSpecifier(s) => {
|
||||
validator.local_functions.insert(s.local.name.to_string());
|
||||
}
|
||||
ImportDeclarationSpecifier::ImportDefaultSpecifier(s) => {
|
||||
validator.local_functions.insert(s.local.name.to_string());
|
||||
}
|
||||
ImportDeclarationSpecifier::ImportNamespaceSpecifier(s) => {
|
||||
validator.local_functions.insert(s.local.name.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Recursive validation of the AST
|
||||
validator.visit_program(program);
|
||||
|
||||
if validator.errors.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!("Validation errors:\n{}", validator.errors.join("\n")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Visit<'a> for Validator {
|
||||
fn visit_statement(&mut self, stmt: &Statement<'a>) {
|
||||
match stmt {
|
||||
Statement::VariableDeclaration(_) |
|
||||
Statement::ExpressionStatement(_) |
|
||||
Statement::IfStatement(_) |
|
||||
Statement::BlockStatement(_) |
|
||||
Statement::ExportNamedDeclaration(_) |
|
||||
Statement::ImportDeclaration(_) |
|
||||
Statement::FunctionDeclaration(_) => {
|
||||
// Supported
|
||||
walk::walk_statement(self, stmt);
|
||||
}
|
||||
_ => {
|
||||
self.errors.push(format!("Unsupported statement type at {:?}", stmt.span()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_expression(&mut self, expr: &Expression<'a>) {
|
||||
match expr {
|
||||
Expression::NumericLiteral(_) |
|
||||
Expression::BooleanLiteral(_) |
|
||||
Expression::StringLiteral(_) |
|
||||
Expression::NullLiteral(_) |
|
||||
Expression::Identifier(_) |
|
||||
Expression::AssignmentExpression(_) |
|
||||
Expression::BinaryExpression(_) |
|
||||
Expression::LogicalExpression(_) |
|
||||
Expression::UnaryExpression(_) |
|
||||
Expression::CallExpression(_) |
|
||||
Expression::StaticMemberExpression(_) => {
|
||||
// Base types supported, detailed checks in specific visit methods if needed
|
||||
walk::walk_expression(self, expr);
|
||||
}
|
||||
_ => {
|
||||
self.errors.push(format!("Unsupported expression type at {:?}", expr.span()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_unary_expression(&mut self, expr: &UnaryExpression<'a>) {
|
||||
match expr.operator {
|
||||
UnaryOperator::UnaryNegation |
|
||||
UnaryOperator::UnaryPlus |
|
||||
UnaryOperator::LogicalNot => {
|
||||
walk::walk_unary_expression(self, expr);
|
||||
}
|
||||
_ => {
|
||||
self.errors.push(format!("Unsupported unary operator {:?} at {:?}", expr.operator, expr.span));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_binary_expression(&mut self, expr: &BinaryExpression<'a>) {
|
||||
match expr.operator {
|
||||
BinaryOperator::Addition |
|
||||
BinaryOperator::Subtraction |
|
||||
BinaryOperator::Multiplication |
|
||||
BinaryOperator::Division |
|
||||
BinaryOperator::Equality |
|
||||
BinaryOperator::Inequality |
|
||||
BinaryOperator::LessThan |
|
||||
BinaryOperator::GreaterThan |
|
||||
BinaryOperator::LessEqualThan |
|
||||
BinaryOperator::GreaterEqualThan => {
|
||||
walk::walk_binary_expression(self, expr);
|
||||
}
|
||||
_ => {
|
||||
self.errors.push(format!("Unsupported binary operator {:?} at {:?}", expr.operator, expr.span));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_call_expression(&mut self, expr: &CallExpression<'a>) {
|
||||
if let Ok(name) = ast_util::get_callee_name(&expr.callee) {
|
||||
if syscall_map::map_syscall(&name).is_none() && !self.local_functions.contains(&name) {
|
||||
self.errors.push(format!("Unsupported function call: {} at {:?}", name, expr.span));
|
||||
}
|
||||
} else {
|
||||
self.errors.push(format!("Unsupported callee expression at {:?}", expr.callee.span()));
|
||||
}
|
||||
walk::walk_call_expression(self, expr);
|
||||
}
|
||||
|
||||
fn visit_logical_expression(&mut self, expr: &LogicalExpression<'a>) {
|
||||
match expr.operator {
|
||||
LogicalOperator::And |
|
||||
LogicalOperator::Or => {
|
||||
walk::walk_logical_expression(self, expr);
|
||||
}
|
||||
_ => {
|
||||
self.errors.push(format!("Unsupported logical operator {:?} at {:?}", expr.operator, expr.span));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user