dev/prometeuc-improvements (#5)
Co-authored-by: Nilton Constantino <nilton.constantino@visma.com> Reviewed-on: #5
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "prometeu-compiler"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "prometeu-compiler"
|
||||
path = "src/main.rs"
|
||||
|
||||
[package.metadata.dist]
|
||||
dist = true
|
||||
include = ["../../VERSION.txt"]
|
||||
|
||||
[dependencies]
|
||||
prometeu-bytecode = { path = "../prometeu-bytecode" }
|
||||
prometeu-core = { path = "../prometeu-core" }
|
||||
oxc_parser = "0.110.0"
|
||||
oxc_allocator = "0.110.0"
|
||||
oxc_ast = "0.110.0"
|
||||
oxc_ast_visit = "0.110.0"
|
||||
oxc_span = "0.110.0"
|
||||
clap = { version = "4.5.54", features = ["derive"] }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0.149"
|
||||
anyhow = "1.0.100"
|
||||
@@ -0,0 +1,40 @@
|
||||
use clap::{Parser, Subcommand};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "prometeu-compiler")]
|
||||
#[command(about = "Prometeu Compiler", long_about = None)]
|
||||
pub struct Cli {
|
||||
#[command(subcommand)]
|
||||
pub command: Commands,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
pub enum Commands {
|
||||
/// Builds a Prometeu project
|
||||
Build {
|
||||
/// Project directory
|
||||
project_dir: PathBuf,
|
||||
|
||||
/// Entry file
|
||||
#[arg(short, long)]
|
||||
entry: Option<PathBuf>,
|
||||
|
||||
/// Output PBC file
|
||||
#[arg(short, long)]
|
||||
out: Option<PathBuf>,
|
||||
|
||||
/// Emit disassembly file
|
||||
#[arg(long, default_value_t = true)]
|
||||
emit_disasm: bool,
|
||||
|
||||
/// Emit symbols file
|
||||
#[arg(long, default_value_t = true)]
|
||||
emit_symbols: bool,
|
||||
},
|
||||
/// Verifies a Prometeu project
|
||||
Verify {
|
||||
/// Project directory
|
||||
project_dir: PathBuf,
|
||||
},
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use anyhow::{Result, Context, anyhow};
|
||||
use oxc_allocator::Allocator;
|
||||
use oxc_parser::Parser;
|
||||
use oxc_span::SourceType;
|
||||
use oxc_ast::ast::*;
|
||||
use crate::codegen::Codegen;
|
||||
use crate::codegen::validator::Validator;
|
||||
use std::fs;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use prometeu_bytecode::disasm::disasm;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Symbol {
|
||||
pub pc: u32,
|
||||
pub file: String,
|
||||
pub line: usize,
|
||||
pub col: usize,
|
||||
}
|
||||
|
||||
pub struct CompilationUnit {
|
||||
pub rom: Vec<u8>,
|
||||
pub symbols: Vec<Symbol>,
|
||||
}
|
||||
|
||||
impl CompilationUnit {
|
||||
pub fn export(&self, out: &Path, emit_disasm: bool, emit_symbols: bool) -> Result<()> {
|
||||
fs::write(out, &self.rom).with_context(|| format!("Failed to write PBC to {:?}", out))?;
|
||||
|
||||
if emit_symbols {
|
||||
let symbols_path = out.with_file_name("symbols.json");
|
||||
let symbols_json = serde_json::to_string_pretty(&self.symbols)?;
|
||||
fs::write(&symbols_path, symbols_json)?;
|
||||
}
|
||||
|
||||
if emit_disasm {
|
||||
let disasm_path = out.with_extension("disasm.txt");
|
||||
|
||||
// Try to parse as PBC, if fails use raw
|
||||
let rom_to_disasm = if let Ok(pbc) = prometeu_bytecode::pbc::parse_pbc(&self.rom) {
|
||||
pbc.rom
|
||||
} else {
|
||||
self.rom.clone()
|
||||
};
|
||||
|
||||
let instructions = disasm(&rom_to_disasm).map_err(|e| anyhow::anyhow!("Disassembly failed: {}", e))?;
|
||||
|
||||
let mut disasm_text = String::new();
|
||||
for instr in instructions {
|
||||
let symbol = self.symbols.iter().find(|s| s.pc == instr.pc);
|
||||
let comment = if let Some(s) = symbol {
|
||||
format!(" ; {}:{}", s.file, s.line)
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
|
||||
let operands_str = instr.operands.iter()
|
||||
.map(|o| format!("{:?}", o))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
|
||||
disasm_text.push_str(&format!("{:08X} {:?} {}{}\n", instr.pc, instr.opcode, operands_str, comment));
|
||||
}
|
||||
fs::write(disasm_path, disasm_text)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_import(base_path: &Path, import_str: &str) -> Result<PathBuf> {
|
||||
let mut path = base_path.parent().unwrap().join(import_str);
|
||||
if !path.exists() {
|
||||
if path.with_extension("ts").exists() {
|
||||
path.set_extension("ts");
|
||||
} else if path.with_extension("js").exists() {
|
||||
path.set_extension("js");
|
||||
}
|
||||
}
|
||||
if !path.exists() {
|
||||
return Err(anyhow!("Cannot resolve import '{}' from {:?}", import_str, base_path));
|
||||
}
|
||||
Ok(path.canonicalize()?)
|
||||
}
|
||||
|
||||
pub fn compile(entry: &Path) -> Result<CompilationUnit> {
|
||||
let allocator = Allocator::default();
|
||||
let mut modules = HashMap::new();
|
||||
let mut queue = VecDeque::new();
|
||||
|
||||
let entry_abs = entry.canonicalize()
|
||||
.with_context(|| format!("Failed to canonicalize entry path: {:?}", entry))?;
|
||||
queue.push_back(entry_abs.clone());
|
||||
|
||||
while let Some(path) = queue.pop_front() {
|
||||
let path_str = path.to_string_lossy().to_string();
|
||||
if modules.contains_key(&path_str) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let source_text = fs::read_to_string(&path)
|
||||
.with_context(|| format!("Failed to read file: {:?}", path))?;
|
||||
|
||||
// Allocate source_text in the allocator to keep it alive
|
||||
let source_text_ptr: &str = allocator.alloc_str(&source_text);
|
||||
|
||||
let source_type = SourceType::from_path(&path).unwrap_or_default();
|
||||
let parser_ret = Parser::new(&allocator, source_text_ptr, source_type).parse();
|
||||
|
||||
if !parser_ret.errors.is_empty() {
|
||||
for error in parser_ret.errors {
|
||||
eprintln!("{:?}", error);
|
||||
}
|
||||
return Err(anyhow!("Failed to parse module: {:?}", path));
|
||||
}
|
||||
|
||||
// Validate individual module
|
||||
Validator::validate(&parser_ret.program)?;
|
||||
|
||||
// Find imports to add to queue
|
||||
for item in &parser_ret.program.body {
|
||||
if let Statement::ImportDeclaration(decl) = item {
|
||||
let import_path = decl.source.value.as_str();
|
||||
let resolved = resolve_import(&path, import_path)?;
|
||||
queue.push_back(resolved);
|
||||
}
|
||||
}
|
||||
|
||||
modules.insert(path_str, (source_text_ptr, parser_ret.program));
|
||||
}
|
||||
|
||||
let entry_str = entry_abs.to_string_lossy().to_string();
|
||||
let mut program_list = Vec::new();
|
||||
|
||||
// Add entry program first
|
||||
let entry_data = modules.get(&entry_str).ok_or_else(|| anyhow!("Entry module not found after loading"))?;
|
||||
program_list.push((entry_str.clone(), entry_data.0.to_string(), &entry_data.1));
|
||||
|
||||
// Add all other programs
|
||||
for (path, (source, program)) in &modules {
|
||||
if path != &entry_str {
|
||||
program_list.push((path.clone(), source.to_string(), program));
|
||||
}
|
||||
}
|
||||
|
||||
let mut codegen = Codegen::new(entry_str.clone(), entry_data.0.to_string());
|
||||
let rom = codegen.compile_programs(program_list)?;
|
||||
|
||||
Ok(CompilationUnit {
|
||||
rom,
|
||||
symbols: codegen.symbols,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
pub mod cli;
|
||||
pub mod codegen;
|
||||
pub mod compiler;
|
||||
pub mod syscall_map;
|
||||
|
||||
use clap::Parser;
|
||||
use anyhow::Result;
|
||||
|
||||
pub fn run() -> Result<()> {
|
||||
let cli = cli::Cli::parse();
|
||||
|
||||
match cli.command {
|
||||
cli::Commands::Build {
|
||||
project_dir,
|
||||
entry,
|
||||
out,
|
||||
emit_disasm,
|
||||
emit_symbols,
|
||||
} => {
|
||||
let entry = entry.unwrap_or_else(|| project_dir.join("src/main.ts"));
|
||||
let build_dir = project_dir.join("build");
|
||||
let out = out.unwrap_or_else(|| build_dir.join("program.pbc"));
|
||||
|
||||
if !build_dir.exists() {
|
||||
std::fs::create_dir_all(&build_dir)?;
|
||||
}
|
||||
|
||||
println!("Building project at {:?}", project_dir);
|
||||
println!("Entry: {:?}", entry);
|
||||
println!("Output: {:?}", out);
|
||||
|
||||
let compilation_unit = compiler::compile(&entry)?;
|
||||
compilation_unit.export(&out, emit_disasm, emit_symbols)?;
|
||||
}
|
||||
cli::Commands::Verify { project_dir } => {
|
||||
let entry = project_dir.join("src/main.ts");
|
||||
println!("Verifying project at {:?}", project_dir);
|
||||
println!("Entry: {:?}", entry);
|
||||
|
||||
compiler::compile(&entry)?;
|
||||
println!("Project is valid!");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
use anyhow::Result;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
prometeu_compiler::run()
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
use prometeu_core::prometeu_os::Syscall;
|
||||
use prometeu_core::model::ButtonId;
|
||||
|
||||
pub const BTN_UP: u32 = ButtonId::Up as u32;
|
||||
pub const BTN_DOWN: u32 = ButtonId::Down as u32;
|
||||
pub const BTN_LEFT: u32 = ButtonId::Left as u32;
|
||||
pub const BTN_RIGHT: u32 = ButtonId::Right as u32;
|
||||
pub const BTN_A: u32 = ButtonId::A as u32;
|
||||
pub const BTN_B: u32 = ButtonId::B as u32;
|
||||
pub const BTN_X: u32 = ButtonId::X as u32;
|
||||
pub const BTN_Y: u32 = ButtonId::Y as u32;
|
||||
pub const BTN_L: u32 = ButtonId::L as u32;
|
||||
pub const BTN_R: u32 = ButtonId::R as u32;
|
||||
pub const BTN_START: u32 = ButtonId::Start as u32;
|
||||
pub const BTN_SELECT: u32 = ButtonId::Select as u32;
|
||||
|
||||
pub fn map_syscall(name: &str) -> Option<u32> {
|
||||
if let Some(syscall) = Syscall::from_name(name) {
|
||||
return Some(syscall as u32);
|
||||
}
|
||||
|
||||
// Fallback para nomes especiais do compilador
|
||||
match name {
|
||||
"Color.rgb" | "color.rgb" => Some(0xFFFF_FFFF), // ID especial para Color.rgb (não é um syscall real)
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user