add prometeuc
This commit is contained in:
@@ -5,3 +5,11 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
prometeu-bytecode = { path = "../prometeu-bytecode" }
|
||||
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"
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
use clap::{Parser, Subcommand};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "prometeuc")]
|
||||
#[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,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
pub use prometeu_bytecode::opcode::OpCode;
|
||||
pub use prometeu_bytecode::asm::{Asm, Operand, assemble};
|
||||
pub mod codegen;
|
||||
|
||||
pub use codegen::Codegen;
|
||||
@@ -0,0 +1,72 @@
|
||||
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(())
|
||||
}
|
||||
@@ -1,5 +1,37 @@
|
||||
pub mod codegen;
|
||||
use clap::Parser;
|
||||
use anyhow::Result;
|
||||
|
||||
fn main() {
|
||||
println!("Prometeu Compiler (stub)");
|
||||
pub mod cli;
|
||||
pub mod codegen;
|
||||
pub mod compiler;
|
||||
pub mod syscall_map;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let cli = cli::Cli::parse();
|
||||
|
||||
match cli.command {
|
||||
cli::Commands::Build {
|
||||
project_dir,
|
||||
entry,
|
||||
out,
|
||||
emit_disasm,
|
||||
emit_symbols,
|
||||
} => {
|
||||
let entry = entry.unwrap_or_else(|| project_dir.join("src/main.ts"));
|
||||
let build_dir = project_dir.join("build");
|
||||
let out = out.unwrap_or_else(|| build_dir.join("program.pbc"));
|
||||
|
||||
if !build_dir.exists() {
|
||||
std::fs::create_dir_all(&build_dir)?;
|
||||
}
|
||||
|
||||
println!("Building project at {:?}", project_dir);
|
||||
println!("Entry: {:?}", entry);
|
||||
println!("Output: {:?}", out);
|
||||
|
||||
compiler::compile(&entry, &out, emit_disasm, emit_symbols)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
pub const SYS_GFX_FILL_RECT: u32 = 0x1002;
|
||||
pub const SYS_INPUT_GET_PAD: u32 = 0x2001;
|
||||
|
||||
pub const BTN_UP: u32 = 0;
|
||||
pub const BTN_DOWN: u32 = 1;
|
||||
pub const BTN_LEFT: u32 = 2;
|
||||
pub const BTN_RIGHT: u32 = 3;
|
||||
pub const BTN_A: u32 = 4;
|
||||
pub const BTN_B: u32 = 5;
|
||||
pub const BTN_X: u32 = 6;
|
||||
pub const BTN_Y: u32 = 7;
|
||||
pub const BTN_L: u32 = 8;
|
||||
pub const BTN_R: u32 = 9;
|
||||
pub const BTN_START: u32 = 10;
|
||||
pub const BTN_SELECT: u32 = 11;
|
||||
|
||||
pub fn map_syscall(name: &str) -> Option<u32> {
|
||||
match name {
|
||||
"gfx.fillRect" => Some(SYS_GFX_FILL_RECT),
|
||||
"input.btnA" | "input.btnB" | "input.get_pad" => Some(SYS_INPUT_GET_PAD),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user