added domains into crates

This commit is contained in:
2026-03-24 13:40:34 +00:00
parent 1135514508
commit bddd588464
222 changed files with 751 additions and 790 deletions
@@ -0,0 +1,46 @@
use std::fs;
use std::path::{Path, PathBuf};
fn collect_rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
if let Ok(entries) = fs::read_dir(dir) {
for e in entries.flatten() {
let path = e.path();
if path.is_dir() {
collect_rs_files(&path, out);
} else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
out.push(path);
}
}
}
}
#[test]
fn backend_must_not_import_pbs() {
let crate_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let backend_dir = crate_root.join("src").join("backend");
if !backend_dir.exists() { return; }
let mut files = Vec::new();
collect_rs_files(&backend_dir, &mut files);
let mut offenders = Vec::new();
for f in files {
if let Ok(src) = fs::read_to_string(&f) {
if src.contains("frontends::pbs") || src.contains("crate::frontends::pbs") {
offenders.push(f);
}
}
}
if !offenders.is_empty() {
let list = offenders
.iter()
.map(|p| p.strip_prefix(&crate_root).unwrap_or(p).display().to_string())
.collect::<Vec<_>>()
.join("\n - ");
panic!(
"Backend must not import PBS modules (frontends::pbs). Offending files:\n - {}",
list
);
}
}
@@ -0,0 +1,26 @@
use prometeu_analysis::{ids::FileId, span::Span};
use prometeu_compiler::common::diagnostics::{Diagnostic, DiagnosticBundle, Severity};
#[test]
fn diagnostic_span_is_valid_for_file() {
// Fixture simples
let text = "let x = 10;"; // len = 11
let file = FileId(1);
// Cria um diagnóstico com span válido: end exclusivo e <= len
let span = Span::new(file, 0, text.len() as u32);
assert!(span.end >= span.start);
assert!(span.end <= text.len() as u32);
let diag = Diagnostic {
severity: Severity::Error,
code: "E_TEST".to_string(),
message: "testing".to_string(),
span,
related: vec![],
};
let bundle = DiagnosticBundle { diagnostics: vec![diag] };
// Serialize para garantir que o span passa pelo pipeline sem panics
let _json = serde_json::to_string(&bundle).expect("must serialize diagnostics");
}
@@ -0,0 +1,292 @@
use prometeu_compiler::building::output::CompiledModule;
use prometeu_compiler::building::output::{compile_project, CompileError, ExportKey, ExportMetadata};
use prometeu_compiler::building::plan::{BuildStep, BuildTarget};
use prometeu_compiler::common::files::FileManager;
use prometeu_compiler::deps::resolver::ProjectKey;
use language_api::types::{ExportItem, ItemName};
use prometeu_compiler::frontends::pbs::adapter::PbsFrontendAdapter;
use prometeu_analysis::ids::ProjectId;
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use tempfile::tempdir;
use std::fs;
#[test]
fn test_local_vs_dependency_conflict() {
let dir = tempdir().unwrap();
let project_dir = dir.path().to_path_buf();
// Dependency: sdk
let dep_key = ProjectKey { name: "sdk-impl".to_string(), version: "1.0.0".to_string() };
let dep_id = ProjectId(0);
let mut dep_exports = BTreeMap::new();
dep_exports.insert(ExportKey {
module_path: "math".to_string(), // normalized path
item: ExportItem::Type { name: ItemName::new("Vector").unwrap() },
}, ExportMetadata {
func_idx: None,
is_host: false,
ty: None,
});
let dep_module = CompiledModule {
project_id: dep_id,
project_key: dep_key.clone(),
target: BuildTarget::Main,
exports: dep_exports,
imports: vec![],
const_pool: vec![],
code: vec![],
function_metas: vec![],
debug_info: None,
symbols: vec![],
};
let mut dep_modules: HashMap<ProjectId, CompiledModule> = HashMap::new();
dep_modules.insert(dep_id, dep_module);
// Main project has a LOCAL module named "sdk/math"
// By creating a file in src/main/modules/sdk/math/, the module path becomes "sdk/math"
fs::create_dir_all(project_dir.join("src/main/modules/sdk/math")).unwrap();
fs::write(project_dir.join("src/main/modules/sdk/math/local.pbs"), "pub declare struct Vector(x: int)").unwrap();
let main_key = ProjectKey { name: "main".to_string(), version: "0.1.0".to_string() };
let main_id = ProjectId(1);
let mut deps: BTreeMap<String, ProjectId> = BTreeMap::new();
deps.insert("sdk".to_string(), ProjectId(0));
let step = BuildStep {
project_id: main_id,
project_key: main_key,
project_dir,
target: BuildTarget::Main,
sources: vec![PathBuf::from("src/main/modules/sdk/math/local.pbs")],
deps,
};
let mut file_manager = FileManager::new();
let fe = PbsFrontendAdapter;
let result = compile_project(step, &dep_modules, &fe, &mut file_manager);
match result {
Err(CompileError::DuplicateExport { symbol, .. }) => {
assert_eq!(symbol, "Vector");
},
_ => panic!("Expected DuplicateExport error, got {:?}", result),
}
}
#[test]
fn test_aliased_dependency_conflict() {
let dir = tempdir().unwrap();
let project_dir = dir.path().to_path_buf();
// Dependency 1: exports "b/c:Vector"
let dep1_key = ProjectKey { name: "p1".to_string(), version: "1.0.0".to_string() };
let dep1_id = ProjectId(0);
let mut dep1_exports = BTreeMap::new();
dep1_exports.insert(ExportKey {
module_path: "b/c".to_string(),
item: ExportItem::Type { name: ItemName::new("Vector").unwrap() },
}, ExportMetadata {
func_idx: None,
is_host: false,
ty: None,
});
let dep1_module = CompiledModule {
project_id: dep1_id,
project_key: dep1_key.clone(),
target: BuildTarget::Main,
exports: dep1_exports,
imports: vec![],
const_pool: vec![],
code: vec![],
function_metas: vec![],
debug_info: None,
symbols: vec![],
};
// Dependency 2: exports "c:Vector"
let dep2_key = ProjectKey { name: "p2".to_string(), version: "1.0.0".to_string() };
let dep2_id = ProjectId(1);
let mut dep2_exports = BTreeMap::new();
dep2_exports.insert(ExportKey {
module_path: "c".to_string(),
item: ExportItem::Type { name: ItemName::new("Vector").unwrap() },
}, ExportMetadata {
func_idx: None,
is_host: false,
ty: None,
});
let dep2_module = CompiledModule {
project_id: dep2_id,
project_key: dep2_key.clone(),
target: BuildTarget::Main,
exports: dep2_exports,
imports: vec![],
const_pool: vec![],
code: vec![],
function_metas: vec![],
debug_info: None,
symbols: vec![],
};
let mut dep_modules: HashMap<ProjectId, CompiledModule> = HashMap::new();
dep_modules.insert(dep1_id, dep1_module);
dep_modules.insert(dep2_id, dep2_module);
let main_key = ProjectKey { name: "main".to_string(), version: "0.1.0".to_string() };
let main_id = ProjectId(2);
let mut deps: BTreeMap<String, ProjectId> = BTreeMap::new();
deps.insert("a".to_string(), ProjectId(0));
deps.insert("a/b".to_string(), ProjectId(1));
let step = BuildStep {
project_id: main_id,
project_key: main_key,
project_dir,
target: BuildTarget::Main,
sources: vec![],
deps,
};
let mut file_manager = FileManager::new();
let fe = PbsFrontendAdapter;
let result = compile_project(step, &dep_modules, &fe, &mut file_manager);
match result {
Err(CompileError::DuplicateExport { symbol, .. }) => {
assert_eq!(symbol, "Vector");
},
_ => panic!("Expected DuplicateExport error, got {:?}", result),
}
}
#[test]
fn test_mixed_main_test_modules() {
let dir = tempdir().unwrap();
let project_dir = dir.path().to_path_buf();
fs::create_dir_all(project_dir.join("src/main/modules/math")).unwrap();
fs::write(project_dir.join("src/main/modules/math/Vector.pbs"), "pub declare struct Vector(x: int)").unwrap();
fs::create_dir_all(project_dir.join("src/test/modules/foo")).unwrap();
fs::write(project_dir.join("src/test/modules/foo/Test.pbs"), "pub declare struct Test(x: int)").unwrap();
let project_key = ProjectKey { name: "mixed".to_string(), version: "0.1.0".to_string() };
let project_id = ProjectId(0);
let step = BuildStep {
project_id,
project_key,
project_dir,
target: BuildTarget::Main,
sources: vec![
PathBuf::from("src/main/modules/math/Vector.pbs"),
PathBuf::from("src/test/modules/foo/Test.pbs"),
],
deps: BTreeMap::new(),
};
let mut file_manager = FileManager::new();
let fe = PbsFrontendAdapter;
let compiled = compile_project(step, &HashMap::new(), &fe, &mut file_manager).unwrap();
// Both should be in exports with normalized paths
assert!(compiled.exports.keys().any(|k| k.module_path == "math"));
assert!(compiled.exports.keys().any(|k| k.module_path == "foo"));
}
#[test]
fn test_module_merging_same_directory() {
let dir = tempdir().unwrap();
let project_dir = dir.path().to_path_buf();
fs::create_dir_all(project_dir.join("src/main/modules/gfx")).unwrap();
fs::write(project_dir.join("src/main/modules/gfx/api.pbs"), "pub declare struct Gfx(id: int)").unwrap();
fs::write(project_dir.join("src/main/modules/gfx/colors.pbs"), "pub declare struct Color(r: int)").unwrap();
let project_key = ProjectKey { name: "merge".to_string(), version: "0.1.0".to_string() };
let project_id = ProjectId(0);
let step = BuildStep {
project_id,
project_key,
project_dir,
target: BuildTarget::Main,
sources: vec![
PathBuf::from("src/main/modules/gfx/api.pbs"),
PathBuf::from("src/main/modules/gfx/colors.pbs"),
],
deps: BTreeMap::new(),
};
let mut file_manager = FileManager::new();
let fe = PbsFrontendAdapter;
let compiled = compile_project(step, &HashMap::new(), &fe, &mut file_manager).unwrap();
// Both should be in the same module "gfx"
assert!(compiled.exports.keys().any(|k| k.module_path == "gfx" && matches!(&k.item, ExportItem::Type { name } if name.as_str() == "Gfx")));
assert!(compiled.exports.keys().any(|k| k.module_path == "gfx" && matches!(&k.item, ExportItem::Type { name } if name.as_str() == "Color")));
}
#[test]
fn test_duplicate_symbol_in_same_module_different_files() {
let dir = tempdir().unwrap();
let project_dir = dir.path().to_path_buf();
fs::create_dir_all(project_dir.join("src/main/modules/gfx")).unwrap();
fs::write(project_dir.join("src/main/modules/gfx/a.pbs"), "pub declare struct Gfx(id: int)").unwrap();
fs::write(project_dir.join("src/main/modules/gfx/b.pbs"), "pub declare struct Gfx(id: int)").unwrap();
let project_key = ProjectKey { name: "dup".to_string(), version: "0.1.0".to_string() };
let project_id = ProjectId(0);
let step = BuildStep {
project_id,
project_key,
project_dir,
target: BuildTarget::Main,
sources: vec![
PathBuf::from("src/main/modules/gfx/a.pbs"),
PathBuf::from("src/main/modules/gfx/b.pbs"),
],
deps: BTreeMap::new(),
};
let mut file_manager = FileManager::new();
let fe = PbsFrontendAdapter;
let result = compile_project(step, &HashMap::new(), &fe, &mut file_manager);
assert!(result.is_err());
// Should be a frontend error (duplicate symbol)
}
#[test]
fn test_root_module_merging() {
let dir = tempdir().unwrap();
let project_dir = dir.path().to_path_buf();
fs::create_dir_all(project_dir.join("src/main/modules")).unwrap();
fs::write(project_dir.join("src/main/modules/main.pbs"), "pub declare struct Main(id: int)").unwrap();
fs::write(project_dir.join("src/main/modules/utils.pbs"), "pub declare struct Utils(id: int)").unwrap();
let project_key = ProjectKey { name: "root-merge".to_string(), version: "0.1.0".to_string() };
let project_id = ProjectId(0);
let step = BuildStep {
project_id,
project_key,
project_dir,
target: BuildTarget::Main,
sources: vec![
PathBuf::from("src/main/modules/main.pbs"),
PathBuf::from("src/main/modules/utils.pbs"),
],
deps: BTreeMap::new(),
};
let mut file_manager = FileManager::new();
let fe = PbsFrontendAdapter;
let compiled = compile_project(step, &HashMap::new(), &fe, &mut file_manager).unwrap();
// Both should be in the root module ""
assert!(compiled.exports.keys().any(|k| k.module_path == "" && matches!(&k.item, ExportItem::Type { name } if name.as_str() == "Main")));
assert!(compiled.exports.keys().any(|k| k.module_path == "" && matches!(&k.item, ExportItem::Type { name } if name.as_str() == "Utils")));
}
@@ -0,0 +1,67 @@
// use prometeu_bytecode::disasm::disasm;
// use prometeu_bytecode::BytecodeLoader;
// use prometeu_compiler::compiler::compile;
// use prometeu_compiler::frontends::pbs::parser::Parser;
// use prometeu_compiler::common::spans::FileId;
// use prometeu_analysis::NameInterner;
// use std::fs;
// use std::path::Path;
//
// #[test]
// fn generate_canonical_goldens() {
// println!("CWD: {:?}", std::env::current_dir().unwrap());
// let project_dir = Path::new("../../test-cartridges/canonical");
// if !project_dir.exists() {
// // Fallback for when running from project root (some IDEs/environments)
// let project_dir = Path::new("../../../../test-cartridges/canonical");
// if !project_dir.exists() {
// panic!("Could not find project directory at ../../test-cartridges/canonical or test-cartridges/canonical");
// }
// }
//
// // We need a stable path for the actual compilation which might use relative paths internally
// let project_dir = if Path::new("../../test-cartridges/canonical").exists() {
// Path::new("../../test-cartridges/canonical")
// } else {
// Path::new("../../../../test-cartridges/canonical")
// };
//
// let unit = compile(project_dir).map_err(|e| {
// println!("Compilation Error: {}", e);
// e
// }).expect("Failed to compile canonical cartridge");
//
// let golden_dir = project_dir.join("golden");
// fs::create_dir_all(&golden_dir).unwrap();
//
// // 1. Bytecode (.pbc)
// fs::write(golden_dir.join("program.pbc"), &unit.rom).unwrap();
//
// // 2. Disassembly
// let module = BytecodeLoader::load(&unit.rom).expect("Failed to load BytecodeModule");
// let instrs = disasm(&module.code).expect("Failed to disassemble");
// let mut disasm_text = String::new();
// for instr in instrs {
// let operands_str = instr.operands.iter()
// .map(|o| format!("{:?}", o))
// .collect::<Vec<_>>()
// .join(" ");
// let line = if operands_str.is_empty() {
// format!("{:04X} {:?}\n", instr.pc, instr.opcode)
// } else {
// format!("{:04X} {:?} {}\n", instr.pc, instr.opcode, operands_str.trim())
// };
// disasm_text.push_str(&line);
// }
// fs::write(golden_dir.join("program.disasm.txt"), disasm_text).unwrap();
//
// // 3. AST JSON
// let source = fs::read_to_string(project_dir.join("src/main/modules/main.pbs")).unwrap();
// let mut interner = NameInterner::new();
// let mut parser = Parser::new(&source, FileId(0), &mut interner);
// let parsed = parser.parse_file().expect("Failed to parse AST");
// let ast_json = serde_json::to_string_pretty(parsed.arena.kind(parsed.root)).unwrap();
// fs::write(golden_dir.join("ast.json"), ast_json).unwrap();
//
// println!("Golden artifacts generated in test-cartridges/canonical/golden/");
// }
@@ -0,0 +1,107 @@
use prometeu_compiler::backend::emit_bytecode::emit_module;
use prometeu_compiler::ir_core::ids::{ConstId as CoreConstId, FieldId, FunctionId, TypeId as CoreTypeId, ValueId};
use prometeu_compiler::ir_core::{self, Block, ConstPool, ConstantValue, Instr, InstrKind as CoreInstrKind, Program, Terminator};
use prometeu_compiler::ir_lang::InstrKind;
use prometeu_compiler::lowering::lower_program;
use std::collections::HashMap;
#[test]
fn test_hip_conformance_core_to_vm_to_bytecode() {
// 1. Setup Core IR Program
let mut const_pool = ConstPool::new();
let _val_const = const_pool.insert(ConstantValue::Int(42));
let type_id = CoreTypeId(10);
let field_id = FieldId(1);
let mut field_offsets = HashMap::new();
field_offsets.insert(field_id, 0); // Field at offset 0
let mut field_types = HashMap::new();
field_types.insert(field_id, ir_core::Type::Int);
let program = Program {
const_pool,
modules: vec![ir_core::Module {
name: "conformance".to_string(),
functions: vec![ir_core::Function {
id: FunctionId(1),
name: "main".to_string(),
sig: {
let mut i = ir_core::global_signature_interner().lock().unwrap();
i.intern(ir_core::Signature { params: vec![], return_type: ir_core::Type::Void })
},
param_slots: 0,
local_slots: 0,
return_slots: 0,
params: vec![],
return_type: ir_core::Type::Void,
local_types: HashMap::new(),
blocks: vec![Block {
id: 0,
instrs: vec![
// allocates a storage struct
Instr::from(CoreInstrKind::Alloc { ty: type_id, slots: 2 }),
Instr::from(CoreInstrKind::SetLocal(0)), // x = alloc
// mutates a field
Instr::from(CoreInstrKind::BeginMutate { gate: ValueId(0) }),
Instr::from(CoreInstrKind::PushConst(CoreConstId(0))),
Instr::from(CoreInstrKind::SetLocal(1)), // v = 42
Instr::from(CoreInstrKind::GateStoreField { gate: ValueId(0), field: field_id, value: ValueId(1) }),
Instr::from(CoreInstrKind::EndMutate),
// peeks value
Instr::from(CoreInstrKind::BeginPeek { gate: ValueId(0) }),
Instr::from(CoreInstrKind::GateLoadField { gate: ValueId(0), field: field_id }),
Instr::from(CoreInstrKind::EndPeek),
Instr::from(CoreInstrKind::Pop), // clean up the peeked value
],
terminator: Terminator::Return,
}],
}],
}],
field_offsets,
field_types,
};
// 2. Lower to VM IR
let vm_module = lower_program(&program).expect("Lowering failed");
let func = &vm_module.functions[0];
// Assert VM IR contains required instructions
let kinds: Vec<_> = func.body.iter().map(|i| &i.kind).collect();
assert!(kinds.iter().any(|k| matches!(k, InstrKind::Alloc { type_id: tid, slots: 2 } if tid.0 == 10)), "Missing correct Alloc");
assert!(kinds.contains(&&InstrKind::GateBeginMutate), "Missing GateBeginMutate");
assert!(kinds.contains(&&InstrKind::GateEndMutate), "Missing GateEndMutate");
assert!(kinds.iter().any(|k| matches!(k, InstrKind::GateStore { offset: 0 })), "Missing correct GateStore");
assert!(kinds.contains(&&InstrKind::GateBeginPeek), "Missing GateBeginPeek");
assert!(kinds.contains(&&InstrKind::GateEndPeek), "Missing GateEndPeek");
assert!(kinds.iter().any(|k| matches!(k, InstrKind::GateLoad { offset: 0 })), "Missing correct GateLoad");
// RC ops
assert!(kinds.contains(&&InstrKind::GateRetain), "Missing GateRetain");
assert!(kinds.contains(&&InstrKind::GateRelease), "Missing GateRelease");
// 3. Emit Bytecode
let emit_result = emit_module(&vm_module).expect("Emission failed");
let bytecode = emit_result.rom;
// 4. Assert industrial PBS\0 format
use prometeu_bytecode::BytecodeLoader;
let module = BytecodeLoader::load(&bytecode).expect("Failed to parse industrial PBC");
assert_eq!(&bytecode[0..4], b"PBS\0");
// 5. Verify a few key instructions in the code section to ensure ABI stability
// We don't do a full byte-for-byte check of the entire file here as the section
// table offsets vary, but we check the instruction stream.
let instrs = module.code;
// Alloc { tid: 10, slots: 2 } -> 0x60 0x00, 0x0a 0x00 0x00 0x00, 0x02 0x00 0x00 0x00
assert!(instrs.windows(10).any(|w| w == &[0x60, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00]));
// PushConst 1 (42) -> 0x10 0x00, 0x01 0x00, 0x00, 0x00
assert!(instrs.windows(6).any(|w| w == &[0x10, 0x00, 0x01, 0x00, 0x00, 0x00]));
}
@@ -0,0 +1,83 @@
// use prometeu_compiler::compiler::compile;
// use std::path::PathBuf;
// use std::sync::Arc;
// use prometeu_compiler::ir_vm::Value;
// use prometeu_hal::{AssetBridge, AudioBridge, GfxBridge, HardwareBridge, HostContext, HostReturn, NativeInterface, PadBridge, TouchBridge};
//
// struct SimpleNative;
// impl NativeInterface for SimpleNative {
// fn syscall(&mut self, _id: u32, _args: &[Value], _ret: &mut HostReturn, _ctx: &mut HostContext) -> Result<(), VmFault> {
// Ok(())
// }
// }
//
// struct SimpleHardware {
// gfx: Gfx,
// audio: Audio,
// pad: Pad,
// touch: Touch,
// assets: AssetManager,
// }
//
// impl SimpleHardware {
// fn new() -> Self {
// let banks = Arc::new(MemoryBanks::new());
// Self {
// gfx: Gfx::new(320, 240, banks.clone()),
// audio: Audio::new(banks.clone()),
// pad: Pad::default(),
// touch: Touch::default(),
// assets: AssetManager::new(vec![], vec![], banks.clone(), banks.clone()),
// }
// }
// }
//
// impl HardwareBridge for SimpleHardware {
// fn gfx(&self) -> &dyn GfxBridge { &self.gfx }
// fn gfx_mut(&mut self) -> &mut dyn GfxBridge { &mut self.gfx }
// fn audio(&self) -> &dyn AudioBridge { &self.audio }
// fn audio_mut(&mut self) -> &mut dyn AudioBridge { &mut self.audio }
// fn pad(&self) -> &dyn PadBridge { &self.pad }
// fn pad_mut(&mut self) -> &mut dyn PadBridge { &mut self.pad }
// fn touch(&self) -> &dyn TouchBridge { &self.touch }
// fn touch_mut(&mut self) -> &mut dyn TouchBridge { &mut self.touch }
// fn assets(&self) -> &dyn AssetBridge { &self.assets }
// fn assets_mut(&mut self) -> &mut dyn AssetBridge { &mut self.assets }
// }
//
// #[test]
// fn test_integration_test01_link() {
// let project_dir = PathBuf::from("../../test-cartridges/test01");
// // Since the test runs from crates/prometeu-compiler, we need to adjust path if necessary.
// // Actually, usually tests run from the workspace root if using cargo test --workspace,
// // but if running from the crate dir, it's different.
//
// // Let's try absolute path or relative to project root.
// let mut root_dir = std::env::current_dir().unwrap();
// while !root_dir.join("test-cartridges").exists() {
// if let Some(parent) = root_dir.parent() {
// root_dir = parent.to_path_buf();
// } else {
// break;
// }
// }
// let _project_dir = root_dir.join("test-cartridges/test01");
//
// let unit = compile(&project_dir).expect("Failed to compile and link");
//
// let mut vm = VirtualMachine::default();
// // Use initialize to load the ROM; entrypoint must be numeric or empty (defaults to 0)
// vm.initialize(unit.rom, "frame").expect("Failed to initialize VM");
//
// let mut native = SimpleNative;
// let mut hw = SimpleHardware::new();
// let mut ctx = HostContext::new(Some(&mut hw));
//
// // Run for a bit
// let report = vm.run_budget(1000, &mut native, &mut ctx).expect("VM execution failed");
//
// // It should not trap. test01 might loop or return.
// if let LogicalFrameEndingReason::Trap(t) = report.reason {
// panic!("VM trapped: {:?}", t);
// }
// }