spliting compiler into backend and frontend
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
use crate::backend::syscall_registry;
|
||||
use crate::common::files::FileManager;
|
||||
use crate::common::symbols::Symbol;
|
||||
use crate::ir;
|
||||
@@ -117,12 +116,8 @@ impl<'a> BytecodeEmitter<'a> {
|
||||
asm_instrs.push(Asm::Op(OpCode::Call, vec![Operand::Label(name.clone()), Operand::U32(*arg_count)]));
|
||||
}
|
||||
InstrKind::Ret => asm_instrs.push(Asm::Op(OpCode::Ret, vec![])),
|
||||
InstrKind::Syscall(name) => {
|
||||
if let Some(id) = syscall_registry::map_syscall(name) {
|
||||
asm_instrs.push(Asm::Op(OpCode::Syscall, vec![Operand::U32(id)]));
|
||||
} else {
|
||||
return Err(anyhow!("Unknown syscall: {}", name));
|
||||
}
|
||||
InstrKind::Syscall(id) => {
|
||||
asm_instrs.push(Asm::Op(OpCode::Syscall, vec![Operand::U32(*id)]));
|
||||
}
|
||||
InstrKind::FrameSync => asm_instrs.push(Asm::Op(OpCode::FrameSync, vec![])),
|
||||
InstrKind::PushScope => asm_instrs.push(Asm::Op(OpCode::PushScope, vec![])),
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
pub mod syscall_registry;
|
||||
pub mod lowering;
|
||||
pub mod emit_bytecode;
|
||||
pub mod disasm;
|
||||
pub mod artifacts;
|
||||
|
||||
pub use emit_bytecode::emit_module;
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
use prometeu_core::hardware::Syscall;
|
||||
|
||||
/// Maps a High-Level function name to its corresponding Virtual Machine Syscall ID.
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_syscall_name(id: u32) -> Option<String> {
|
||||
if id == 0xFFFF_FFFF {
|
||||
return Some("Color.rgb".to_string());
|
||||
}
|
||||
|
||||
// This is a bit hacky because Syscall is an enum, we might need a better way in prometeu-core
|
||||
// For now, let's just assume we can find it.
|
||||
None // TODO: implement reverse mapping if needed
|
||||
}
|
||||
@@ -1,861 +0,0 @@
|
||||
use crate::codegen::ast_util;
|
||||
use crate::codegen::{input_map, syscall_map};
|
||||
use crate::compiler::Symbol;
|
||||
use anyhow::{anyhow, Result};
|
||||
use oxc_allocator::Vec as OXCVec;
|
||||
use oxc_ast::ast::*;
|
||||
use oxc_ast_visit::{walk, Visit};
|
||||
use oxc_span::{GetSpan, Span};
|
||||
use oxc_syntax::scope::ScopeFlags;
|
||||
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;
|
||||
|
||||
/// Helper to count local variables and hoisted functions in a function body.
|
||||
struct LocalCounter {
|
||||
count: u32,
|
||||
}
|
||||
|
||||
impl<'a> Visit<'a> for LocalCounter {
|
||||
fn visit_statement(&mut self, stmt: &Statement<'a>) {
|
||||
match stmt {
|
||||
Statement::FunctionDeclaration(f) => {
|
||||
self.visit_function(f, ScopeFlags::empty());
|
||||
}
|
||||
_ => walk::walk_statement(self, stmt),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_variable_declaration(&mut self, decl: &VariableDeclaration<'a>) {
|
||||
self.count += decl.declarations.len() as u32;
|
||||
walk::walk_variable_declaration(self, decl);
|
||||
}
|
||||
|
||||
fn visit_function(&mut self, f: &Function<'a>, _flags: ScopeFlags) {
|
||||
if f.id.is_some() {
|
||||
self.count += 1;
|
||||
}
|
||||
// Stop recursion: nested functions have their own frames and locals.
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata for a symbol (variable or function) in the symbol table.
|
||||
#[allow(dead_code)]
|
||||
struct SymbolEntry {
|
||||
name: String,
|
||||
slot_index: u32,
|
||||
scope_depth: usize,
|
||||
is_const: bool,
|
||||
is_initialized: bool,
|
||||
// PC of the instruction where the symbol was declared/initialized.
|
||||
// Useful for debug symbols and potentially for more advanced TDZ checks.
|
||||
declared_at_pc: u32,
|
||||
initialized_at_pc: u32,
|
||||
}
|
||||
|
||||
/// 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>,
|
||||
/// The stream of generated assembly instructions.
|
||||
/// The boolean indicates if the instruction should have a debug symbol attached.
|
||||
instructions: Vec<(Asm, bool)>,
|
||||
/// Scoped symbol table. Each element is a scope level containing a map of symbols.
|
||||
symbol_table: Vec<HashMap<String, SymbolEntry>>,
|
||||
/// Current depth of the scope (0 is global/function top-level).
|
||||
scope_depth: usize,
|
||||
/// 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,
|
||||
source_text,
|
||||
symbols: Vec::new(),
|
||||
instructions: Vec::new(),
|
||||
symbol_table: Vec::new(),
|
||||
scope_depth: 0,
|
||||
globals: HashMap::new(),
|
||||
constant_pool: vec![ConstantPoolEntry::Null], // Index 0 is always Null
|
||||
next_local: 0,
|
||||
next_global: 0,
|
||||
label_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Enters a new scope level.
|
||||
fn enter_scope(&mut self) {
|
||||
self.symbol_table.push(HashMap::new());
|
||||
self.scope_depth += 1;
|
||||
}
|
||||
|
||||
/// Exits the current scope level.
|
||||
fn exit_scope(&mut self) {
|
||||
self.symbol_table.pop();
|
||||
self.scope_depth -= 1;
|
||||
}
|
||||
|
||||
/// Declares a new symbol in the current scope.
|
||||
fn declare_symbol(&mut self, name: String, is_const: bool, is_initialized: bool, span: Span) -> Result<&mut SymbolEntry> {
|
||||
let current_scope = self.symbol_table.last_mut().ok_or_else(|| anyhow!("No active scope"))?;
|
||||
|
||||
if current_scope.contains_key(&name) {
|
||||
return Err(anyhow!("Variable '{}' already declared in this scope at {:?}", name, span));
|
||||
}
|
||||
|
||||
let slot_index = self.next_local;
|
||||
self.next_local += 1;
|
||||
|
||||
let entry = SymbolEntry {
|
||||
name: name.clone(),
|
||||
slot_index,
|
||||
scope_depth: self.scope_depth,
|
||||
is_const,
|
||||
is_initialized,
|
||||
declared_at_pc: 0, // Will be filled if needed
|
||||
initialized_at_pc: 0,
|
||||
};
|
||||
|
||||
current_scope.insert(name.clone(), entry);
|
||||
Ok(self.symbol_table.last_mut().unwrap().get_mut(&name).unwrap())
|
||||
}
|
||||
|
||||
/// Marks a symbol as initialized.
|
||||
fn initialize_symbol(&mut self, name: &str) {
|
||||
for scope in self.symbol_table.iter_mut().rev() {
|
||||
if let Some(entry) = scope.get_mut(name) {
|
||||
entry.is_initialized = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a symbol name to its entry, searching from inner to outer scopes.
|
||||
fn resolve_symbol(&self, name: &str) -> Option<&SymbolEntry> {
|
||||
for scope in self.symbol_table.iter().rev() {
|
||||
if let Some(entry) = scope.get(name) {
|
||||
return Some(entry);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Discovers all function declarations in a program, including nested ones.
|
||||
fn discover_functions<'a>(
|
||||
&self,
|
||||
file: String,
|
||||
source: String,
|
||||
program: &'a Program<'a>,
|
||||
all_functions: &mut Vec<(String, String, &'a Function<'a>)>,
|
||||
) {
|
||||
struct Collector<'a, 'b> {
|
||||
file: String,
|
||||
source: String,
|
||||
functions: &'b mut Vec<(String, String, &'a Function<'a>)>,
|
||||
}
|
||||
|
||||
impl<'a, 'b> Visit<'a> for Collector<'a, 'b> {
|
||||
fn visit_function(&mut self, f: &Function<'a>, flags: ScopeFlags) {
|
||||
// Safety: The program AST lives long enough as it's owned by the caller
|
||||
// of compile_programs and outlives the compilation process.
|
||||
let f_ref = unsafe { std::mem::transmute::<&Function<'a>, &'a Function<'a>>(f) };
|
||||
self.functions.push((self.file.clone(), self.source.clone(), f_ref));
|
||||
walk::walk_function(self, f, flags);
|
||||
}
|
||||
}
|
||||
|
||||
let mut collector = Collector {
|
||||
file,
|
||||
source,
|
||||
functions: all_functions,
|
||||
};
|
||||
collector.visit_program(program);
|
||||
}
|
||||
|
||||
/// 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
|
||||
} else {
|
||||
let pos = self.constant_pool.len();
|
||||
self.constant_pool.push(entry);
|
||||
pos as u32
|
||||
}
|
||||
}
|
||||
|
||||
/// 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: 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 {
|
||||
// Collect global variables and discover all functions (including nested)
|
||||
for item in &program.body {
|
||||
match item {
|
||||
// Exported declaration: export function foo() ... or export const x = 1;
|
||||
Statement::ExportNamedDeclaration(decl) => {
|
||||
if let Some(Declaration::VariableDeclaration(var)) = &decl.declaration {
|
||||
self.export_global_variable_declarations(&var);
|
||||
}
|
||||
}
|
||||
// Global variable declaration: var x = 1;
|
||||
Statement::VariableDeclaration(var) => {
|
||||
self.export_global_variable_declarations(&var);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Discovery Pass for all functions in this program
|
||||
self.discover_functions(file.clone(), source.clone(), program, &mut all_functions);
|
||||
}
|
||||
|
||||
// --- 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 {
|
||||
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 == "frame" {
|
||||
frame_fn_name = Some(ident.name.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let frame_fn_name = frame_fn_name.ok_or_else(|| anyhow!("export function frame() not found in entry file"))?;
|
||||
|
||||
// --- 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();
|
||||
for item in &program.body {
|
||||
let var_opt = match item {
|
||||
Statement::VariableDeclaration(var) => Some(var.as_ref()),
|
||||
Statement::ExportNamedDeclaration(decl) => {
|
||||
if let Some(Declaration::VariableDeclaration(var)) = &decl.declaration {
|
||||
Some(var.as_ref())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(var) = var_opt {
|
||||
for decl in &var.declarations {
|
||||
if let BindingPattern::BindingIdentifier(ident) = &decl.id {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- 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());
|
||||
|
||||
// --- 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))?;
|
||||
|
||||
// 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.symbol_table.clear();
|
||||
self.scope_depth = 0;
|
||||
self.next_local = 0;
|
||||
|
||||
// Start scope for parameters and local variables
|
||||
self.enter_scope();
|
||||
self.emit_op(OpCode::PushScope, vec![], f.span);
|
||||
|
||||
// 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) = ¶m.pattern {
|
||||
let name = ident.name.to_string();
|
||||
// Parameters are considered initialized
|
||||
self.declare_symbol(name, false, true, ident.span)?;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(body) = &f.body {
|
||||
// Reserve slots for all local variables and hoisted functions
|
||||
let locals_to_reserve = self.count_locals(&body.statements);
|
||||
for _ in 0..locals_to_reserve {
|
||||
// Initializing with I32 0 as it's the safest default for Prometeu VM
|
||||
self.emit_op(OpCode::PushI32, vec![Operand::I32(0)], f.span);
|
||||
}
|
||||
|
||||
// Function and Variable hoisting within the function scope
|
||||
self.hoist_functions(&body.statements)?;
|
||||
self.hoist_variables(&body.statements)?;
|
||||
|
||||
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.
|
||||
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(())
|
||||
}
|
||||
|
||||
/// Counts the total number of local variable and function declarations in a function body.
|
||||
fn count_locals(&self, statements: &OXCVec<Statement>) -> u32 {
|
||||
let mut counter = LocalCounter { count: 0 };
|
||||
for stmt in statements {
|
||||
counter.visit_statement(stmt);
|
||||
}
|
||||
counter.count
|
||||
}
|
||||
|
||||
/// Hoists function declarations to the top of the current scope.
|
||||
fn hoist_functions(&mut self, statements: &OXCVec<Statement>) -> Result<()> {
|
||||
for stmt in statements {
|
||||
if let Statement::FunctionDeclaration(f) = stmt {
|
||||
if let Some(ident) = &f.id {
|
||||
let name = ident.name.to_string();
|
||||
// Functions are hoisted and already considered initialized
|
||||
self.declare_symbol(name, false, true, ident.span)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Hoists variable declarations (let/const) to the top of the current scope.
|
||||
fn hoist_variables(&mut self, statements: &OXCVec<Statement>) -> Result<()> {
|
||||
for stmt in statements {
|
||||
if let Statement::VariableDeclaration(var) = stmt {
|
||||
let is_const = var.kind == VariableDeclarationKind::Const;
|
||||
for decl in &var.declarations {
|
||||
if let BindingPattern::BindingIdentifier(ident) = &decl.id {
|
||||
let name = ident.name.to_string();
|
||||
// Register as uninitialized for TDZ
|
||||
self.declare_symbol(name, is_const, false, ident.span)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Translates a Statement into bytecode.
|
||||
fn compile_stmt(&mut self, stmt: &Statement) -> Result<()> {
|
||||
match stmt {
|
||||
// var x = 10;
|
||||
Statement::VariableDeclaration(var) => {
|
||||
let is_const = var.kind == VariableDeclarationKind::Const;
|
||||
for decl in &var.declarations {
|
||||
if let BindingPattern::BindingIdentifier(ident) = &decl.id {
|
||||
let name = ident.name.to_string();
|
||||
|
||||
// Variable should already be in the symbol table due to hoisting
|
||||
let entry = self.resolve_symbol(&name)
|
||||
.ok_or_else(|| anyhow!("Internal compiler error: symbol '{}' not hoisted at {:?}", name, ident.span))?;
|
||||
|
||||
let slot_index = entry.slot_index;
|
||||
|
||||
if let Some(init) = &decl.init {
|
||||
self.compile_expr(init)?;
|
||||
self.emit_op(OpCode::SetLocal, vec![Operand::U32(slot_index)], decl.span);
|
||||
self.initialize_symbol(&name);
|
||||
} else {
|
||||
if is_const {
|
||||
return Err(anyhow!("Missing initializer in const declaration at {:?}", decl.span));
|
||||
}
|
||||
// Default initialization to 0
|
||||
self.emit_op(OpCode::PushI32, vec![Operand::I32(0)], decl.span);
|
||||
self.emit_op(OpCode::SetLocal, vec![Operand::U32(slot_index)], decl.span);
|
||||
self.initialize_symbol(&name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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");
|
||||
|
||||
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);
|
||||
}
|
||||
// { let x = 1; }
|
||||
Statement::BlockStatement(block) => {
|
||||
self.enter_scope();
|
||||
self.emit_op(OpCode::PushScope, vec![], block.span);
|
||||
|
||||
// Hoist functions and variables in the block
|
||||
self.hoist_functions(&block.body)?;
|
||||
self.hoist_variables(&block.body)?;
|
||||
|
||||
for stmt in &block.body {
|
||||
self.compile_stmt(stmt)?;
|
||||
}
|
||||
|
||||
self.emit_op(OpCode::PopScope, vec![], block.span);
|
||||
self.exit_scope();
|
||||
}
|
||||
// Function declarations are handled by hoisting and compiled separately
|
||||
Statement::FunctionDeclaration(_) => {}
|
||||
_ => return Err(anyhow!("Unsupported statement type at {:?}", stmt.span())),
|
||||
}
|
||||
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 {
|
||||
self.emit_op(OpCode::PushI32, vec![Operand::I32(val as i32)], n.span);
|
||||
} else {
|
||||
self.emit_op(OpCode::PushF64, vec![Operand::F64(val)], 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);
|
||||
}
|
||||
// Variable access: resolve to GetLocal or GetGlobal
|
||||
Expression::Identifier(ident) => {
|
||||
let name = ident.name.to_string();
|
||||
if let Some(entry) = self.resolve_symbol(&name) {
|
||||
if !entry.is_initialized {
|
||||
return Err(anyhow!("TDZ Violation: Variable '{}' accessed before initialization at {:?}", name, ident.span));
|
||||
}
|
||||
self.emit_op(OpCode::GetLocal, vec![Operand::U32(entry.slot_index)], ident.span);
|
||||
} else if let Some(&id) = self.globals.get(&name) {
|
||||
self.emit_op(OpCode::GetGlobal, vec![Operand::U32(id)], ident.span);
|
||||
} else {
|
||||
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();
|
||||
|
||||
if let Some(entry) = self.resolve_symbol(&name) {
|
||||
if entry.is_const {
|
||||
return Err(anyhow!("Assignment to constant variable '{}' at {:?}", name, assign.span));
|
||||
}
|
||||
if !entry.is_initialized {
|
||||
return Err(anyhow!("TDZ Violation: Variable '{}' accessed before initialization at {:?}", name, assign.span));
|
||||
}
|
||||
let slot_index = entry.slot_index;
|
||||
self.compile_expr(&assign.right)?;
|
||||
self.emit_op(OpCode::SetLocal, vec![Operand::U32(slot_index)], assign.span);
|
||||
self.emit_op(OpCode::GetLocal, vec![Operand::U32(slot_index)], assign.span); // Assignment returns the value
|
||||
} else if let Some(&id) = self.globals.get(&name) {
|
||||
self.compile_expr(&assign.right)?;
|
||||
self.emit_op(OpCode::SetGlobal, vec![Operand::U32(id)], assign.span);
|
||||
self.emit_op(OpCode::GetGlobal, 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));
|
||||
}
|
||||
}
|
||||
// Binary operations: evaluate both sides and apply the opcode
|
||||
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);
|
||||
}
|
||||
// Logical operations: evaluate both sides and apply the opcode
|
||||
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);
|
||||
}
|
||||
// Unary operations: evaluate argument and apply the opcode
|
||||
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);
|
||||
}
|
||||
// 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 {
|
||||
// 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));
|
||||
}
|
||||
|
||||
// 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);
|
||||
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 (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);
|
||||
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 (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);
|
||||
self.emit_op(OpCode::Shr, vec![], call.span);
|
||||
}
|
||||
|
||||
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)?;
|
||||
}
|
||||
}
|
||||
self.emit_op(OpCode::Syscall, vec![Operand::U32(syscall_id)], call.span);
|
||||
}
|
||||
} else {
|
||||
// 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)?;
|
||||
}
|
||||
}
|
||||
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),
|
||||
"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.") {
|
||||
// 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 = input_map::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.") {
|
||||
// Re-mapped to specific touch syscalls
|
||||
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(())
|
||||
}
|
||||
|
||||
/// 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, // Will be resolved during finalize_symbols
|
||||
file: self.file_name.clone(),
|
||||
line,
|
||||
col,
|
||||
});
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
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;
|
||||
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)
|
||||
}
|
||||
|
||||
/// 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;
|
||||
|
||||
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; // OpCode size (u16)
|
||||
current_pc = asm::update_pc_by_operand(current_pc, operands);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
//! # 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;
|
||||
@@ -1,20 +0,0 @@
|
||||
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,180 +0,0 @@
|
||||
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;
|
||||
use oxc_syntax::scope::ScopeFlags;
|
||||
|
||||
/// 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. Discovery Pass: Collect all function names and imports recursively
|
||||
validator.discover_functions(program);
|
||||
|
||||
// 2. Traversal Pass: Check every node for compatibility
|
||||
validator.visit_program(program);
|
||||
|
||||
if validator.errors.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!("Validation errors:\n{}", validator.errors.join("\n")))
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively discovers all function declarations in the program.
|
||||
fn discover_functions(&mut self, program: &Program) {
|
||||
struct FunctionDiscoverer<'a> {
|
||||
functions: &'a mut std::collections::HashSet<String>,
|
||||
}
|
||||
impl<'a, 'b> Visit<'b> for FunctionDiscoverer<'a> {
|
||||
fn visit_function(&mut self, f: &Function<'b>, _flags: ScopeFlags) {
|
||||
if let Some(ident) = &f.id {
|
||||
self.functions.insert(ident.name.to_string());
|
||||
}
|
||||
walk::walk_function(self, f, _flags);
|
||||
}
|
||||
fn visit_import_declaration(&mut self, decl: &ImportDeclaration<'b>) {
|
||||
if let Some(specifiers) = &decl.specifiers {
|
||||
for specifier in specifiers {
|
||||
match specifier {
|
||||
ImportDeclarationSpecifier::ImportSpecifier(s) => {
|
||||
self.functions.insert(s.local.name.to_string());
|
||||
}
|
||||
ImportDeclarationSpecifier::ImportDefaultSpecifier(s) => {
|
||||
self.functions.insert(s.local.name.to_string());
|
||||
}
|
||||
ImportDeclarationSpecifier::ImportNamespaceSpecifier(s) => {
|
||||
self.functions.insert(s.local.name.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut discoverer = FunctionDiscoverer { functions: &mut self.local_functions };
|
||||
discoverer.visit_program(program);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Visit<'a> for Validator {
|
||||
/// Validates that only supported expressions are used.
|
||||
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(_) => {
|
||||
// Basic JS logic is supported.
|
||||
walk::walk_expression(self, expr);
|
||||
}
|
||||
_ => {
|
||||
self.errors.push(format!("Unsupported expression type at {:?}. Note: Closures, arrow functions, and object literals are not yet supported.", 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_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_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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates that only supported statements are used.
|
||||
fn visit_statement(&mut self, stmt: &Statement<'a>) {
|
||||
match stmt {
|
||||
Statement::VariableDeclaration(_) |
|
||||
Statement::ExpressionStatement(_) |
|
||||
Statement::IfStatement(_) |
|
||||
Statement::BlockStatement(_) |
|
||||
Statement::ExportNamedDeclaration(_) |
|
||||
Statement::ImportDeclaration(_) |
|
||||
Statement::FunctionDeclaration(_) |
|
||||
Statement::ReturnStatement(_) => {
|
||||
// These are the only statements the PVM handles currently.
|
||||
walk::walk_statement(self, stmt);
|
||||
}
|
||||
_ => {
|
||||
self.errors.push(format!("Unsupported statement type at {:?}. Note: Prometeu does not support while/for loops or classes yet.", stmt.span()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,4 +2,3 @@ pub mod diagnostics;
|
||||
pub mod spans;
|
||||
pub mod files;
|
||||
pub mod symbols;
|
||||
pub mod sourcemap;
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
// PC <-> Span mapping logic
|
||||
@@ -34,4 +34,35 @@ pub fn map_btn_name(btn_name: &str) -> anyhow::Result<u32> {
|
||||
"select" => Ok(BTN_SELECT),
|
||||
_ => Err(anyhow!("Unsupported button: {}. Expected one of: up, down, left, right, a, b, x, y, l, r, start, select.", btn_name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Translates a pad state name (e.g., "pressed") into the corresponding syscall name.
|
||||
pub fn map_pad_state(state_name: &str) -> anyhow::Result<&'static str> {
|
||||
match state_name {
|
||||
"down" => Ok("input.getPad"),
|
||||
"pressed" => Ok("input.getPadPressed"),
|
||||
"released" => Ok("input.getPadReleased"),
|
||||
"holdFrames" => Ok("input.getPadHold"),
|
||||
_ => Err(anyhow!("Unsupported button state: {}. Expected one of: down, pressed, released, holdFrames.", state_name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Translates a touch property name (e.g., "x") into the corresponding syscall name.
|
||||
pub fn map_touch_prop(prop_name: &str) -> anyhow::Result<&'static str> {
|
||||
match prop_name {
|
||||
"x" => Ok("touch.getX"),
|
||||
"y" => Ok("touch.getY"),
|
||||
_ => Err(anyhow!("Unsupported touch property: {}. Expected one of: x, y.", prop_name)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Translates a touch button state name (e.g., "down") into the corresponding syscall name.
|
||||
pub fn map_touch_button_state(state_name: &str) -> anyhow::Result<&'static str> {
|
||||
match state_name {
|
||||
"down" => Ok("touch.isDown"),
|
||||
"pressed" => Ok("touch.isPressed"),
|
||||
"released" => Ok("touch.isReleased"),
|
||||
"holdFrames" => Ok("touch.getHold"),
|
||||
_ => Err(anyhow!("Unsupported touch button state: {}. Expected one of: down, pressed, released, holdFrames.", state_name)),
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ pub mod validate;
|
||||
pub mod to_ir;
|
||||
pub mod ast_util;
|
||||
pub mod input_map;
|
||||
pub mod syscall_map;
|
||||
|
||||
use crate::common::diagnostics::DiagnosticBundle;
|
||||
use crate::frontends::Frontend;
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
use prometeu_core::hardware::Syscall;
|
||||
|
||||
/// Maps a high-level function name to its corresponding Syscall ID in the Virtual Machine.
|
||||
///
|
||||
/// This logic resides in the TypeScript frontend because string name resolution
|
||||
/// from the source code is dependent on the language and the provided SDK.
|
||||
pub fn map_syscall(name: &str) -> Option<u32> {
|
||||
// Check if the name corresponds to a standard syscall defined in the core firmware
|
||||
from_name(name)
|
||||
}
|
||||
|
||||
/// Converts a textual name (e.g., "gfx.fillRect") to the numeric ID of the syscall.
|
||||
fn from_name(name: &str) -> Option<u32> {
|
||||
let id = match name.to_lowercase().as_str() {
|
||||
"system.hascart" | "system.has_cart" => Syscall::SystemHasCart,
|
||||
"system.runcart" | "system.run_cart" => Syscall::SystemRunCart,
|
||||
"gfx.clear" => Syscall::GfxClear,
|
||||
"gfx.fillrect" | "gfx.draw_rect" => Syscall::GfxFillRect,
|
||||
"gfx.drawline" | "gfx.draw_line" => Syscall::GfxDrawLine,
|
||||
"gfx.drawcircle" | "gfx.draw_circle" => Syscall::GfxDrawCircle,
|
||||
"gfx.drawdisc" | "gfx.draw_disc" => Syscall::GfxDrawDisc,
|
||||
"gfx.drawsquare" | "gfx.draw_square" => Syscall::GfxDrawSquare,
|
||||
"gfx.setsprite" | "gfx.set_sprite" => Syscall::GfxSetSprite,
|
||||
"gfx.drawtext" | "gfx.draw_text" => Syscall::GfxDrawText,
|
||||
"input.getpad" | "input.get_pad" => Syscall::InputGetPad,
|
||||
"input.getpadpressed" | "input.get_pad_pressed" => Syscall::InputGetPadPressed,
|
||||
"input.getpadreleased" | "input.get_pad_released" => Syscall::InputGetPadReleased,
|
||||
"input.getpadhold" | "input.get_pad_hold" => Syscall::InputGetPadHold,
|
||||
"touch.getx" | "touch.get_x" => Syscall::TouchGetX,
|
||||
"touch.gety" | "touch.get_y" => Syscall::TouchGetY,
|
||||
"touch.isdown" | "touch.is_down" => Syscall::TouchIsDown,
|
||||
"touch.ispressed" | "touch.is_pressed" => Syscall::TouchIsPressed,
|
||||
"touch.isreleased" | "touch.is_released" => Syscall::TouchIsReleased,
|
||||
"touch.gethold" | "touch.get_hold" => Syscall::TouchGetHold,
|
||||
"audio.playsample" | "audio.play_sample" => Syscall::AudioPlaySample,
|
||||
"audio.play" => Syscall::AudioPlay,
|
||||
"fs.open" => Syscall::FsOpen,
|
||||
"fs.read" => Syscall::FsRead,
|
||||
"fs.write" => Syscall::FsWrite,
|
||||
"fs.close" => Syscall::FsClose,
|
||||
"fs.listdir" | "fs.list_dir" => Syscall::FsListDir,
|
||||
"fs.exists" => Syscall::FsExists,
|
||||
"fs.delete" => Syscall::FsDelete,
|
||||
"log.write" => Syscall::LogWrite,
|
||||
"log.writetag" | "log.write_tag" => Syscall::LogWriteTag,
|
||||
"asset.load" => Syscall::AssetLoad,
|
||||
"asset.status" => Syscall::AssetStatus,
|
||||
"asset.commit" => Syscall::AssetCommit,
|
||||
"asset.cancel" => Syscall::AssetCancel,
|
||||
"bank.info" => Syscall::BankInfo,
|
||||
"bank.slotinfo" | "bank.slot_info" => Syscall::BankSlotInfo,
|
||||
_ => return None,
|
||||
};
|
||||
Some(id as u32)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::backend::syscall_registry as syscall_map;
|
||||
use crate::frontends::ts::syscall_map;
|
||||
use crate::common::spans::Span as IRSpan;
|
||||
use crate::frontends::ts::ast_util;
|
||||
use crate::frontends::ts::input_map;
|
||||
@@ -42,17 +42,10 @@ impl<'a> Visit<'a> for LocalCounter {
|
||||
}
|
||||
|
||||
/// Metadata for a symbol (variable or function) in the symbol table.
|
||||
#[allow(dead_code)]
|
||||
struct SymbolEntry {
|
||||
name: String,
|
||||
slot_index: u32,
|
||||
scope_depth: usize,
|
||||
is_const: bool,
|
||||
is_initialized: bool,
|
||||
// PC of the instruction where the symbol was declared/initialized.
|
||||
// Useful for debug symbols and potentially for more advanced TDZ checks.
|
||||
declared_at_pc: u32,
|
||||
initialized_at_pc: u32,
|
||||
}
|
||||
|
||||
/// The TS AST to Prometeu IR translator.
|
||||
@@ -120,13 +113,9 @@ impl ToIR {
|
||||
self.next_local += 1;
|
||||
|
||||
let entry = SymbolEntry {
|
||||
name: name.clone(),
|
||||
slot_index,
|
||||
scope_depth: self.scope_depth,
|
||||
is_const,
|
||||
is_initialized,
|
||||
declared_at_pc: 0, // Will be filled if needed
|
||||
initialized_at_pc: 0,
|
||||
};
|
||||
|
||||
current_scope.insert(name.clone(), entry);
|
||||
@@ -615,52 +604,69 @@ impl ToIR {
|
||||
// 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 {
|
||||
// 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));
|
||||
}
|
||||
|
||||
// Argument 0: r (shift right 3, shift left 11)
|
||||
if let Some(expr) = call.arguments[0].as_expression() {
|
||||
self.compile_expr(expr)?;
|
||||
self.emit_instr(InstrKind::PushInt(3), call.span);
|
||||
self.emit_instr(InstrKind::Shr, call.span);
|
||||
self.emit_instr(InstrKind::PushInt(11), call.span);
|
||||
self.emit_instr(InstrKind::Shl, call.span);
|
||||
}
|
||||
|
||||
// Argument 1: g (shift right 2, shift left 5)
|
||||
if let Some(expr) = call.arguments[1].as_expression() {
|
||||
self.compile_expr(expr)?;
|
||||
self.emit_instr(InstrKind::PushInt(2), call.span);
|
||||
self.emit_instr(InstrKind::Shr, call.span);
|
||||
self.emit_instr(InstrKind::PushInt(5), call.span);
|
||||
self.emit_instr(InstrKind::Shl, call.span);
|
||||
}
|
||||
|
||||
self.emit_instr(InstrKind::BitOr, call.span);
|
||||
|
||||
// Argument 2: b (shift right 3)
|
||||
if let Some(expr) = call.arguments[2].as_expression() {
|
||||
self.compile_expr(expr)?;
|
||||
self.emit_instr(InstrKind::PushInt(3), call.span);
|
||||
self.emit_instr(InstrKind::Shr, call.span);
|
||||
}
|
||||
|
||||
self.emit_instr(InstrKind::BitOr, call.span);
|
||||
|
||||
} else {
|
||||
// Standard System Call
|
||||
for arg in &call.arguments {
|
||||
if let Some(expr) = arg.as_expression() {
|
||||
self.compile_expr(expr)?;
|
||||
}
|
||||
}
|
||||
self.emit_instr(InstrKind::Syscall(name), call.span);
|
||||
let name_lower = name.to_lowercase();
|
||||
|
||||
if name_lower == "color.rgb" {
|
||||
// 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));
|
||||
}
|
||||
|
||||
// Argument 0: r (shift right 3, shift left 11)
|
||||
if let Some(expr) = call.arguments[0].as_expression() {
|
||||
self.compile_expr(expr)?;
|
||||
self.emit_instr(InstrKind::PushInt(3), call.span);
|
||||
self.emit_instr(InstrKind::Shr, call.span);
|
||||
self.emit_instr(InstrKind::PushInt(11), call.span);
|
||||
self.emit_instr(InstrKind::Shl, call.span);
|
||||
}
|
||||
|
||||
// Argument 1: g (shift right 2, shift left 5)
|
||||
if let Some(expr) = call.arguments[1].as_expression() {
|
||||
self.compile_expr(expr)?;
|
||||
self.emit_instr(InstrKind::PushInt(2), call.span);
|
||||
self.emit_instr(InstrKind::Shr, call.span);
|
||||
self.emit_instr(InstrKind::PushInt(5), call.span);
|
||||
self.emit_instr(InstrKind::Shl, call.span);
|
||||
}
|
||||
|
||||
self.emit_instr(InstrKind::BitOr, call.span);
|
||||
|
||||
// Argument 2: b (shift right 3)
|
||||
if let Some(expr) = call.arguments[2].as_expression() {
|
||||
self.compile_expr(expr)?;
|
||||
self.emit_instr(InstrKind::PushInt(3), call.span);
|
||||
self.emit_instr(InstrKind::Shr, call.span);
|
||||
}
|
||||
|
||||
self.emit_instr(InstrKind::BitOr, call.span);
|
||||
|
||||
} else if name_lower.starts_with("input.btn") || name_lower.starts_with("pinput.btn") {
|
||||
// Special case for legacy Input.btnX() calls
|
||||
// They map to input.getPad(BTN_X)
|
||||
let btn_name = if name_lower.starts_with("pinput.btn") {
|
||||
&name[10..]
|
||||
} else {
|
||||
&name[9..]
|
||||
};
|
||||
|
||||
// Strip parentheses if any (though get_callee_name should handle just the callee)
|
||||
let btn_name = btn_name.strip_suffix("()").unwrap_or(btn_name);
|
||||
|
||||
let btn_id = input_map::map_btn_name(btn_name)?;
|
||||
self.emit_instr(InstrKind::PushInt(btn_id as i64), call.span);
|
||||
let pad_id = syscall_map::map_syscall("input.getPad").ok_or_else(|| anyhow!("input.getPad syscall not found"))?;
|
||||
self.emit_instr(InstrKind::Syscall(pad_id), call.span);
|
||||
|
||||
} else if let Some(syscall_id) = syscall_map::map_syscall(&name) {
|
||||
// Standard System Call
|
||||
for arg in &call.arguments {
|
||||
if let Some(expr) = arg.as_expression() {
|
||||
self.compile_expr(expr)?;
|
||||
}
|
||||
}
|
||||
self.emit_instr(InstrKind::Syscall(syscall_id), call.span);
|
||||
} else {
|
||||
// Local function call (to a function defined in the project)
|
||||
for arg in &call.arguments {
|
||||
@@ -689,7 +695,7 @@ impl ToIR {
|
||||
"color.orange" => self.emit_instr(InstrKind::PushInt(Color::ORANGE.raw() as i64), member.span),
|
||||
"color.indigo" => self.emit_instr(InstrKind::PushInt(Color::INDIGO.raw() as i64), member.span),
|
||||
"color.magenta" => self.emit_instr(InstrKind::PushInt(Color::MAGENTA.raw() as i64), member.span),
|
||||
"color.colorkey" | "color.color_key" => self.emit_instr(InstrKind::PushInt(Color::COLOR_KEY.raw() as i64), member.span),
|
||||
"color.colorKey" | "color.color_key" => self.emit_instr(InstrKind::PushInt(Color::COLOR_KEY.raw() as i64), member.span),
|
||||
_ => return Err(anyhow!("Unsupported color constant: {} at {:?}", full_name, member.span)),
|
||||
}
|
||||
} else if full_name.to_lowercase().starts_with("pad.") {
|
||||
@@ -699,15 +705,10 @@ impl ToIR {
|
||||
let btn_name = parts[1];
|
||||
let state_name = parts[2];
|
||||
let btn_id = input_map::map_btn_name(btn_name)?;
|
||||
let syscall_name = match state_name {
|
||||
"down" => "InputGetPad",
|
||||
"pressed" => "InputGetPadPressed",
|
||||
"released" => "InputGetPadReleased",
|
||||
"holdFrames" => "InputGetPadHold",
|
||||
_ => return Err(anyhow!("Unsupported button state: {} at {:?}", state_name, member.span)),
|
||||
};
|
||||
let syscall_name = input_map::map_pad_state(state_name)?;
|
||||
let syscall_id = syscall_map::map_syscall(syscall_name).unwrap();
|
||||
self.emit_instr(InstrKind::PushInt(btn_id as i64), member.span);
|
||||
self.emit_instr(InstrKind::Syscall(syscall_name.to_string()), member.span);
|
||||
self.emit_instr(InstrKind::Syscall(syscall_id), member.span);
|
||||
} else {
|
||||
return Err(anyhow!("Partial Pad access not supported: {} at {:?}", full_name, member.span));
|
||||
}
|
||||
@@ -717,23 +718,15 @@ impl ToIR {
|
||||
match parts.len() {
|
||||
2 => {
|
||||
let prop = parts[1];
|
||||
let syscall_name = match prop {
|
||||
"x" => "TouchGetX",
|
||||
"y" => "TouchGetY",
|
||||
_ => return Err(anyhow!("Unsupported touch property: {} at {:?}", prop, member.span)),
|
||||
};
|
||||
self.emit_instr(InstrKind::Syscall(syscall_name.to_string()), member.span);
|
||||
let syscall_name = input_map::map_touch_prop(prop)?;
|
||||
let syscall_id = syscall_map::map_syscall(syscall_name).unwrap();
|
||||
self.emit_instr(InstrKind::Syscall(syscall_id), member.span);
|
||||
}
|
||||
3 if parts[1] == "button" => {
|
||||
let state_name = parts[2];
|
||||
let syscall_name = match state_name {
|
||||
"down" => "TouchIsDown",
|
||||
"pressed" => "TouchIsPressed",
|
||||
"released" => "TouchIsReleased",
|
||||
"holdFrames" => "TouchGetHold",
|
||||
_ => return Err(anyhow!("Unsupported touch button state: {} at {:?}", state_name, member.span)),
|
||||
};
|
||||
self.emit_instr(InstrKind::Syscall(syscall_name.to_string()), member.span);
|
||||
let syscall_name = input_map::map_touch_button_state(state_name)?;
|
||||
let syscall_id = syscall_map::map_syscall(syscall_name).unwrap();
|
||||
self.emit_instr(InstrKind::Syscall(syscall_id), member.span);
|
||||
}
|
||||
_ => return Err(anyhow!("Unsupported touch access: {} at {:?}", full_name, member.span)),
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::backend::syscall_registry as syscall_map;
|
||||
use crate::frontends::ts::syscall_map;
|
||||
use crate::frontends::ts::ast_util;
|
||||
use anyhow::{anyhow, Result};
|
||||
use oxc_ast::ast::*;
|
||||
@@ -104,7 +104,10 @@ impl<'a> Visit<'a> for Validator {
|
||||
|
||||
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) {
|
||||
let name_lower = name.to_lowercase();
|
||||
let is_intrinsic = name_lower == "color.rgb" || name_lower.starts_with("input.btn") || name_lower.starts_with("pinput.btn");
|
||||
|
||||
if !is_intrinsic && syscall_map::map_syscall(&name).is_none() && !self.local_functions.contains(&name) {
|
||||
self.errors.push(format!("Unsupported function call: {} at {:?}", name, expr.span));
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -71,7 +71,7 @@ pub enum InstrKind {
|
||||
Ret,
|
||||
|
||||
// OS / System
|
||||
Syscall(String),
|
||||
Syscall(u32),
|
||||
FrameSync,
|
||||
PushScope,
|
||||
PopScope,
|
||||
|
||||
Reference in New Issue
Block a user