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:
2026-01-21 10:55:47 +00:00
co-authored by Nilton Constantino
parent 73353d864d
commit 0e6da1433b
76 changed files with 2820 additions and 756 deletions
+2
View File
@@ -2,6 +2,8 @@
name = "prometeu-bytecode"
version = "0.1.0"
edition = "2021"
license.workspace = true
repository.workspace = true
[dependencies]
# No dependencies for now
+13 -7
View File
@@ -18,6 +18,18 @@ pub enum Asm {
Label(String),
}
pub fn update_pc_by_operand(initial_pc: u32, operands: &Vec<Operand>) -> u32 {
let mut pcp: u32 = initial_pc;
for operand in operands {
match operand {
Operand::U32(_) | Operand::I32(_) | Operand::Label(_) => pcp += 4,
Operand::I64(_) | Operand::F64(_) => pcp += 8,
Operand::Bool(_) => pcp += 1,
}
}
pcp
}
pub fn assemble(instructions: &[Asm]) -> Result<Vec<u8>, String> {
let mut labels = HashMap::new();
let mut current_pc = 0u32;
@@ -30,13 +42,7 @@ pub fn assemble(instructions: &[Asm]) -> Result<Vec<u8>, String> {
}
Asm::Op(_opcode, operands) => {
current_pc += 2; // OpCode is u16 (2 bytes)
for operand in operands {
match operand {
Operand::U32(_) | Operand::I32(_) | Operand::Label(_) => current_pc += 4,
Operand::I64(_) | Operand::F64(_) => current_pc += 8,
Operand::Bool(_) => current_pc += 1,
}
}
current_pc = update_pc_by_operand(current_pc, operands);
}
}
}
+27
View File
@@ -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"
@@ -2,7 +2,7 @@ use clap::{Parser, Subcommand};
use std::path::PathBuf;
#[derive(Parser)]
#[command(name = "prometeuc")]
#[command(name = "prometeu-compiler")]
#[command(about = "Prometeu Compiler", long_about = None)]
pub struct Cli {
#[command(subcommand)]
@@ -32,4 +32,9 @@ pub enum Commands {
#[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) = &param.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);
}
}
}
}
}
@@ -1,3 +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));
}
}
}
}
+154
View File
@@ -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,
})
}
@@ -1,12 +1,12 @@
use clap::Parser;
use anyhow::Result;
pub mod cli;
pub mod codegen;
pub mod compiler;
pub mod syscall_map;
fn main() -> Result<()> {
use clap::Parser;
use anyhow::Result;
pub fn run() -> Result<()> {
let cli = cli::Cli::parse();
match cli.command {
@@ -29,7 +29,16 @@ fn main() -> Result<()> {
println!("Entry: {:?}", entry);
println!("Output: {:?}", out);
compiler::compile(&entry, &out, emit_disasm, emit_symbols)?;
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!");
}
}
+5
View File
@@ -0,0 +1,5 @@
use anyhow::Result;
fn main() -> Result<()> {
prometeu_compiler::run()
}
@@ -21,7 +21,7 @@ pub fn map_syscall(name: &str) -> Option<u32> {
// Fallback para nomes especiais do compilador
match name {
"input.btnA" | "input.btnB" => Some(Syscall::InputGetPad as u32),
"Color.rgb" | "color.rgb" => Some(0xFFFF_FFFF), // ID especial para Color.rgb (não é um syscall real)
_ => None,
}
}
+2 -2
View File
@@ -5,6 +5,6 @@ edition = "2024"
license.workspace = true
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.149"
prometeu-bytecode = { path = "../prometeu-bytecode" }
+15
View File
@@ -133,6 +133,8 @@ impl Gfx {
color: Color,
mode: BlendMode,
) {
if color == Color::COLOR_KEY { return; }
let fw = self.w as i32;
let fh = self.h as i32;
@@ -160,6 +162,7 @@ impl Gfx {
/// Draws a single pixel.
pub fn draw_pixel(&mut self, x: i32, y: i32, color: Color) {
if color == Color::COLOR_KEY { return; }
if x >= 0 && x < self.w as i32 && y >= 0 && y < self.h as i32 {
self.back[y as usize * self.w + x as usize] = color.0;
}
@@ -167,6 +170,8 @@ impl Gfx {
/// Draws a line between two points using Bresenham's algorithm.
pub fn draw_line(&mut self, x0: i32, y0: i32, x1: i32, y1: i32, color: Color) {
if color == Color::COLOR_KEY { return; }
let dx = (x1 - x0).abs();
let sx = if x0 < x1 { 1 } else { -1 };
let dy = -(y1 - y0).abs();
@@ -193,6 +198,8 @@ impl Gfx {
/// Draws a circle outline using Midpoint Circle Algorithm.
pub fn draw_circle(&mut self, xc: i32, yc: i32, r: i32, color: Color) {
if color == Color::COLOR_KEY { return; }
if r < 0 { return; }
let mut x = 0;
let mut y = r;
@@ -223,6 +230,8 @@ impl Gfx {
/// Draws a filled circle.
pub fn fill_circle(&mut self, xc: i32, yc: i32, r: i32, color: Color) {
if color == Color::COLOR_KEY { return; }
if r < 0 { return; }
let mut x = 0;
let mut y = r;
@@ -255,6 +264,8 @@ impl Gfx {
/// Draws a rectangle outline.
pub fn draw_rect(&mut self, x: i32, y: i32, w: i32, h: i32, color: Color) {
if color == Color::COLOR_KEY { return; }
if w <= 0 || h <= 0 { return; }
self.draw_horizontal_line(x, x + w - 1, y, color);
self.draw_horizontal_line(x, x + w - 1, y + h - 1, color);
@@ -269,6 +280,8 @@ impl Gfx {
}
fn draw_horizontal_line(&mut self, x0: i32, x1: i32, y: i32, color: Color) {
if color == Color::COLOR_KEY { return; }
if y < 0 || y >= self.h as i32 { return; }
let start = x0.max(0);
let end = x1.min(self.w as i32 - 1);
@@ -279,6 +292,8 @@ impl Gfx {
}
fn draw_vertical_line(&mut self, x: i32, y0: i32, y1: i32, color: Color) {
if color == Color::COLOR_KEY { return; }
if x < 0 || x >= self.w as i32 { return; }
let start = y0.max(0);
let end = y1.min(self.h as i32 - 1);
+10
View File
@@ -60,4 +60,14 @@ impl Color {
pub const fn raw(self) -> u16 {
self.0
}
pub const fn hex(self) -> i32 {
let (r5, g6, b5) = Self::unpack_to_native(self.0);
let r8 = ((r5 as u32) << 3) | ((r5 as u32) >> 2);
let g8 = ((g6 as u32) << 2) | ((g6 as u32) >> 4);
let b8 = ((b5 as u32) << 3) | ((b5 as u32) >> 2);
let hex = r8 << 16 | g8 << 8 | b8;
hex as i32
}
}
@@ -325,26 +325,31 @@ impl PrometeuOS {
Ok(100)
}
pub fn get_color(&self, index: usize, hw: &mut dyn HardwareBridge) -> Color {
if let Some(bank) = hw.gfx().banks[0].as_ref() {
bank.palettes[0][index % 16]
} else {
match index % 16 {
0 => Color::BLACK,
1 => Color::WHITE,
2 => Color::RED,
3 => Color::GREEN,
4 => Color::BLUE,
5 => Color::YELLOW,
6 => Color::CYAN,
7 => Color::INDIGO,
8 => Color::GRAY,
_ => Color::BLACK,
}
}
pub fn get_color(&self, value: i64) -> Color {
// Agora usamos o valor diretamente como RGB565.
Color::from_raw(value as u16)
}
// Helper para syscalls
pub fn get_button<'a>(&self, id: u32, hw: &'a dyn HardwareBridge) -> Option<&'a crate::model::Button> {
let pad = hw.pad();
match id {
0 => Some(&pad.up),
1 => Some(&pad.down),
2 => Some(&pad.left),
3 => Some(&pad.right),
4 => Some(&pad.a),
5 => Some(&pad.b),
6 => Some(&pad.x),
7 => Some(&pad.y),
8 => Some(&pad.l),
9 => Some(&pad.r),
10 => Some(&pad.start),
11 => Some(&pad.select),
_ => None,
}
}
pub fn is_button_down(&self, id: u32, hw: &mut dyn HardwareBridge) -> bool {
match id {
0 => hw.pad().up.down,
@@ -464,6 +469,17 @@ mod tests {
assert!(cycles_after_tick_2 > cycles_after_tick_1, "VM should have consumed more cycles because FrameSync reset the budget");
}
#[test]
fn test_get_color_logic() {
let os = PrometeuOS::new(None);
// Deve retornar a cor raw diretamente
assert_eq!(os.get_color(0x07E0), Color::GREEN);
assert_eq!(os.get_color(0xF800), Color::RED);
assert_eq!(os.get_color(0x001F), Color::BLUE);
assert_eq!(os.get_color(3), Color::from_raw(3));
}
#[test]
fn test_syscall_log_write_and_rate_limit() {
let mut os = PrometeuOS::new(None);
@@ -575,70 +591,70 @@ impl NativeInterface for PrometeuOS {
// gfx.clear(color_index) -> null
Syscall::GfxClear => {
let color_idx = vm.pop_integer()? as usize;
let color = self.get_color(color_idx, hw);
let color_val = vm.pop_integer()?;
let color = self.get_color(color_val);
hw.gfx_mut().clear(color);
vm.push(Value::Null);
Ok(100)
}
// gfx.draw_rect(x, y, w, h, color_index) -> null
Syscall::GfxFillRect => {
let color_idx = vm.pop_integer()? as usize;
let color_val = vm.pop_integer()?;
let h = vm.pop_integer()? as i32;
let w = vm.pop_integer()? as i32;
let y = vm.pop_integer()? as i32;
let x = vm.pop_integer()? as i32;
let color = self.get_color(color_idx, hw);
let color = self.get_color(color_val);
hw.gfx_mut().fill_rect(x, y, w, h, color);
vm.push(Value::Null);
Ok(200)
}
// gfx.draw_line(x1, y1, x2, y2, color_index) -> null
Syscall::GfxDrawLine => {
let color_idx = vm.pop_integer()? as usize;
let color_val = vm.pop_integer()?;
let y2 = vm.pop_integer()? as i32;
let x2 = vm.pop_integer()? as i32;
let y1 = vm.pop_integer()? as i32;
let x1 = vm.pop_integer()? as i32;
let color = self.get_color(color_idx, hw);
let color = self.get_color(color_val);
hw.gfx_mut().draw_line(x1, y1, x2, y2, color);
vm.push(Value::Null);
Ok(200)
}
// gfx.draw_circle(x, y, r, color_index) -> null
Syscall::GfxDrawCircle => {
let color_idx = vm.pop_integer()? as usize;
let color_val = vm.pop_integer()?;
let r = vm.pop_integer()? as i32;
let y = vm.pop_integer()? as i32;
let x = vm.pop_integer()? as i32;
let color = self.get_color(color_idx, hw);
let color = self.get_color(color_val);
hw.gfx_mut().draw_circle(x, y, r, color);
vm.push(Value::Null);
Ok(200)
}
// gfx.draw_disc(x, y, r, border_color_idx, fill_color_idx) -> null
Syscall::GfxDrawDisc => {
let fill_color_idx = vm.pop_integer()? as usize;
let border_color_idx = vm.pop_integer()? as usize;
let fill_color_val = vm.pop_integer()?;
let border_color_val = vm.pop_integer()?;
let r = vm.pop_integer()? as i32;
let y = vm.pop_integer()? as i32;
let x = vm.pop_integer()? as i32;
let fill_color = self.get_color(fill_color_idx, hw);
let border_color = self.get_color(border_color_idx, hw);
let fill_color = self.get_color(fill_color_val);
let border_color = self.get_color(border_color_val);
hw.gfx_mut().draw_disc(x, y, r, border_color, fill_color);
vm.push(Value::Null);
Ok(300)
}
// gfx.draw_square(x, y, w, h, border_color_idx, fill_color_idx) -> null
Syscall::GfxDrawSquare => {
let fill_color_idx = vm.pop_integer()? as usize;
let border_color_idx = vm.pop_integer()? as usize;
let fill_color_val = vm.pop_integer()?;
let border_color_val = vm.pop_integer()?;
let h = vm.pop_integer()? as i32;
let w = vm.pop_integer()? as i32;
let y = vm.pop_integer()? as i32;
let x = vm.pop_integer()? as i32;
let fill_color = self.get_color(fill_color_idx, hw);
let border_color = self.get_color(border_color_idx, hw);
let fill_color = self.get_color(fill_color_val);
let border_color = self.get_color(border_color_val);
hw.gfx_mut().draw_square(x, y, w, h, border_color, fill_color);
vm.push(Value::Null);
Ok(200)
@@ -653,6 +669,49 @@ impl NativeInterface for PrometeuOS {
vm.push(Value::Boolean(is_down));
Ok(50)
}
Syscall::InputGetPadPressed => {
let button_id = vm.pop_integer()? as u32;
let val = self.get_button(button_id, hw).map(|b| b.pressed).unwrap_or(false);
vm.push(Value::Boolean(val));
Ok(50)
}
Syscall::InputGetPadReleased => {
let button_id = vm.pop_integer()? as u32;
let val = self.get_button(button_id, hw).map(|b| b.released).unwrap_or(false);
vm.push(Value::Boolean(val));
Ok(50)
}
Syscall::InputGetPadHold => {
let button_id = vm.pop_integer()? as u32;
let val = self.get_button(button_id, hw).map(|b| b.hold_frames).unwrap_or(0);
vm.push(Value::Int32(val as i32));
Ok(50)
}
Syscall::TouchGetX => {
vm.push(Value::Int32(hw.touch().x));
Ok(50)
}
Syscall::TouchGetY => {
vm.push(Value::Int32(hw.touch().y));
Ok(50)
}
Syscall::TouchIsDown => {
vm.push(Value::Boolean(hw.touch().f.down));
Ok(50)
}
Syscall::TouchIsPressed => {
vm.push(Value::Boolean(hw.touch().f.pressed));
Ok(50)
}
Syscall::TouchIsReleased => {
vm.push(Value::Boolean(hw.touch().f.released));
Ok(50)
}
Syscall::TouchGetHold => {
vm.push(Value::Int32(hw.touch().f.hold_frames as i32));
Ok(50)
}
// --- Audio Syscalls ---
@@ -15,6 +15,16 @@ pub enum Syscall {
// Input
InputGetPad = 0x2001,
InputGetPadPressed = 0x2002,
InputGetPadReleased = 0x2003,
InputGetPadHold = 0x2004,
TouchGetX = 0x2101,
TouchGetY = 0x2102,
TouchIsDown = 0x2103,
TouchIsPressed = 0x2104,
TouchIsReleased = 0x2105,
TouchGetHold = 0x2106,
// Audio
AudioPlaySample = 0x3001,
@@ -45,6 +55,15 @@ impl Syscall {
0x1005 => Some(Self::GfxDrawDisc),
0x1006 => Some(Self::GfxDrawSquare),
0x2001 => Some(Self::InputGetPad),
0x2002 => Some(Self::InputGetPadPressed),
0x2003 => Some(Self::InputGetPadReleased),
0x2004 => Some(Self::InputGetPadHold),
0x2101 => Some(Self::TouchGetX),
0x2102 => Some(Self::TouchGetY),
0x2103 => Some(Self::TouchIsDown),
0x2104 => Some(Self::TouchIsPressed),
0x2105 => Some(Self::TouchIsReleased),
0x2106 => Some(Self::TouchGetHold),
0x3001 => Some(Self::AudioPlaySample),
0x4001 => Some(Self::FsOpen),
0x4002 => Some(Self::FsRead),
@@ -59,52 +78,71 @@ impl Syscall {
}
}
pub fn as_str(&self) -> &'static str {
match self {
Self::SystemHasCart => "system.has_cart",
Self::SystemRunCart => "system.run_cart",
Self::GfxClear => "gfx.clear",
Self::GfxFillRect => "gfx.fillRect",
Self::GfxDrawLine => "gfx.drawLine",
Self::GfxDrawCircle => "gfx.drawCircle",
Self::GfxDrawDisc => "gfx.drawDisc",
Self::GfxDrawSquare => "gfx.drawSquare",
Self::InputGetPad => "input.get_pad",
Self::AudioPlaySample => "audio.playSample",
Self::FsOpen => "fs.open",
Self::FsRead => "fs.read",
Self::FsWrite => "fs.write",
Self::FsClose => "fs.close",
Self::FsListDir => "fs.listDir",
Self::FsExists => "fs.exists",
Self::FsDelete => "fs.delete",
Self::LogWrite => "log.write",
Self::LogWriteTag => "log.writeTag",
}
}
// pub fn as_str(&self) -> &'static str {
// match self {
// Self::SystemHasCart => "system.has_cart",
// Self::SystemRunCart => "system.run_cart",
// Self::GfxClear => "gfx.clear",
// Self::GfxFillRect => "gfx.fillRect",
// Self::GfxDrawLine => "gfx.drawLine",
// Self::GfxDrawCircle => "gfx.drawCircle",
// Self::GfxDrawDisc => "gfx.drawDisc",
// Self::GfxDrawSquare => "gfx.drawSquare",
// Self::InputGetPad => "input.get_pad",
// Self::InputGetPadPressed => "input.get_pad_pressed",
// Self::InputGetPadReleased => "input.get_pad_released",
// Self::InputGetPadHold => "input.get_pad_hold",
// Self::TouchGetX => "touch.getX",
// Self::TouchGetY => "touch.getY",
// Self::TouchIsDown => "touch.isDown",
// Self::TouchIsPressed => "touch.isPressed",
// Self::TouchIsReleased => "touch.isReleased",
// Self::TouchGetHold => "touch.getHold",
// Self::AudioPlaySample => "audio.playSample",
// Self::FsOpen => "fs.open",
// Self::FsRead => "fs.read",
// Self::FsWrite => "fs.write",
// Self::FsClose => "fs.close",
// Self::FsListDir => "fs.listDir",
// Self::FsExists => "fs.exists",
// Self::FsDelete => "fs.delete",
// Self::LogWrite => "log.write",
// Self::LogWriteTag => "log.writeTag",
// }
// }
pub fn from_name(name: &str) -> Option<Self> {
match name {
"system.has_cart" => Some(Self::SystemHasCart),
"system.run_cart" => Some(Self::SystemRunCart),
"system.hasCart" | "system.has_cart" => Some(Self::SystemHasCart),
"gfx.clear" => Some(Self::GfxClear),
"gfx.fillRect" | "gfx.draw_rect" => Some(Self::GfxFillRect),
"gfx.drawLine" | "gfx.draw_line" => Some(Self::GfxDrawLine),
"gfx.drawCircle" | "gfx.draw_circle" => Some(Self::GfxDrawCircle),
"gfx.drawDisc" | "gfx.draw_disc" => Some(Self::GfxDrawDisc),
"gfx.drawSquare" | "gfx.draw_square" => Some(Self::GfxDrawSquare),
"input.get_pad" => Some(Self::InputGetPad),
"input.getPad" => Some(Self::InputGetPad),
"input.getPadPressed" | "input.get_pad_pressed" => Some(Self::InputGetPadPressed),
"input.getPadReleased" | "input.get_pad_released" => Some(Self::InputGetPadReleased),
"input.getPadHold" | "input.get_pad_hold" => Some(Self::InputGetPadHold),
"touch.getX" | "touch.get_x" => Some(Self::TouchGetX),
"touch.getY" | "touch.get_y" => Some(Self::TouchGetY),
"touch.isDown" | "touch.is_down" => Some(Self::TouchIsDown),
"touch.isPressed" | "touch.is_pressed" => Some(Self::TouchIsPressed),
"touch.isReleased" | "touch.is_released" => Some(Self::TouchIsReleased),
"touch.getHold" | "touch.get_hold" => Some(Self::TouchGetHold),
"audio.playSample" | "audio.play_sample" => Some(Self::AudioPlaySample),
"fs.open" => Some(Self::FsOpen),
"fs.read" => Some(Self::FsRead),
"fs.write" => Some(Self::FsWrite),
"fs.close" => Some(Self::FsClose),
"fs.listDir" => Some(Self::FsListDir),
"fs.listDir" | "fs.list_dir" => Some(Self::FsListDir),
"fs.exists" => Some(Self::FsExists),
"fs.delete" => Some(Self::FsDelete),
"log.write" => Some(Self::LogWrite),
"log.writeTag" => Some(Self::LogWriteTag),
_ => None,
"log.writeTag" | "log.write_tag" => Some(Self::LogWriteTag),
_ => {
None
}
}
}
}
+1 -1
View File
@@ -19,4 +19,4 @@ winit = "0.30.12"
pixels = "0.15.0"
cpal = "0.15.3"
ringbuf = "0.4.7"
serde_json = "1.0"
serde_json = "1.0.149"
@@ -0,0 +1,84 @@
pub mod audio;
pub mod runner;
pub mod fs_backend;
pub mod log_sink;
pub mod debugger;
pub mod stats;
pub mod input;
pub mod cap;
pub mod utilities;
use runner::HostRunner;
use cap::load_cap_config;
use winit::event_loop::EventLoop;
use prometeu_core::firmware::BootTarget;
pub fn run() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().collect();
let mut fs_root = None;
let mut cap_config = None;
let mut cartridge_path = None;
let mut debug_mode = false;
let mut debug_port = 7777;
let mut i = 1; // Skip the executable name
while i < args.len() {
match args[i].as_str() {
"--run" => {
if i + 1 < args.len() {
cartridge_path = Some(args[i + 1].clone());
debug_mode = false;
i += 1;
}
}
"--debug" => {
if i + 1 < args.len() {
cartridge_path = Some(args[i + 1].clone());
debug_mode = true;
i += 1;
}
}
"--port" => {
if i + 1 < args.len() {
if let Ok(port) = args[i + 1].parse::<u16>() {
debug_port = port;
}
i += 1;
}
}
"--fs-root" => {
if i + 1 < args.len() {
fs_root = Some(args[i + 1].clone());
i += 1;
}
}
"--cap" => {
if i + 1 < args.len() {
cap_config = load_cap_config(&args[i + 1]);
i += 1;
}
}
_ => {}
}
i += 1;
}
let boot_target = if let Some(path) = cartridge_path {
BootTarget::Cartridge {
path,
debug: debug_mode,
debug_port: if debug_mode { debug_port } else { 7777 },
}
} else {
BootTarget::Hub
};
let event_loop = EventLoop::new()?;
let mut runner = HostRunner::new(fs_root, cap_config);
runner.set_boot_target(boot_target);
event_loop.run_app(&mut runner)?;
Ok(())
}
+1 -82
View File
@@ -1,84 +1,3 @@
mod audio;
mod runner;
mod fs_backend;
mod log_sink;
mod debugger;
mod stats;
mod input;
mod cap;
mod utilities;
use crate::runner::HostRunner;
use crate::cap::load_cap_config;
use winit::event_loop::EventLoop;
use prometeu_core::firmware::BootTarget;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().collect();
let mut fs_root = None;
let mut cap_config = None;
let mut cartridge_path = None;
let mut debug_mode = false;
let mut debug_port = 7777;
let mut i = 1; // Skip the executable name
while i < args.len() {
match args[i].as_str() {
"--run" => {
if i + 1 < args.len() {
cartridge_path = Some(args[i + 1].clone());
debug_mode = false;
i += 1;
}
}
"--debug" => {
if i + 1 < args.len() {
cartridge_path = Some(args[i + 1].clone());
debug_mode = true;
i += 1;
}
}
"--port" => {
if i + 1 < args.len() {
if let Ok(port) = args[i + 1].parse::<u16>() {
debug_port = port;
}
i += 1;
}
}
"--fs-root" => {
if i + 1 < args.len() {
fs_root = Some(args[i + 1].clone());
i += 1;
}
}
"--cap" => {
if i + 1 < args.len() {
cap_config = load_cap_config(&args[i + 1]);
i += 1;
}
}
_ => {}
}
i += 1;
}
let boot_target = if let Some(path) = cartridge_path {
BootTarget::Cartridge {
path,
debug: debug_mode,
debug_port: if debug_mode { debug_port } else { 7777 },
}
} else {
BootTarget::Hub
};
let event_loop = EventLoop::new()?;
let mut runner = HostRunner::new(fs_root, cap_config);
runner.set_boot_target(boot_target);
event_loop.run_app(&mut runner)?;
Ok(())
prometeu_runtime_desktop::run()
}
+9 -16
View File
@@ -11,29 +11,22 @@ path = "src/main.rs"
[[bin]]
name = "prometeu-runtime"
path = "../prometeu-runtime-desktop/src/main.rs"
path = "src/bin/prometeu-runtime.rs"
# Future binaries (commented)
# [[bin]]
# name = "prometeuc"
# path = "../prometeuc/src/main.rs"
#
# [[bin]]
# name = "prometeup"
# path = "../prometeup/src/main.rs"
[[bin]]
name = "prometeuc"
path = "src/bin/prometeuc.rs"
[package.metadata.dist]
dist = true
include = [
"../../VERSION.txt",
"../../dist-staging/devtools-protocol"
"../../dist-staging/devtools/debugger-protocol",
"../../dist-staging/devtools/typescript-sdk"
]
[dependencies]
clap = { version = "4.5", features = ["derive"] }
prometeu-core = { path = "../prometeu-core" }
winit = "0.30.12"
pixels = "0.15.0"
cpal = "0.15.3"
ringbuf = "0.4.7"
serde_json = "1.0"
prometeu-runtime-desktop = { path = "../prometeu-runtime-desktop" }
prometeu-compiler = { path = "../prometeu-compiler" }
anyhow = "1.0.100"
+3 -1
View File
@@ -6,8 +6,10 @@ The `prometeu` binary acts as the unified front-end for the ecosystem. It does n
- `prometeu run <cart>`: Runs a cartridge using the available runtime.
- `prometeu debug <cart> [--port <p>]`: Starts execution in debug mode.
- `prometeu build <projectDir>`: (Planned) Calls the `prometeuc` compiler.
- `prometeu build <projectDir>`: Calls the `prometeuc` compiler.
- `prometeu verify c <projectDir>`: Calls the `prometeuc` compiler.
- `prometeu pack <cartDir>`: (Planned) Calls the `prometeup` packager.
- `prometeu verify p <cartDir>`: (Planned) Calls the `prometeup` packager.
## How it works
@@ -0,0 +1 @@
fn main() -> Result<(), Box<dyn std::error::Error>> { prometeu_runtime_desktop::run() }
+1
View File
@@ -0,0 +1 @@
fn main() -> anyhow::Result<()> { prometeu_compiler::run() }
+7 -5
View File
@@ -8,7 +8,7 @@ use std::process::Command;
/// The main entry point for the user. This binary does not implement
/// compilation or execution logic itself; instead, it acts as a smart
/// front-end that locates and dispatches commands to specialized
/// components like `prometeu-runtime-desktop` or `prometeuc`.
/// components like `prometeu-runtime-desktop` or `prometeu-compiler`.
#[derive(Parser)]
#[command(name = "prometeu")]
#[command(about = "Dispatcher for the Prometeu ecosystem", long_about = None)]
@@ -86,14 +86,16 @@ fn main() {
&["--debug", &cart, "--port", &port.to_string()],
);
}
Some(Commands::Build { .. }) => {
not_implemented("build", "prometeuc");
Some(Commands::Build { project_dir }) => {
dispatch(&exe_dir, "prometeuc", &["build", &project_dir]);
}
Some(Commands::Pack { .. }) => {
not_implemented("pack", "prometeup");
}
Some(Commands::Verify { target }) => match target {
VerifyCommands::C { .. } => not_implemented("verify c", "prometeuc"),
VerifyCommands::C { project_dir } => {
dispatch(&exe_dir, "prometeuc", &["verify", &project_dir]);
}
VerifyCommands::P { .. } => not_implemented("verify p", "prometeup"),
},
None => {
@@ -119,7 +121,7 @@ fn dispatch(exe_dir: &Path, bin_name: &str, args: &[&str]) {
eprintln!(
"prometeu: command '{}' is not yet available in this distribution on {}",
match bin_name {
"prometeu-runtime-desktop" => "run/debug",
"prometeu-runtime" => "run/debug",
"prometeuc" => "build/verify c",
"prometeup" => "pack/verify p",
_ => bin_name,
-16
View File
@@ -1,16 +0,0 @@
[package]
name = "prometeuc"
version = "0.1.0"
edition = "2021"
[dependencies]
prometeu-bytecode = { path = "../prometeu-bytecode" }
prometeu-core = { path = "../prometeu-core" }
oxc_parser = "0.48.0"
oxc_allocator = "0.48.0"
oxc_ast = "0.48.0"
oxc_span = "0.48.0"
clap = { version = "4.4", features = ["derive"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
anyhow = "1.0"
-324
View File
@@ -1,324 +0,0 @@
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 crate::compiler::Symbol;
use crate::syscall_map;
use std::collections::HashMap;
pub struct Codegen {
file_name: String,
source_text: String,
pub symbols: Vec<Symbol>,
instructions: Vec<(Asm, bool)>, // (Asm, has_symbol)
locals: HashMap<String, u32>,
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(),
next_local: 0,
label_count: 0,
}
}
pub fn compile_program(&mut self, program: &Program) -> Result<Vec<u8>> {
// Find tick function
let mut tick_fn = None;
for item in &program.body {
if let Statement::ExportNamedDeclaration(decl) = item {
if let Some(Declaration::FunctionDeclaration(f)) = &decl.declaration {
if let Some(ident) = &f.id {
if ident.name == "tick" {
tick_fn = Some(f);
break;
}
}
}
}
}
let tick_fn = tick_fn.ok_or_else(|| anyhow!("export function tick() not found"))?;
// Entry point: loop calling tick
self.emit_label("entry".to_string());
self.emit_op(OpCode::Call, vec![Operand::Label("tick".to_string()), Operand::U32(0)], Span::default());
self.emit_op(OpCode::FrameSync, vec![], Span::default());
self.emit_op(OpCode::Jmp, vec![Operand::Label("entry".to_string())], Span::default());
// Function tick
self.emit_label("tick".to_string());
self.compile_function(tick_fn)?;
self.emit_op(OpCode::Ret, vec![], Span::default());
let asm_vec: Vec<Asm> = self.instructions.iter().map(|(a, _)| a.clone()).collect();
let rom = assemble(&asm_vec).map_err(|e| anyhow!("Assemble error: {}", e))?;
// Finalize symbols (associate PC)
self.finalize_symbols();
Ok(rom)
}
fn compile_function(&mut self, f: &Function) -> Result<()> {
self.locals.clear();
self.next_local = 0;
if let Some(body) = &f.body {
for stmt in &body.statements {
self.compile_stmt(stmt)?;
}
}
Ok(())
}
fn compile_stmt(&mut self, stmt: &Statement) -> Result<()> {
match stmt {
Statement::VariableDeclaration(var) => {
for decl in &var.declarations {
if let BindingPatternKind::BindingIdentifier(ident) = &decl.id.kind {
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.emit_op(OpCode::SetLocal, vec![Operand::U32(id)], decl.span);
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) => {
for stmt in &block.body {
self.compile_stmt(stmt)?;
}
}
_ => 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::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::Dup, vec![], assign.span);
self.emit_op(OpCode::SetLocal, 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 = self.get_callee_name(&call.callee)?;
if let Some(syscall_id) = syscall_map::map_syscall(&name) {
if name == "input.btnA" {
self.emit_op(OpCode::PushI32, vec![Operand::I32(syscall_map::BTN_A as i32)], call.span);
} else if name == "input.btnB" {
self.emit_op(OpCode::PushI32, vec![Operand::I32(syscall_map::BTN_B as i32)], 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 {
return Err(anyhow!("Unsupported function call: {} at {:?}", name, call.span));
}
}
Expression::StaticMemberExpression(member) => {
let obj = self.get_callee_name_from_member_obj(&member.object)?;
let prop = member.property.name.to_string();
let full_name = format!("{}.{}", obj, prop);
// If it's used as a value (GetGlobal/GetLocal?), but for now we only support it in calls
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 get_callee_name(&self, expr: &Expression) -> Result<String> {
match expr {
Expression::Identifier(ident) => Ok(ident.name.to_string()),
Expression::StaticMemberExpression(member) => {
let obj = self.get_callee_name_from_member_obj(&member.object)?;
let prop = member.property.name.to_string();
Ok(format!("{}.{}", obj, prop))
}
_ => Err(anyhow!("Unsupported callee expression at {:?}", expr.span())),
}
}
fn get_callee_name_from_member_obj(&self, expr: &Expression) -> Result<String> {
if let Expression::Identifier(ident) = expr {
Ok(ident.name.to_string())
} else {
Err(anyhow!("Unsupported member object expression"))
}
}
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;
for operand in operands {
match operand {
Operand::U32(_) | Operand::I32(_) | Operand::Label(_) => current_pc += 4,
Operand::I64(_) | Operand::F64(_) => current_pc += 8,
Operand::Bool(_) => current_pc += 1,
}
}
}
}
}
}
}
-72
View File
@@ -1,72 +0,0 @@
use std::path::Path;
use anyhow::{Result, Context};
use oxc_allocator::Allocator;
use oxc_parser::Parser;
use oxc_span::SourceType;
use crate::codegen::Codegen;
use std::fs;
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 fn compile(entry: &Path, out: &Path, emit_disasm: bool, emit_symbols: bool) -> Result<()> {
let source_text = fs::read_to_string(entry)
.with_context(|| format!("Failed to read entry file: {:?}", entry))?;
let allocator = Allocator::default();
let source_type = SourceType::from_path(entry).unwrap_or_default();
let mut codegen = Codegen::new(entry.to_string_lossy().to_string(), source_text.clone());
let rom = {
let ret = Parser::new(&allocator, &source_text, source_type).parse();
if !ret.errors.is_empty() {
for error in ret.errors {
eprintln!("{:?}", error);
}
return Err(anyhow::anyhow!("Failed to parse module"));
}
codegen.compile_program(&ret.program)?
};
fs::write(out, &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(&codegen.symbols)?;
fs::write(&symbols_path, symbols_json)?;
}
if emit_disasm {
let disasm_path = out.with_extension("disasm.txt");
let instructions = disasm(&rom).map_err(|e| anyhow::anyhow!("Disassembly failed: {}", e))?;
let mut disasm_text = String::new();
for instr in instructions {
let symbol = codegen.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(())
}