clean up, debugger, add comments

This commit is contained in:
Nilton Constantino
2026-01-23 06:52:31 +00:00
parent 5ac24e5491
commit a7b824fe21
60 changed files with 1033 additions and 557 deletions
-40
View File
@@ -1,40 +0,0 @@
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,
},
}
@@ -1,15 +1,23 @@
use anyhow::{anyhow, Result};
use oxc_ast::ast::*;
use anyhow::{Result, anyhow};
/// Extracts the name of the function being called from a CallExpression.
pub fn get_callee_name(expr: &Expression) -> Result<String> {
get_member_expr_name(expr)
}
/// Recursively extracts a full name from an identifier or a member expression.
///
/// Example:
/// - `foo` -> "foo"
/// - `Color.RED` -> "Color.RED"
/// - `PGfx.drawRect` -> "Gfx.drawRect" (Stripping 'P' prefix if appropriate)
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)
// Prometeu SDK uses 'P' prefix for some internal names to avoid conflicts
// with standard JS identifiers. We strip it here to match the ISA names.
if name.len() > 1 && name.starts_with('P') && name.chars().nth(1).unwrap().is_uppercase() {
Ok(name[1..].to_string())
} else {
@@ -21,6 +29,6 @@ pub fn get_member_expr_name(expr: &Expression) -> Result<String> {
let prop = member.property.name.to_string();
Ok(format!("{}.{}", obj, prop))
}
_ => Err(anyhow!("Unsupported expression")),
_ => Err(anyhow!("Unsupported expression for name resolution")),
}
}
+137 -71
View File
@@ -1,31 +1,47 @@
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 crate::codegen::{input_map, syscall_map};
use crate::compiler::Symbol;
use anyhow::{anyhow, Result};
use oxc_ast::ast::*;
use oxc_span::{GetSpan, Span};
use prometeu_bytecode::asm;
use prometeu_bytecode::asm::{assemble, Asm, Operand};
use prometeu_bytecode::opcode::OpCode;
use prometeu_bytecode::pbc::{write_pbc, ConstantPoolEntry, PbcFile};
use prometeu_core::hardware::Syscall;
use prometeu_core::model::Color;
use std::collections::HashMap;
/// The core Code Generator for the Prometeu Compiler.
///
/// It maintains the state of the compilation process, including symbol tables,
/// local/global variable mapping, and the constant pool.
pub struct Codegen {
/// Name of the file being compiled (used for debug symbols).
file_name: String,
/// Full source code of the file (used for position lookup).
source_text: String,
/// Collected debug symbols mapping PC to source lines.
pub symbols: Vec<Symbol>,
instructions: Vec<(Asm, bool)>, // (Asm, has_symbol)
/// The stream of generated assembly instructions.
/// The boolean indicates if the instruction should have a debug symbol attached.
instructions: Vec<(Asm, bool)>,
/// Mapping of local variable names to their stack offsets in the current frame.
locals: HashMap<String, u32>,
/// Mapping of global variable names to their slots in the VM's global memory.
globals: HashMap<String, u32>,
/// The Constant Pool, which stores unique values (strings, large numbers).
constant_pool: Vec<ConstantPoolEntry>,
/// Counter for the next available local variable ID.
next_local: u32,
/// Counter for the next available global variable ID.
next_global: u32,
/// Counter for generating unique labels (e.g., for 'if' or 'while' blocks).
label_count: u32,
}
impl Codegen {
/// Creates a new Codegen instance for a specific file.
pub fn new(file_name: String, source_text: String) -> Self {
Self {
file_name,
@@ -41,6 +57,8 @@ impl Codegen {
}
}
/// Adds a value to the Constant Pool and returns its index.
/// If the value already exists, it returns the existing index.
fn add_constant(&mut self, entry: ConstantPoolEntry) -> u32 {
if let Some(pos) = self.constant_pool.iter().position(|e| e == &entry) {
pos as u32
@@ -51,53 +69,54 @@ impl Codegen {
}
}
/// Entry point for compiling a single Program (AST).
pub fn compile_program(&mut self, program: &Program) -> Result<Vec<u8>> {
self.compile_programs(vec![(self.file_name.clone(), self.source_text.clone(), program)])
}
/// Compiles multiple programs (files) into a single Prometeu executable (.pbc).
///
/// The compilation process follows several steps:
/// 1. Collection of global symbols (functions and variables).
/// 2. Entry point verification (`frame` function).
/// 3. Global variable initialization.
/// 4. Main system loop generation.
/// 5. Compilation of all function bodies.
/// 6. Assembly and symbol resolution.
pub fn compile_programs(&mut self, programs: Vec<(String, String, &Program)>) -> Result<Vec<u8>> {
// First pass: collect all functions and global variables
// --- FIRST PASS: Global Functions and Variables Collection ---
// In this stage, we iterate through all files to register the existence of functions
// and global variables before starting code generation. This allows a
// function to call another that was defined later or in another file.
let mut all_functions = Vec::new();
for (file, source, program) in &programs {
for item in &program.body {
match item {
// Standard function declaration: function foo() { ... }
Statement::FunctionDeclaration(f) => {
all_functions.push((file.clone(), source.clone(), f.as_ref()));
}
// Exported declaration: export function foo() ... or export const x = 1;
Statement::ExportNamedDeclaration(decl) => {
if let Some(Declaration::FunctionDeclaration(f)) = &decl.declaration {
all_functions.push((file.clone(), source.clone(), f.as_ref()));
} else if let Some(Declaration::VariableDeclaration(var)) = &decl.declaration {
for decl in &var.declarations {
if let BindingPattern::BindingIdentifier(ident) = &decl.id {
let name = ident.name.to_string();
if !self.globals.contains_key(&name) {
let id = self.next_global;
self.globals.insert(name, id);
self.next_global += 1;
}
}
}
self.export_global_variable_declarations(&var);
}
}
// Global variable declaration: var x = 1;
Statement::VariableDeclaration(var) => {
for decl in &var.declarations {
if let BindingPattern::BindingIdentifier(ident) = &decl.id {
let name = ident.name.to_string();
if !self.globals.contains_key(&name) {
let id = self.next_global;
self.globals.insert(name, id);
self.next_global += 1;
}
}
}
self.export_global_variable_declarations(&var);
}
_ => {}
}
}
}
// Find frame function (should be in the first program, which is the entry)
// --- ENTRY POINT VERIFICATION ---
// Prometeu requires a function named `frame()` in the main file (the first in the list).
// This function is called automatically every logical frame, which is supposed to
// be close to the tick (60Hz).
let mut frame_fn_name = None;
if let Some((_, _, entry_program)) = programs.first() {
for item in &entry_program.body {
@@ -126,7 +145,9 @@ impl Codegen {
let frame_fn_name = frame_fn_name.ok_or_else(|| anyhow!("export function frame() not found in entry file"))?;
// Initialize globals
// --- GLOBAL INITIALIZATION ---
// Here we generate the code that will be executed as soon as the program loads.
// It evaluates the initialization expressions of global variables and stores them.
for (file, source, program) in &programs {
self.file_name = file.clone();
self.source_text = source.clone();
@@ -149,10 +170,13 @@ impl Codegen {
let name = ident.name.to_string();
let id = *self.globals.get(&name).unwrap();
if let Some(init) = &decl.init {
// Compiles the initialization expression (e.g., the "10" in "var x = 10")
self.compile_expr(init)?;
} else {
// If there is no initializer, it defaults to 0 (I32)
self.emit_op(OpCode::PushI32, vec![Operand::I32(0)], decl.span);
}
// Stores the resulting value in the global variable slot
self.emit_op(OpCode::SetGlobal, vec![Operand::U32(id)], decl.span);
}
}
@@ -160,39 +184,74 @@ impl Codegen {
}
}
// Entry point: loop calling frame
// --- EXECUTION LOOP GENERATION (ENTRY POINT) ---
// After initializing globals, the code enters an infinite loop that:
// 1. Calls the frame() function.
// 2. Clears the return value from the stack (Prometeu ABI requires functions to leave 1 value).
// 3. Synchronizes with hardware (FrameSync - waits for the next VSync).
// 4. Jumps back to the start of the loop.
self.emit_label("entry".to_string());
self.emit_op(OpCode::Call, vec![Operand::Label(frame_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
// --- FUNCTION COMPILATION ---
// Compiles the body of each function collected in the first pass.
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();
// Each function starts with a label with its name to be resolved by Call
self.emit_label(name);
self.compile_function(f)?;
// Ensures the function returns to the caller
self.emit_op(OpCode::Ret, vec![], Span::default());
}
}
// --- FINAL PHASE: ASSEMBLY AND PACKAGING ---
// 1. Converts the list of instructions into raw bytecode
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)
// 2. Resolves label addresses to real bytecode positions (PC)
self.finalize_symbols();
// 3. Builds the PBC file structure (Constant Pool + Bytecode)
let pbc = PbcFile {
cp: self.constant_pool.clone(),
rom: bytecode,
};
// 4. Serializes to the final binary format
write_pbc(&pbc).map_err(|e| anyhow!("PBC Write error: {}", e))
}
/// Registers a global variable in the symbol table.
/// Global variables are accessible from any function and persist between frames.
fn export_global_variable_declarations(&mut self, var: &VariableDeclaration) {
for decl in &var.declarations {
if let BindingPattern::BindingIdentifier(ident) = &decl.id {
let name = ident.name.to_string();
if !self.globals.contains_key(&name) {
let id = self.next_global;
self.globals.insert(name, id);
self.next_global += 1;
}
}
}
}
/// Compiles a function declaration.
///
/// Functions in Prometeu follow the ABI:
/// 1. Parameters are mapped to the first `n` local slots.
/// 2. `PushScope` is called to protect the caller's environment.
/// 3. The body is compiled sequentially.
/// 4. `PopScope` and `Push Null` are executed before `Ret` to ensure the stack rule.
fn compile_function(&mut self, f: &Function) -> Result<()> {
self.locals.clear();
self.next_local = 0;
@@ -200,7 +259,7 @@ impl Codegen {
// Start scope for parameters and local variables
self.emit_op(OpCode::PushScope, vec![], f.span);
// Map parameters to locals
// Map parameters to locals (they are pushed by the caller before the Call instruction)
for param in &f.params.items {
if let BindingPattern::BindingIdentifier(ident) = &param.pattern {
let name = ident.name.to_string();
@@ -218,15 +277,15 @@ impl Codegen {
// 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(())
}
/// Translates a Statement into bytecode.
fn compile_stmt(&mut self, stmt: &Statement) -> Result<()> {
match stmt {
// var x = 10;
Statement::VariableDeclaration(var) => {
for decl in &var.declarations {
if let BindingPattern::BindingIdentifier(ident) = &decl.id {
@@ -234,6 +293,7 @@ impl Codegen {
if let Some(init) = &decl.init {
self.compile_expr(init)?;
} else {
// Default initialization to 0
self.emit_op(OpCode::PushI32, vec![Operand::I32(0)], decl.span);
}
let id = self.next_local;
@@ -242,10 +302,13 @@ impl Codegen {
}
}
}
// console.log("hello");
Statement::ExpressionStatement(expr_stmt) => {
self.compile_expr(&expr_stmt.expression)?;
// ABI requires us to Pop unused return values from the stack to prevent leaks
self.emit_op(OpCode::Pop, vec![], expr_stmt.span);
}
// if (a == b) { ... } else { ... }
Statement::IfStatement(if_stmt) => {
let else_label = self.new_label("else");
let end_label = self.new_label("end_if");
@@ -263,6 +326,7 @@ impl Codegen {
self.emit_label(end_label);
}
// { let x = 1; }
Statement::BlockStatement(block) => {
self.emit_op(OpCode::PushScope, vec![], block.span);
for stmt in &block.body {
@@ -275,8 +339,11 @@ impl Codegen {
Ok(())
}
/// Translates an Expression into bytecode.
/// Expressions always leave exactly one value at the top of the stack.
fn compile_expr(&mut self, expr: &Expression) -> Result<()> {
match expr {
// Literals: push the value directly onto the stack
Expression::NumericLiteral(n) => {
let val = n.value;
if val.fract() == 0.0 && val >= i32::MIN as f64 && val <= i32::MAX as f64 {
@@ -295,6 +362,7 @@ impl Codegen {
Expression::NullLiteral(n) => {
self.emit_op(OpCode::PushConst, vec![Operand::U32(0)], n.span);
}
// Variable access: resolve to GetLocal or GetGlobal
Expression::Identifier(ident) => {
let name = ident.name.to_string();
if let Some(&id) = self.locals.get(&name) {
@@ -305,13 +373,14 @@ impl Codegen {
return Err(anyhow!("Undefined variable: {} at {:?}", name, ident.span));
}
}
// Assignment: evaluate RHS and store result in LHS slot
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);
self.emit_op(OpCode::GetLocal, vec![Operand::U32(id)], assign.span); // Assignment returns the value
} else if let Some(&id) = self.globals.get(&name) {
self.emit_op(OpCode::SetGlobal, vec![Operand::U32(id)], assign.span);
self.emit_op(OpCode::GetGlobal, vec![Operand::U32(id)], assign.span);
@@ -322,6 +391,7 @@ impl Codegen {
return Err(anyhow!("Unsupported assignment target at {:?}", assign.span));
}
}
// Binary operations: evaluate both sides and apply the opcode
Expression::BinaryExpression(bin) => {
self.compile_expr(&bin.left)?;
self.compile_expr(&bin.right)?;
@@ -340,6 +410,7 @@ impl Codegen {
};
self.emit_op(op, vec![], bin.span);
}
// Logical operations: evaluate both sides and apply the opcode
Expression::LogicalExpression(log) => {
self.compile_expr(&log.left)?;
self.compile_expr(&log.right)?;
@@ -350,6 +421,7 @@ impl Codegen {
};
self.emit_op(op, vec![], log.span);
}
// Unary operations: evaluate argument and apply the opcode
Expression::UnaryExpression(unary) => {
self.compile_expr(&unary.argument)?;
let op = match unary.operator {
@@ -360,19 +432,18 @@ impl Codegen {
};
self.emit_op(op, vec![], unary.span);
}
// Function calls: resolve to Syscall or Call
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)
// Special case for Color.rgb(r, g, b)
// It's compiled to a sequence of bitwise operations for performance
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
// Argument 0: r (shift right 3, shift left 11)
if let Some(expr) = call.arguments[0].as_expression() {
self.compile_expr(expr)?;
self.emit_op(OpCode::PushI32, vec![Operand::I32(3)], call.span);
@@ -381,7 +452,7 @@ impl Codegen {
self.emit_op(OpCode::Shl, vec![], call.span);
}
// Argument 1: g
// Argument 1: g (shift right 2, shift left 5)
if let Some(expr) = call.arguments[1].as_expression() {
self.compile_expr(expr)?;
self.emit_op(OpCode::PushI32, vec![Operand::I32(2)], call.span);
@@ -392,7 +463,7 @@ impl Codegen {
self.emit_op(OpCode::BitOr, vec![], call.span);
// Argument 2: b
// Argument 2: b (shift right 3)
if let Some(expr) = call.arguments[2].as_expression() {
self.compile_expr(expr)?;
self.emit_op(OpCode::PushI32, vec![Operand::I32(3)], call.span);
@@ -402,6 +473,7 @@ impl Codegen {
self.emit_op(OpCode::BitOr, vec![], call.span);
} else {
// Standard System Call
for arg in &call.arguments {
if let Some(expr) = arg.as_expression() {
self.compile_expr(expr)?;
@@ -410,7 +482,7 @@ impl Codegen {
self.emit_op(OpCode::Syscall, vec![Operand::U32(syscall_id)], call.span);
}
} else {
// Local function call
// Local function call (to a function defined in the project)
for arg in &call.arguments {
if let Some(expr) = arg.as_expression() {
self.compile_expr(expr)?;
@@ -419,10 +491,12 @@ impl Codegen {
self.emit_op(OpCode::Call, vec![Operand::Label(name), Operand::U32(call.arguments.len() as u32)], call.span);
}
}
// Member access (e.g., Color.RED, Pad.A.down)
Expression::StaticMemberExpression(member) => {
let full_name = ast_util::get_member_expr_name(expr)?;
if full_name.to_lowercase().starts_with("color.") {
// Resolved at compile-time to literal values
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),
@@ -435,15 +509,16 @@ impl Codegen {
"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),
"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.") {
// Re-mapped to specific input syscalls
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 btn_id = input_map::map_btn_name(btn_name)?;
let syscall_id = match state_name {
"down" => Syscall::InputGetPad as u32,
"pressed" => Syscall::InputGetPadPressed as u32,
@@ -457,6 +532,7 @@ impl Codegen {
return Err(anyhow!("Partial Pad access not supported: {} at {:?}", full_name, member.span));
}
} else if full_name.to_lowercase().starts_with("touch.") {
// Re-mapped to specific touch syscalls
let parts: Vec<&str> = full_name.split('.').collect();
match parts.len() {
2 => {
@@ -490,39 +566,25 @@ impl Codegen {
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)),
}
}
/// Generates a new unique label name for control flow.
fn new_label(&mut self, prefix: &str) -> String {
let label = format!("{}_{}", prefix, self.label_count);
self.label_count += 1;
label
}
/// Emits a label definition in the instruction stream.
fn emit_label(&mut self, name: String) {
self.instructions.push((Asm::Label(name), false));
}
/// Emits an OpCode and its operands into the instruction stream.
/// Also records a debug symbol if the source span is available.
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,
pc: 0, // Will be resolved during finalize_symbols
file: self.file_name.clone(),
line,
col,
@@ -534,6 +596,7 @@ impl Codegen {
self.instructions.push((Asm::Op(opcode, operands), has_symbol));
}
/// Converts a character position (offset) into line and column numbers.
fn lookup_pos(&self, pos: u32) -> (usize, usize) {
let mut line = 1;
let mut col = 1;
@@ -551,6 +614,9 @@ impl Codegen {
(line, col)
}
/// Second pass of symbol resolution.
/// After the final PC for each instruction is known (via `assemble`),
/// this function updates the `pc` field in all debug symbols.
fn finalize_symbols(&mut self) {
let mut current_pc = 0u32;
let mut symbol_ptr = 0;
@@ -564,7 +630,7 @@ impl Codegen {
symbol_ptr += 1;
}
current_pc += 2;
current_pc += 2; // OpCode size (u16)
current_pc = asm::update_pc_by_operand(current_pc, operands);
}
}
+14 -1
View File
@@ -1,5 +1,18 @@
//! # Codegen Module
//!
//! This module is responsible for translating the High-Level AST into
//! Low-Level Prometeu ByteCode instructions.
//!
//! It consists of:
//! - **codegen.rs**: The main engine that traverses the AST and maintains the compiler state.
//! - **validator.rs**: A pre-flight check to ensure the AST only contains supported constructs.
//! - **syscall_map.rs**: A bridge between high-level JS functions and virtual machine syscall IDs.
//! - **ast_util.rs**: Convenience functions for extracting information from OXC AST nodes.
pub mod codegen;
pub mod validator;
pub mod ast_util;
pub mod syscall_map;
mod input_map;
pub use codegen::Codegen;
pub use codegen::Codegen;
@@ -0,0 +1,20 @@
use prometeu_core::hardware::Syscall;
/// Maps a High-Level function name to its corresponding Virtual Machine Syscall ID.
///
/// The Prometeu VM exposes hardware functionality (Graphics, Audio, I/O) through
/// a syscall interface. This function allows the compiler to recognize these
/// calls and emit the `Syscall <id>` opcode.
pub fn map_syscall(name: &str) -> Option<u32> {
// Check if the name matches a standard syscall defined in the core firmware
if let Some(syscall) = Syscall::from_name(name) {
return Some(syscall as u32);
}
// Handle special compiler intrinsics that don't map 1:1 to a single syscall ID.
match name {
// Color.rgb(r,g,b) is expanded to bitwise logic by the codegen
"Color.rgb" | "color.rgb" => Some(0xFFFF_FFFF),
_ => None,
}
}
@@ -1,23 +1,35 @@
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;
use crate::codegen::syscall_map;
use anyhow::{anyhow, Result};
use oxc_ast::ast::*;
use oxc_ast_visit::{walk, Visit};
use oxc_span::GetSpan;
/// AST Visitor that ensures the source code follows the Prometeu subset of JS/TS.
///
/// Since the Prometeu Virtual Machine is highly optimized and focused on game logic,
/// it does not support the full ECMA-262 specification (e.g., no `async`, `class`,
/// `try/catch`, or `generators`).
pub struct Validator {
/// List of validation errors found during the pass.
errors: Vec<String>,
/// Set of function names defined in the project, used to distinguish
/// local calls from invalid references.
local_functions: std::collections::HashSet<String>,
}
impl Validator {
/// Performs a full validation pass on a program.
///
/// Returns `Ok(())` if the program is valid, or a combined error message
/// listing all violations.
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
// 1. Discovery Pass: Collect all function names and imports
for item in &program.body {
match item {
Statement::FunctionDeclaration(f) => {
@@ -53,7 +65,7 @@ impl Validator {
}
}
// 2. Recursive validation of the AST
// 2. Traversal Pass: Check every node for compatibility
validator.visit_program(program);
if validator.errors.is_empty() {
@@ -65,6 +77,7 @@ impl Validator {
}
impl<'a> Visit<'a> for Validator {
/// Validates that only supported statements are used.
fn visit_statement(&mut self, stmt: &Statement<'a>) {
match stmt {
Statement::VariableDeclaration(_) |
@@ -74,15 +87,16 @@ impl<'a> Visit<'a> for Validator {
Statement::ExportNamedDeclaration(_) |
Statement::ImportDeclaration(_) |
Statement::FunctionDeclaration(_) => {
// Supported
// These are the only statements the PVM handles currently.
walk::walk_statement(self, stmt);
}
_ => {
self.errors.push(format!("Unsupported statement type at {:?}", stmt.span()));
self.errors.push(format!("Unsupported statement type at {:?}. Note: Prometeu does not support while/for loops or classes yet.", stmt.span()));
}
}
}
/// Validates that only supported expressions are used.
fn visit_expression(&mut self, expr: &Expression<'a>) {
match expr {
Expression::NumericLiteral(_) |
@@ -96,11 +110,11 @@ impl<'a> Visit<'a> for Validator {
Expression::UnaryExpression(_) |
Expression::CallExpression(_) |
Expression::StaticMemberExpression(_) => {
// Base types supported, detailed checks in specific visit methods if needed
// Basic JS logic is supported.
walk::walk_expression(self, expr);
}
_ => {
self.errors.push(format!("Unsupported expression type at {:?}", expr.span()));
self.errors.push(format!("Unsupported expression type at {:?}. Note: Closures, arrow functions, and object literals are not yet supported.", expr.span()));
}
}
}
+51 -14
View File
@@ -1,43 +1,62 @@
use std::path::{Path, PathBuf};
use anyhow::{Result, Context, anyhow};
use crate::codegen::validator::Validator;
use crate::codegen::Codegen;
use anyhow::{anyhow, Context, Result};
use oxc_allocator::Allocator;
use oxc_ast::ast::*;
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;
use std::collections::{HashMap, VecDeque};
use std::fs;
use std::path::{Path, PathBuf};
/// Represents a debug symbol that maps a Program Counter (PC) to a specific
/// source code location.
#[derive(Serialize)]
pub struct Symbol {
/// The absolute address in the bytecode.
pub pc: u32,
/// The original source file path.
pub file: String,
/// 1-based line number.
pub line: usize,
/// 1-based column number.
pub col: usize,
}
/// The result of a successful compilation process.
/// It contains the final binary and the metadata needed for debugging.
pub struct CompilationUnit {
/// The raw binary data (PBC format).
pub rom: Vec<u8>,
/// The list of debug symbols for source mapping.
pub symbols: Vec<Symbol>,
}
impl CompilationUnit {
/// Writes the compilation results to the disk.
///
/// # Arguments
/// * `out` - The target path for the .pbc file.
/// * `emit_disasm` - If true, generates a .disasm.txt file next to the output.
/// * `emit_symbols` - If true, generates a symbols.json file for debuggers.
pub fn export(&self, out: &Path, emit_disasm: bool, emit_symbols: bool) -> Result<()> {
// 1. Save the main binary
fs::write(out, &self.rom).with_context(|| format!("Failed to write PBC to {:?}", out))?;
// 2. Export symbols for the HostDebugger
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)?;
}
// 3. Export human-readable disassembly for developer inspection
if emit_disasm {
let disasm_path = out.with_extension("disasm.txt");
// Try to parse as PBC, if fails use raw
// Extract the actual bytecode (stripping the PBC header if present)
let rom_to_disasm = if let Ok(pbc) = prometeu_bytecode::pbc::parse_pbc(&self.rom) {
pbc.rom
} else {
@@ -48,6 +67,7 @@ impl CompilationUnit {
let mut disasm_text = String::new();
for instr in instructions {
// Find a matching symbol to show which source line generated this instruction
let symbol = self.symbols.iter().find(|s| s.pc == instr.pc);
let comment = if let Some(s) = symbol {
format!(" ; {}:{}", s.file, s.line)
@@ -69,8 +89,11 @@ impl CompilationUnit {
}
}
/// Helper to resolve import paths (e.g., converting './utils' to './utils.ts').
fn resolve_import(base_path: &Path, import_str: &str) -> Result<PathBuf> {
let mut path = base_path.parent().unwrap().join(import_str);
// Auto-append extensions if missing
if !path.exists() {
if path.with_extension("ts").exists() {
path.set_extension("ts");
@@ -78,36 +101,48 @@ fn resolve_import(base_path: &Path, import_str: &str) -> Result<PathBuf> {
path.set_extension("js");
}
}
if !path.exists() {
return Err(anyhow!("Cannot resolve import '{}' from {:?}", import_str, base_path));
}
Ok(path.canonicalize()?)
}
/// Orchestrates the compilation of a Prometeu project starting from an entry file.
///
/// This function:
/// 1. Crawls the import graph to find all dependencies.
/// 2. Parses each file using `oxc`.
/// 3. Validates that the code adheres to Prometeu's restricted JS/TS subset.
/// 4. Hands over all programs to the `Codegen` for binary generation.
pub fn compile(entry: &Path) -> Result<CompilationUnit> {
let allocator = Allocator::default();
let mut modules = HashMap::new();
let mut queue = VecDeque::new();
// Start with the entry point
let entry_abs = entry.canonicalize()
.with_context(|| format!("Failed to canonicalize entry path: {:?}", entry))?;
queue.push_back(entry_abs.clone());
// --- PHASE 1: Dependency Resolution and Parsing ---
while let Some(path) = queue.pop_front() {
let path_str = path.to_string_lossy().to_string();
if modules.contains_key(&path_str) {
continue;
continue; // Already processed
}
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
// We use an Allocator to manage the lifetime of AST nodes and source strings efficiently
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();
// Handle syntax errors immediately
if !parser_ret.errors.is_empty() {
for error in parser_ret.errors {
eprintln!("{:?}", error);
@@ -115,10 +150,11 @@ pub fn compile(entry: &Path) -> Result<CompilationUnit> {
return Err(anyhow!("Failed to parse module: {:?}", path));
}
// Validate individual module
// --- PHASE 2: Individual Module Validation ---
// Checks for things like 'class' or 'async' which are not supported by PVM.
Validator::validate(&parser_ret.program)?;
// Find imports to add to queue
// Discover new imports to crawl
for item in &parser_ret.program.body {
if let Statement::ImportDeclaration(decl) = item {
let import_path = decl.source.value.as_str();
@@ -130,14 +166,15 @@ pub fn compile(entry: &Path) -> Result<CompilationUnit> {
modules.insert(path_str, (source_text_ptr, parser_ret.program));
}
// --- PHASE 3: Code Generation ---
let entry_str = entry_abs.to_string_lossy().to_string();
let mut program_list = Vec::new();
// Add entry program first
// Ensure the entry module (containing 'frame()') is processed 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
// Collect all other modules
for (path, (source, program)) in &modules {
if path != &entry_str {
program_list.push((path.clone(), source.to_string(), program));
+65 -6
View File
@@ -1,16 +1,75 @@
pub mod cli;
//! # Prometeu Compiler
//!
//! This crate provides the official compiler for the Prometeu ecosystem.
//! It translates TypeScript/JavaScript source code into Prometeu ByteCode (.pbc).
//!
//! ## Workflow:
//! 1. **Parsing**: Uses the `oxc` parser to generate an Abstract Syntax Tree (AST).
//! 2. **Validation**: Checks for unsupported features and ensures ABI compliance.
//! 3. **Codegen**: Traverses the AST and emits `prometeu-bytecode` instructions.
//! 4. **Assembly**: Resolves labels and serializes the program into the binary PBC format.
//!
//! ## Example Usage:
//! ```bash
//! # Build a project
//! prometeu-compiler build ./my-game --entry ./src/main.ts --out ./game.pbc
//! ```
pub mod codegen;
pub mod compiler;
pub mod syscall_map;
use clap::Parser;
use anyhow::Result;
use clap::{Parser, Subcommand};
use std::path::PathBuf;
/// Command line interface for the Prometeu Compiler.
#[derive(Parser)]
#[command(name = "prometeu-compiler")]
#[command(version, about = "Official compiler for the PROMETEU Virtual Machine", long_about = None)]
pub struct Cli {
/// The action to perform (build or verify).
#[command(subcommand)]
pub command: Commands,
}
/// Available subcommands for the compiler.
#[derive(Subcommand)]
pub enum Commands {
/// Builds a Prometeu project by compiling source code into a PBC file.
Build {
/// Path to the project root directory.
project_dir: PathBuf,
/// Explicit path to the entry file (defaults to src/main.ts).
#[arg(short, long)]
entry: Option<PathBuf>,
/// Path to save the compiled .pbc file.
#[arg(short, long)]
out: Option<PathBuf>,
/// Whether to generate a .disasm file for debugging.
#[arg(long, default_value_t = true)]
emit_disasm: bool,
/// Whether to generate a .json symbols file for source mapping.
#[arg(long, default_value_t = true)]
emit_symbols: bool,
},
/// Verifies if a Prometeu project is syntactically and semantically valid without emitting code.
Verify {
/// Path to the project root directory.
project_dir: PathBuf,
},
}
/// Main entry point for the compiler library's execution logic.
/// Parses CLI arguments and dispatches to the appropriate compiler functions.
pub fn run() -> Result<()> {
let cli = cli::Cli::parse();
let cli = Cli::parse();
match cli.command {
cli::Commands::Build {
Commands::Build {
project_dir,
entry,
out,
@@ -32,7 +91,7 @@ pub fn run() -> Result<()> {
let compilation_unit = compiler::compile(&entry)?;
compilation_unit.export(&out, emit_disasm, emit_symbols)?;
}
cli::Commands::Verify { project_dir } => {
Commands::Verify { project_dir } => {
let entry = project_dir.join("src/main.ts");
println!("Verifying project at {:?}", project_dir);
println!("Entry: {:?}", entry);
+2
View File
@@ -1,5 +1,7 @@
use anyhow::Result;
/// Main entry point for the Prometeu Compiler binary.
/// It delegates execution to the library's `run` function.
fn main() -> Result<()> {
prometeu_compiler::run()
}
@@ -1,27 +0,0 @@
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,
}
}