feat(pbs): add concrete generic structs and free functions

This commit is contained in:
2026-10-22 14:42:38 +01:00
parent 240216170c
commit 76a8b074e8
52 changed files with 3285 additions and 103 deletions
+84 -4
View File
@@ -37,6 +37,7 @@ impl NativeInterface for NoNative {
fn main() {
let root = std::path::PathBuf::from(std::env::args().nth(1).expect("fixture directory"));
if std::env::args().any(|arg| arg == "--generic-contracts-only") { verify_pbs_generic_contract_fixtures(&root); return; }
if std::env::args().any(|arg| arg == "--generic-structs-only") { verify_pbs_generic_struct_fixtures(&root); return; }
if std::env::args().any(|arg| arg == "--random-only") { verify_pbs_random_fixtures(&root); return; }
verify_pbs_math_fixtures(&root);
if std::env::args().any(|arg| arg == "--math-only") { return; }
@@ -45,6 +46,7 @@ fn main() {
verify_pbs_fixtures(&root);
verify_pbs_structured_fixtures(&root);
verify_pbs_generic_contract_fixtures(&root);
verify_pbs_generic_struct_fixtures(&root);
verify_pbs_resource_refusals(&root);
verify_pbs_closure_frames(&root);
for name in [
@@ -481,7 +483,7 @@ fn verify_pbs_fixtures(root: &std::path::Path) {
for entry in std::fs::read_dir(root).unwrap() {
let path = entry.unwrap().path();
let name = path.file_stem().unwrap().to_str().unwrap();
if name.starts_with("pbs-random-") || name.starts_with("pbs-math-") || name.starts_with("pbs-structured-") || name.starts_with("pbs-generic-contract-") || !name.starts_with("pbs-") || path.extension().and_then(|v| v.to_str()) != Some("pbx") { continue; }
if name.starts_with("pbs-random-") || name.starts_with("pbs-math-") || name.starts_with("pbs-structured-") || name.starts_with("pbs-generic-contract-") || name.starts_with("pbs-generic-struct-") || !name.starts_with("pbs-") || path.extension().and_then(|v| v.to_str()) != Some("pbx") { continue; }
count += 1;
let bytes = std::fs::read(&path).unwrap();
let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE)
@@ -592,6 +594,84 @@ fn verify_pbs_structured_fixtures(root: &std::path::Path) {
}
}
fn verify_pbs_generic_struct_fixtures(root: &std::path::Path) {
use prometeu_vm::{LogicalFrameEndingReason as End, resource_budget::{RuntimeLimits, RuntimeResource}};
use prometeu_bytecode::registry::TypeKind;
let mut object_heap = None;
let mut function_heap = None;
for name in ["basic", "manual", "constructor", "phantom", "tuple", "optional", "array", "recursive",
"combined", "function", "function-manual", "gc", "imports", "installed", "multiple", "origins"] {
let bytes = std::fs::read(root.join(format!("pbs-generic-struct-{name}.pbx")))
.unwrap_or_else(|error| panic!("missing mandatory generic struct/function fixture {name}: {error}"));
let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE)
.unwrap_or_else(|error| panic!("generic struct/function {name}: {error:?}"));
let declarations = image.registry().declarations();
if name == "phantom" {
let structs = declarations.types.iter().filter(|t| matches!(t.kind, TypeKind::Struct(_))
&& t.name.as_deref().is_some_and(|name| name.starts_with("Marker<"))).count();
assert_eq!(structs, 2, "phantom arguments preserve distinct nominal applications");
}
if name == "origins" {
assert_eq!(declarations.types.iter().filter(|t| t.name.as_deref() == Some("Enemy")).count(), 2);
assert_eq!(declarations.types.iter().filter(|t| t.name.as_deref() == Some("Box<Enemy>")).count(), 2);
}
if name == "combined" || name == "imports" {
assert_eq!(declarations.implementations.len(), 1, "one concrete owner/contract pair, shared across aliases");
let first = &declarations.implementations[0];
assert_eq!(image.registry().implementation(first.owner, first.trait_id).unwrap().0, 0);
}
println!("PBS GENERIC STRUCT METADATA {name}: types={} implementations={} bytes={}", declarations.types.len(), declarations.implementations.len(), bytes.len());
let limits = if ["basic", "manual", "function", "function-manual"].contains(&name) {
RuntimeLimits::default().lowered(RuntimeResource::HandleSlots, 1).unwrap()
} else { RuntimeLimits::default() };
let mut vm = VirtualMachine::from_image(image, limits);
let observer = vm.resource_observer();
vm.prepare_boot_call().unwrap();
let mut report = vm.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap();
if name == "gc" {
assert!(matches!(report.reason, End::FrameSync), "{name}: {report:?}");
let gc = vm.resource_snapshot().gc;
assert!(gc.collections >= 1 && gc.reclaimed >= 1100, "{gc:?}");
report = vm.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap();
}
assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{name}: {report:?}");
if name != "imports" && name != "origins" { assert_eq!(vm.operand_stack_top(1), vec![Value::Int32(42)], "{name}"); }
if name == "basic" || name == "manual" {
assert_eq!(vm.heap().len(), 1, "one object, without a generic wrapper");
let heap = observer.used(RuntimeResource::GuestBytes);
if let Some(reference) = object_heap { assert_eq!(heap, reference); }
object_heap = Some(heap);
}
if name == "function" || name == "function-manual" {
let heap = observer.used(RuntimeResource::GuestBytes);
if let Some(reference) = function_heap { assert_eq!(heap, reference); }
function_heap = Some(heap);
}
drop(vm);
for resource in [RuntimeResource::GuestBytes, RuntimeResource::HandleSlots, RuntimeResource::AuxiliaryBytes,
RuntimeResource::TemporaryBytes, RuntimeResource::StringBytes, RuntimeResource::StringAllocations] {
assert_eq!(observer.used(resource), 0, "{name}: release {resource:?}");
}
if name == "basic" || name == "combined" {
for (resource, limit) in [(RuntimeResource::GuestBytes, 0), (RuntimeResource::HandleSlots, 0)] {
let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap();
let mut refused = VirtualMachine::from_image(image, RuntimeLimits::default().lowered(resource, limit).unwrap());
let observed = refused.resource_observer();
refused.prepare_boot_call().unwrap();
let report = refused.run_budget(100_000, &mut NoNative, &mut HostContext::new(None)).unwrap();
assert!(matches!(report.reason, End::Trap(ref fault) if fault.code == prometeu_bytecode::TRAP_RESOURCE_LIMIT), "{name}/{resource:?}: {report:?}");
assert_eq!(refused.heap().len(), 0);
assert!(observed.used(resource) <= limit);
drop(refused);
for domain in [RuntimeResource::GuestBytes, RuntimeResource::HandleSlots, RuntimeResource::AuxiliaryBytes, RuntimeResource::TemporaryBytes] {
assert_eq!(observed.used(domain), 0);
}
}
}
println!("PBS GENERIC STRUCT SOURCE/LOAD/EXEC PASS {name}");
}
}
fn verify_pbs_generic_contract_fixtures(root: &std::path::Path) {
use prometeu_vm::{LogicalFrameEndingReason as End, resource_budget::{RuntimeLimits, RuntimeResource}};
use prometeu_bytecode::{registry::{TypeId, TypeKind}, isa::core::CoreOpCode};
@@ -862,9 +942,9 @@ fn verify_pbs_random_fixtures(root: &std::path::Path) {
}
};
add("mixed", vec![long(words[3]), "l:-7".into(), "f:3fb304aa46c98538".into()], vec![32,8,12,12,8], None);
add("storage", vec![long(words[0]),long(words[3]),long(words[2]),long(words[1]),long(words[0])], vec![32,8,8,8,8,32,8], None);
add("storage", vec![long(words[0]),long(words[3]),long(words[2]),long(words[1]),long(words[0])], vec![32,32,8,8,8,8,32,8], None);
for (name, trace) in [("named",312),("positional",123)] {
add(name,vec![long(words[3]),"l:-7".into(),format!("i:{trace}")],vec![32,8,8,12,8],None);
add(name,vec![long(words[3]),"l:-7".into(),format!("i:{trace}")],vec![32,32,8,8,12,8],None);
}
let bounds = [(0,1),(-10,-3),(-10,10),(0,16),(i64::MIN,0),(-1,i64::MAX),(i64::MIN,i64::MAX)];
for (index,(min,max)) in bounds.into_iter().enumerate() {
@@ -877,7 +957,7 @@ fn verify_pbs_random_fixtures(root: &std::path::Path) {
for index in [7,8] { add(&format!("range-{index}"),vec![],vec![32,4],Some(prometeu_bytecode::TRAP_NUMERIC_DOMAIN)); }
let rejected_then_accepted = i128::from(i64::MIN)+i128::from(words[2]%((1u64<<63)+1));
add("rejection",vec![long(words[3]),format!("l:{rejected_then_accepted}")],vec![32,8,20,8],None);
for name in ["null","typed-null"] { add(name,vec![],vec![8],Some(prometeu_bytecode::TRAP_NULL_REFERENCE)); }
for name in ["null","typed-null"] { add(name,vec![],vec![32,8],Some(prometeu_bytecode::TRAP_NULL_REFERENCE)); }
let mut gc_costs=vec![32;1101]; gc_costs.extend([8,8,8]);
add("gc",vec![long(words[2]),long(words[1]),long(words[0])],gc_costs,None);
let mut cycles_by_name = std::collections::BTreeMap::new();
+2 -1
View File
@@ -15,6 +15,7 @@ parser.add_argument("--release", action="store_true", help="Execute an optimized
parser.add_argument("--math-only", action="store_true", help="Run the complete PBS math corpus only")
parser.add_argument("--random-only", action="store_true", help="Run the complete PBS Random corpus only")
parser.add_argument("--generic-contracts-only", action="store_true", help="Run the mandatory generic-contract source corpus only")
parser.add_argument("--generic-structs-only", action="store_true", help="Run the mandatory generic-struct/function source corpus only")
args = parser.parse_args()
runtime = args.runtime.resolve()
if not args.math_only:
@@ -43,4 +44,4 @@ with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory:
(root / "Cargo.lock").write_text((runtime / "Cargo.lock").read_text())
(root / "src").mkdir()
(root / "src/main.rs").write_text(pathlib.Path(__file__).with_name("main.rs").read_text())
subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else []), *(["--generic-contracts-only"] if args.generic_contracts_only else [])], check=True)
subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else []), *(["--generic-contracts-only"] if args.generic_contracts_only else []), *(["--generic-structs-only"] if args.generic_structs_only else [])], check=True)