test cartridge for lua and js
This commit is contained in:
@@ -1,3 +1,12 @@
|
||||
//! # TypeScript Frontend
|
||||
//!
|
||||
//! This module implements the TypeScript/JavaScript frontend for the Prometeu Compiler.
|
||||
//! It is responsible for:
|
||||
//! 1. Parsing `.ts` files into an Abstract Syntax Tree (AST).
|
||||
//! 2. Resolving imports and building a dependency graph.
|
||||
//! 3. Validating that the source code uses only supported VM features.
|
||||
//! 4. Lowering the high-level AST into the generic Intermediate Representation (IR).
|
||||
|
||||
pub mod parse;
|
||||
pub mod resolve;
|
||||
pub mod validate;
|
||||
@@ -14,6 +23,7 @@ use std::collections::{HashMap, VecDeque};
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
/// The main entry point for the TypeScript compiler frontend.
|
||||
pub struct TypescriptFrontend;
|
||||
|
||||
impl Frontend for TypescriptFrontend {
|
||||
@@ -21,6 +31,21 @@ impl Frontend for TypescriptFrontend {
|
||||
"typescript"
|
||||
}
|
||||
|
||||
/// Compiles a TypeScript entry file (and all its dependencies) into an IR Module.
|
||||
///
|
||||
/// # The Compilation Pipeline:
|
||||
///
|
||||
/// 1. **Discovery & Parsing**:
|
||||
/// Starting from the `entry` file, it reads, parses, and discovers imports recursively.
|
||||
/// It uses the `oxc` parser for high-performance AST generation.
|
||||
///
|
||||
/// 2. **Semantic Validation**:
|
||||
/// Each parsed module is checked against the `Validator`. Since Prometeu is a
|
||||
/// specialized VM, it doesn't support the full range of TS/JS features (e.g., no `try/catch` yet).
|
||||
///
|
||||
/// 3. **IR Lowering**:
|
||||
/// Once all modules are parsed and validated, the `ToIR` engine traverses the ASTs
|
||||
/// and emits equivalent IR instructions.
|
||||
fn compile_to_ir(
|
||||
&self,
|
||||
entry: &Path,
|
||||
@@ -35,6 +60,7 @@ impl Frontend for TypescriptFrontend {
|
||||
queue.push_back(entry_abs.clone());
|
||||
|
||||
// --- PHASE 1: Dependency Resolution and Parsing ---
|
||||
// We traverse the dependency graph breadth-first to ensure all files are loaded.
|
||||
while let Some(path) = queue.pop_front() {
|
||||
let path_str: String = path.to_string_lossy().into_owned();
|
||||
if modules.contains_key(&path_str) {
|
||||
@@ -45,12 +71,14 @@ impl Frontend for TypescriptFrontend {
|
||||
let file_id = file_manager.add(path.clone(), source_text.clone());
|
||||
let source_text_ptr = allocator.alloc_str(&source_text);
|
||||
|
||||
// Parse the source into an AST
|
||||
let program = parse::parse_file(&allocator, &path).map_err(|e| DiagnosticBundle::error(format!("Failed to parse module: {}", e), None))?;
|
||||
|
||||
// --- PHASE 2: Individual Module Validation ---
|
||||
// Ensure the code adheres to Prometeu's restricted subset of TypeScript.
|
||||
validate::Validator::validate(&program).map_err(|e| DiagnosticBundle::error(format!("Validation error: {}", e), None))?;
|
||||
|
||||
// Discover new imports
|
||||
// Discover new imports and add them to the queue
|
||||
for item in &program.body {
|
||||
if let oxc_ast::ast::Statement::ImportDeclaration(decl) = item {
|
||||
let import_path = decl.source.value.as_str();
|
||||
@@ -63,6 +91,7 @@ impl Frontend for TypescriptFrontend {
|
||||
}
|
||||
|
||||
// --- PHASE 3: To IR ---
|
||||
// Collect all parsed modules and feed them into the IR generator.
|
||||
let entry_str = entry_abs.to_string_lossy().to_string();
|
||||
let mut program_list = Vec::new();
|
||||
|
||||
|
||||
@@ -1,3 +1,34 @@
|
||||
//! # To IR Lowering
|
||||
//!
|
||||
//! This module implements the core translation logic from the TypeScript AST (Abstract Syntax Tree)
|
||||
//! into the Prometeu Intermediate Representation (IR).
|
||||
//!
|
||||
//! ## How it works:
|
||||
//!
|
||||
//! The `ToIR` engine traverses the AST and for each node (expression, statement, etc.),
|
||||
//! it emits equivalent stack-based IR instructions.
|
||||
//!
|
||||
//! ### Symbol Resolution
|
||||
//! It maintains a scoped symbol table to track local variables and their assigned slots.
|
||||
//! It also manages global variables, which are mapped to permanent memory slots in the VM.
|
||||
//!
|
||||
//! ### Control Flow
|
||||
//! High-level control flow (like `if`, `while`, `for`) is lowered into jumps and labels.
|
||||
//! Unique labels are generated for each branch to avoid collisions.
|
||||
//!
|
||||
//! ### Example Translation:
|
||||
//! **TS Source:**
|
||||
//! ```typescript
|
||||
//! let x = 10 + 20;
|
||||
//! ```
|
||||
//! **Generated IR:**
|
||||
//! ```text
|
||||
//! PushInt(10)
|
||||
//! PushInt(20)
|
||||
//! Add
|
||||
//! SetLocal(0)
|
||||
//! ```
|
||||
|
||||
use crate::frontends::ts::syscall_map;
|
||||
use crate::common::spans::Span as IRSpan;
|
||||
use crate::frontends::ts::ast_util;
|
||||
@@ -14,11 +45,15 @@ use prometeu_core::model::Color;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Helper to count local variables and hoisted functions in a function body.
|
||||
///
|
||||
/// This is used to determine how many slots need to be reserved on the stack frame
|
||||
/// before executing a function.
|
||||
struct LocalCounter {
|
||||
count: u32,
|
||||
}
|
||||
|
||||
impl<'a> Visit<'a> for LocalCounter {
|
||||
/// Discovers function declarations which also occupy a slot in the current frame.
|
||||
fn visit_statement(&mut self, stmt: &Statement<'a>) {
|
||||
match stmt {
|
||||
Statement::FunctionDeclaration(f) => {
|
||||
@@ -28,6 +63,7 @@ impl<'a> Visit<'a> for LocalCounter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Discovers variable declarations (let/const/var) and increments the local count.
|
||||
fn visit_variable_declaration(&mut self, decl: &VariableDeclaration<'a>) {
|
||||
self.count += decl.declarations.len() as u32;
|
||||
walk::walk_variable_declaration(self, decl);
|
||||
@@ -43,8 +79,11 @@ impl<'a> Visit<'a> for LocalCounter {
|
||||
|
||||
/// Metadata for a symbol (variable or function) in the symbol table.
|
||||
struct SymbolEntry {
|
||||
/// The unique index assigned to this variable in the current frame or global memory.
|
||||
slot_index: u32,
|
||||
/// Whether the variable was declared with `const`.
|
||||
is_const: bool,
|
||||
/// Tracks if the variable has been assigned a value (used for Temporal Dead Zone checks).
|
||||
is_initialized: bool,
|
||||
}
|
||||
|
||||
@@ -59,12 +98,13 @@ pub struct ToIR {
|
||||
/// The stream of generated IR instructions.
|
||||
pub instructions: Vec<ir::Instruction>,
|
||||
/// Scoped symbol table. Each element is a scope level containing a map of symbols.
|
||||
/// This allows for variable shadowing and block scope resolution.
|
||||
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>,
|
||||
/// Counter for the next available local variable ID.
|
||||
/// Counter for the next available local variable ID in the current function.
|
||||
next_local: u32,
|
||||
/// Counter for the next available global variable ID.
|
||||
next_global: u32,
|
||||
|
||||
Reference in New Issue
Block a user