feat(studio): integrate memcard persistence and headless controls
Persist cartridge identity and slot configuration, add MemcardBoot and the MemcardBuffer SDK, and consume the runtime's negotiated memcard host controls with protected teardown. Qualify save/reopen and version upgrades through distinct configured runtime processes. Include specs, examples, regression evidence and the consolidated discussion lesson.
This commit is contained in:
+5
-1
@@ -456,7 +456,11 @@ public final class PbsFrontendCompiler {
|
||||
fileId,
|
||||
fileInitReference,
|
||||
projectInitReference,
|
||||
frameReference);
|
||||
frameReference,
|
||||
executableFunctions.stream().anyMatch(f -> f.metadata() != null
|
||||
&& f.metadata().role() == p.studio.compiler.models.registry.IRRegistry.Role.MEMCARD_BOOT)
|
||||
? ReadOnlyList.from(new IRBackendExecutableFunction.HostCallMetadata("mem", "bootstrap", 1, 0, 1))
|
||||
: ReadOnlyList.empty());
|
||||
return declaration.isEmpty() ? null : declaration;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -170,7 +170,7 @@ final class PbsGenericTemplateValidator {
|
||||
context.error("CONTEXT", "Generic construction requires an expected application or explicit type arguments", n.span());
|
||||
if (d instanceof PbsAst.StructDecl s) {
|
||||
var env = bindings(s, result);
|
||||
var constructor = PbsSdkCollections.isCollection(s) && n.ctorName()==null ? "make" : n.ctorName();
|
||||
var constructor = (PbsSdkCollections.isCollection(s) || PbsSdkMemcard.isBuffer(s)) && n.ctorName()==null ? "make" : n.ctorName();
|
||||
var expectedParameters = constructor == null ? map(s.fields(), f -> new PbsAst.Parameter(f.name(), PbsTypeSubstitution.substitute(f.typeRef(), env), f.span()))
|
||||
: s.ctors().stream().filter(c -> c.name().equals(constructor) && c.parameters().size()==n.arguments().size()).findFirst().map(c ->
|
||||
map(c.parameters(), p -> new PbsAst.Parameter(p.name(), PbsTypeSubstitution.substitute(p.typeRef(), env), p.span()))).orElse(ReadOnlyList.empty());
|
||||
|
||||
+11
@@ -45,6 +45,17 @@ public final class PbsHostAdmissionValidator {
|
||||
requiredCapabilities.add(normalizedCapability);
|
||||
}
|
||||
|
||||
for (var capability : metadata.requiredCapabilities()) {
|
||||
if (requiredCapabilities.contains(capability)) continue;
|
||||
if (!knownCapabilities.contains(capability) || context.enforceDeclaredCapabilities()
|
||||
&& !declaredCapabilities.contains(capability)) {
|
||||
Diagnostics.error(diagnostics, PbsHostAdmissionErrors.E_HOST_CAPABILITY_NOT_DECLARED.name(),
|
||||
"Required runtime capability '" + capability + "' is unavailable or not declared",
|
||||
p.studio.compiler.source.Span.none());
|
||||
} else {
|
||||
requiredCapabilities.add(capability);
|
||||
}
|
||||
}
|
||||
return ReadOnlyList.wrap(requiredCapabilities.stream().toList());
|
||||
}
|
||||
|
||||
|
||||
+5
@@ -21,6 +21,11 @@ public final class PbsReservedMetadataExtractor {
|
||||
final PbsAst.File ast,
|
||||
final SourceKind sourceKind) {
|
||||
if (sourceKind != SourceKind.SDK_INTERFACE) {
|
||||
if (ast.topDecls().stream().anyMatch(d -> d instanceof PbsAst.FunctionDecl f
|
||||
&& f.lifecycleMarker() == PbsAst.LifecycleMarker.MEMCARD_BOOT)) {
|
||||
return new IRReservedMetadata(ReadOnlyList.empty(), ReadOnlyList.empty(), ReadOnlyList.empty(),
|
||||
ReadOnlyList.from("memcard"));
|
||||
}
|
||||
return IRReservedMetadata.empty();
|
||||
}
|
||||
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
|
||||
/** Source identity of the installed SDK byte carrier; spelling alone grants no native layout. */
|
||||
public final class PbsSdkMemcard {
|
||||
private PbsSdkMemcard() {}
|
||||
|
||||
public static boolean isBuffer(PbsAst.TopDecl declaration) {
|
||||
return declaration instanceof PbsAst.StructDecl struct
|
||||
&& PbsSdkCollections.attribute(struct.attributes(), "SdkMemcardBuffer") != null;
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -137,7 +137,8 @@ public final class PbsAst {
|
||||
INIT("Init"),
|
||||
FRAME("Frame"),
|
||||
BEFORE_PAUSE("BeforePause"),
|
||||
BEFORE_RESUME("BeforeResume");
|
||||
BEFORE_RESUME("BeforeResume"),
|
||||
MEMCARD_BOOT("MemcardBoot");
|
||||
|
||||
private final String attributeName;
|
||||
|
||||
|
||||
+92
@@ -1106,6 +1106,19 @@ final class PbsExecutableBodyLowerer {
|
||||
if(slot==null) { reportUnsupportedLowering("Missing named argument: "+parameter.name(), apply.span(), c); return; }
|
||||
emitLoadLocalSlots(slot,c.types().slots(parameter.typeRef()),apply.span(),c);
|
||||
}
|
||||
if (call.callee() instanceof PbsAst.MemberExpr member) {
|
||||
var owner=PbsRuntimeTypes.unwrap(expressionType(member.receiver(),c));
|
||||
var service=owner==null?null:c.types().services.get(owner.name());
|
||||
if (service!=null) {
|
||||
var methods=service.methods().stream().filter(m -> m.name().equals(member.memberName())
|
||||
&& m.parameters().size()==signature.parameters().size()
|
||||
&& p.studio.compiler.pbs.PbsSdkCollections.attribute(m.attributes(),"HostForward")!=null).toList();
|
||||
if (methods.size()==1) {
|
||||
emitHostForward(methods.getFirst(),call,signature.parameters().stream().mapToInt(p->c.types().slots(p.typeRef())).sum(),c);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
callsiteEmitter.emitCallsite(call,c);
|
||||
}
|
||||
|
||||
@@ -1681,6 +1694,25 @@ final class PbsExecutableBodyLowerer {
|
||||
var operation=p.studio.compiler.pbs.PbsSdkCollections.argument(binding,"name");
|
||||
var span=function.span();
|
||||
switch(operation) {
|
||||
case "memcard_buffer_capacity" -> {
|
||||
emitGetLocal(0,span,c);
|
||||
registry(ARRAY_LEN,c.types().memcardBufferStorage(),0,1,1,span,c);
|
||||
identityIntrinsic("math.i64.to_i32",span,c);
|
||||
}
|
||||
case "memcard_buffer_read" -> {
|
||||
emitGetLocal(0,span,c);
|
||||
emitGetLocal(1,span,c);
|
||||
identityIntrinsic("math.i32.to_i64",span,c);
|
||||
registry(ARRAY_GET,c.types().memcardBufferStorage(),0,2,1,span,c);
|
||||
}
|
||||
case "memcard_buffer_write" -> {
|
||||
requireMemcardRange(2,255,span,c);
|
||||
emitGetLocal(0,span,c);
|
||||
emitGetLocal(1,span,c);
|
||||
identityIntrinsic("math.i32.to_i64",span,c);
|
||||
emitGetLocal(2,span,c);
|
||||
registry(ARRAY_SET,c.types().memcardBufferStorage(),0,3,0,span,c);
|
||||
}
|
||||
case "fail" -> {
|
||||
if (!function.parameters().isEmpty()) throw new IllegalArgumentException("SDK failure binding takes no operands");
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.TRAP,"",null,null,span));
|
||||
@@ -1868,6 +1900,19 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
private void lowerStructNew(PbsAst.NewExpr expr,PbsExecutableLoweringContext c) {
|
||||
var declaration=c.types().structs.get(expr.typeName());var ref=c.types().registryType(PbsRuntimeTypes.type(expr.typeName()));
|
||||
if (p.studio.compiler.pbs.PbsSdkMemcard.isBuffer(declaration)) {
|
||||
if (expr.arguments().size()!=1 || expr.ctorName()!=null && !expr.ctorName().equals("make")) {
|
||||
reportUnsupportedLowering("MemcardBuffer requires one int capacity",expr.span(),c);
|
||||
return;
|
||||
}
|
||||
lowerExpected(expr.arguments().getFirst(),PbsRuntimeTypes.type("int"),c);
|
||||
int capacity=save(1,expr.span(),c);
|
||||
requireMemcardRange(capacity,4096,expr.span(),c);
|
||||
emitGetLocal(capacity,expr.span(),c);
|
||||
identityIntrinsic("math.i32.to_i64",expr.span(),c);
|
||||
registry(ARRAY_NEW,ref,0,1,1,expr.span(),c);
|
||||
return;
|
||||
}
|
||||
boolean list=p.studio.compiler.pbs.PbsSdkCollections.hasCapacityConstructor(declaration);
|
||||
if(expr.ctorName()!=null) {
|
||||
var ctor=declaration.ctors().stream().filter(f->f.name().equals(expr.ctorName()) && parametersMatch(f.parameters(),expr.arguments(),c,list)).findFirst().orElse(null);
|
||||
@@ -1890,6 +1935,20 @@ final class PbsExecutableBodyLowerer {
|
||||
emitGetLocal(instance,expr.span(),c);
|
||||
}
|
||||
|
||||
private void requireMemcardRange(int slot,int maximum,Span span,PbsExecutableLoweringContext c) {
|
||||
var fail=c.nextLabel("memcard_range_invalid");
|
||||
var valid=c.nextLabel("memcard_range_valid");
|
||||
emitGetLocal(slot,span,c); emitPushI32(0,span,c);
|
||||
emitBinaryOperatorInstruction("<",span,c);
|
||||
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_TRUE,fail,span,c);
|
||||
emitGetLocal(slot,span,c); emitPushI32(maximum,span,c);
|
||||
emitBinaryOperatorInstruction(">",span,c);
|
||||
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE,valid,span,c);
|
||||
emitLabel(fail,span,c);
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.TRAP,"",null,null,span));
|
||||
emitLabel(valid,span,c);
|
||||
}
|
||||
|
||||
private void lowerFieldAssignment(PbsAst.AssignStatement statement,PbsExecutableLoweringContext c) {
|
||||
var target=statement.target();
|
||||
PbsAst.Expression receiver=target.rootName().equals("this")?new PbsAst.ThisExpr(target.span()):new PbsAst.IdentifierExpr(target.rootName(),target.span());
|
||||
@@ -1947,6 +2006,10 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
int pops=0;
|
||||
for(int i=0;i<call.arguments().size();i++){var type=PbsTypeSubstitution.replaceSelf(method.parameters().get(i).typeRef(),owner.name());lowerExpected(call.arguments().get(i),type,c);pops+=c.types().slots(type);}
|
||||
if (p.studio.compiler.pbs.PbsSdkCollections.attribute(method.attributes(),"HostForward") != null) {
|
||||
emitHostForward(method,call,pops,c);
|
||||
return true;
|
||||
}
|
||||
emitStructuredFunction(owner.name()+"."+method.name(),method.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),pops,c.types().slots(method.returnType()),call.span(),c);return true;
|
||||
}
|
||||
var struct=c.types().structs.get(owner.name());if(struct==null)return false;
|
||||
@@ -1964,6 +2027,35 @@ final class PbsExecutableBodyLowerer {
|
||||
return types;
|
||||
}
|
||||
|
||||
/** Native status-first payloads may be Null on error and cannot cross a typed wrapper RET. */
|
||||
private void emitHostForward(PbsAst.FunctionDecl method,PbsAst.CallExpr source,int arguments,PbsExecutableLoweringContext c) {
|
||||
var body=method.body();
|
||||
if (body==null || body.tailExpression()!=null || body.statements().size()!=1
|
||||
|| !(body.statements().getFirst() instanceof PbsAst.ReturnStatement result)
|
||||
|| !(result.value() instanceof PbsAst.CallExpr forward)
|
||||
|| forward.arguments().size()!=method.parameters().size()) {
|
||||
reportUnsupportedLowering("SDK HostForward requires one exact host return",source.span(),c);
|
||||
return;
|
||||
}
|
||||
for (int i=0;i<forward.arguments().size();i++) {
|
||||
if (!(forward.arguments().get(i) instanceof PbsAst.IdentifierExpr parameter)
|
||||
|| !parameter.name().equals(method.parameters().get(i).name())) {
|
||||
reportUnsupportedLowering("SDK HostForward must preserve all parameter positions",source.span(),c);
|
||||
return;
|
||||
}
|
||||
}
|
||||
var call=new PbsAst.CallExpr(forward.callee(),source.arguments(),source.span());
|
||||
var host=callsiteEmitter.resolveUniqueHostBinding(call,c);
|
||||
if (host==null || host.retSlots()!=c.types().slots(method.returnType())) {
|
||||
reportUnsupportedLowering("SDK HostForward requires a matching native result ABI",source.span(),c);
|
||||
return;
|
||||
}
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(
|
||||
IRBackendExecutableFunction.InstructionKind.CALL_HOST,"",null,
|
||||
new IRBackendExecutableFunction.HostCallMetadata(host.abiModule(),host.abiMethod(),host.abiVersion(),arguments,host.retSlots()),
|
||||
null,arguments,host.retSlots(),source.span()));
|
||||
}
|
||||
|
||||
private PbsAst.FunctionDecl sourceFunction(PbsAst.CallExpr call, PbsExecutableLoweringContext c) {
|
||||
if (!(call.callee() instanceof PbsAst.IdentifierExpr name)) return null;
|
||||
var candidates = c.types().functions.getOrDefault(name.name(),java.util.List.of()).stream()
|
||||
|
||||
+8
@@ -146,6 +146,12 @@ final class PbsRuntimeTypes {
|
||||
used.putIfAbsent(ref.declarationKey(), new IRRegistry.TypeDeclaration(ref, null, new IRRegistry.Array(element)));
|
||||
return ref;
|
||||
}
|
||||
IRRegistry.TypeRef memcardBufferStorage() {
|
||||
var ref = new IRRegistry.TypeRef("pbs:memcard-buffer");
|
||||
var element = builtin(0x10);
|
||||
used.putIfAbsent(ref.declarationKey(), new IRRegistry.TypeDeclaration(ref, "MemcardBuffer", new IRRegistry.Array(element)));
|
||||
return ref;
|
||||
}
|
||||
IRRegistry.TypeRef builtin(int id) {
|
||||
var ref = IRRegistry.TypeRef.builtin(id);
|
||||
used.putIfAbsent(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,null,new IRRegistry.Builtin(id)));
|
||||
@@ -158,6 +164,7 @@ final class PbsRuntimeTypes {
|
||||
}
|
||||
IRRegistry.TypeRef registryType(PbsAst.TypeRef type) {
|
||||
var t = unwrap(type);
|
||||
if (p.studio.compiler.pbs.PbsSdkMemcard.isBuffer(contractTypes.declaration(t))) return memcardBufferStorage();
|
||||
if (t.kind() == PbsAst.TypeRefKind.FN) {
|
||||
var ref = new IRRegistry.TypeRef("pbs:" + key(t));
|
||||
if (!used.containsKey(ref.declarationKey())) {
|
||||
@@ -234,6 +241,7 @@ final class PbsRuntimeTypes {
|
||||
ReadOnlyList.wrap(captures), switch (f.lifecycleMarker()) {
|
||||
case BEFORE_PAUSE -> IRRegistry.Role.BEFORE_PAUSE;
|
||||
case BEFORE_RESUME -> IRRegistry.Role.BEFORE_RESUME;
|
||||
case MEMCARD_BOOT -> IRRegistry.Role.MEMCARD_BOOT;
|
||||
default -> IRRegistry.Role.NONE;
|
||||
});
|
||||
}
|
||||
|
||||
+3
-3
@@ -696,7 +696,7 @@ final class PbsDeclarationParser {
|
||||
final String targetSurface) {
|
||||
for (final var attribute : attributes) {
|
||||
if ("Doc".equals(attribute.name()) || attribute.trustedSdkOrigin() &&
|
||||
java.util.Set.of("SdkList", "SdkLinked", "SdkSet", "SdkMap", "SdkStack", "SdkQueue").contains(attribute.name()) && "struct declarations".equals(targetSurface)) {
|
||||
java.util.Set.of("SdkList", "SdkLinked", "SdkSet", "SdkMap", "SdkStack", "SdkQueue", "SdkMemcardBuffer").contains(attribute.name()) && "struct declarations".equals(targetSurface)) {
|
||||
continue;
|
||||
}
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(),
|
||||
@@ -735,7 +735,7 @@ final class PbsDeclarationParser {
|
||||
for (final var attribute : attributes) {
|
||||
final PbsAst.LifecycleMarker nextMarker;
|
||||
if ("Doc".equals(attribute.name()) || attribute.trustedSdkOrigin() &&
|
||||
java.util.Set.of("StoragePrimitive","IdentityPrimitive","SdkPrivate").contains(attribute.name())) {
|
||||
java.util.Set.of("StoragePrimitive","IdentityPrimitive","SdkPrivate","HostForward").contains(attribute.name())) {
|
||||
continue;
|
||||
}
|
||||
if (!isOrdinaryMode()) {
|
||||
@@ -744,7 +744,7 @@ final class PbsDeclarationParser {
|
||||
}
|
||||
nextMarker = PbsAst.LifecycleMarker.forAttribute(attribute.name());
|
||||
if (nextMarker == PbsAst.LifecycleMarker.NONE) {
|
||||
reportAttributesNotAllowed(attributes, "Only [Doc] and lifecycle markers [Init], [Frame], [BeforePause], [BeforeResume] are allowed before top-level functions");
|
||||
reportAttributesNotAllowed(attributes, "Only [Doc] and lifecycle markers [Init], [Frame], [BeforePause], [BeforeResume], [MemcardBoot] are allowed before top-level functions");
|
||||
return PbsAst.LifecycleMarker.NONE;
|
||||
}
|
||||
|
||||
|
||||
+11
@@ -230,6 +230,17 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
return ExprResult.type(TypeView.optional(payloadExpected == null ? payload : payloadExpected));
|
||||
}
|
||||
if (expression instanceof PbsAst.NewExpr newExpr) {
|
||||
if (p.studio.compiler.pbs.PbsSdkMemcard.isBuffer(model.contractTypes.declaration(PbsAst.TypeRef.simple(newExpr.typeName(), newExpr.span())))) {
|
||||
if (newExpr.arguments().size() != 1 || newExpr.ctorName() != null && !newExpr.ctorName().equals("make")) {
|
||||
Diagnostics.error(diagnostics, "E_SEM_MEMCARD_BUFFER_CONSTRUCTOR",
|
||||
"MemcardBuffer requires exactly one int capacity", newExpr.span());
|
||||
} else {
|
||||
var capacity = analyzeValueExpression(newExpr.arguments().getFirst(), context, TypeView.intType()).type();
|
||||
if (!typeOps.compatible(capacity, TypeView.intType())) Diagnostics.error(diagnostics,
|
||||
"E_SEM_MEMCARD_BUFFER_CONSTRUCTOR", "MemcardBuffer capacity must be int", newExpr.span());
|
||||
}
|
||||
return ExprResult.type(typeOps.typeFromTypeRef(PbsAst.TypeRef.simple(newExpr.typeName(), newExpr.span()), model, null));
|
||||
}
|
||||
// Fieldless builtins are opaque provider references, not source constructors.
|
||||
if (model.isOpaqueBuiltin(TypeView.struct(newExpr.typeName()))) {
|
||||
Diagnostics.error(diagnostics, "E_SEM_OPAQUE_BUILTIN_CONSTRUCTION",
|
||||
|
||||
+18
@@ -45,6 +45,24 @@ public final class PbsLifecycleSemanticsValidator {
|
||||
private void validateLifecycleSignature(
|
||||
final PbsAst.FunctionDecl functionDecl,
|
||||
final p.studio.compiler.source.diagnostics.DiagnosticSink diagnostics) {
|
||||
if (functionDecl.lifecycleMarker() == PbsAst.LifecycleMarker.MEMCARD_BOOT) {
|
||||
final var valid = functionDecl.typeParameters().isEmpty()
|
||||
&& functionDecl.parameters().size() == 1
|
||||
&& functionDecl.parameters().getFirst().typeRef().kind() == PbsAst.TypeRefKind.SIMPLE
|
||||
&& "long".equals(functionDecl.parameters().getFirst().typeRef().name())
|
||||
&& functionDecl.returnKind() == PbsAst.ReturnKind.PLAIN
|
||||
&& functionDecl.returnType() != null
|
||||
&& functionDecl.returnType().kind() == PbsAst.TypeRefKind.SIMPLE
|
||||
&& "int".equals(functionDecl.returnType().name())
|
||||
&& functionDecl.resultErrorType() == null;
|
||||
if (!valid) {
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics,
|
||||
PbsSemanticsErrors.E_SEM_INVALID_LIFECYCLE_SIGNATURE.name(),
|
||||
"[MemcardBoot] requires a non-generic top-level function '(context: long) -> int'",
|
||||
functionDecl.span());
|
||||
}
|
||||
return;
|
||||
}
|
||||
final var valid = functionDecl.typeParameters().isEmpty()
|
||||
&& functionDecl.parameters().isEmpty()
|
||||
&& functionDecl.returnKind() == PbsAst.ReturnKind.EXPLICIT_UNIT
|
||||
|
||||
+2
-1
@@ -31,7 +31,8 @@ final class PbsProjectLifecycleSemanticsValidator {
|
||||
continue;
|
||||
}
|
||||
final var marker = functionDecl.lifecycleMarker();
|
||||
if (marker == PbsAst.LifecycleMarker.BEFORE_PAUSE || marker == PbsAst.LifecycleMarker.BEFORE_RESUME) {
|
||||
if (marker == PbsAst.LifecycleMarker.BEFORE_PAUSE || marker == PbsAst.LifecycleMarker.BEFORE_RESUME
|
||||
|| marker == PbsAst.LifecycleMarker.MEMCARD_BOOT) {
|
||||
final var previous = hooks.putIfAbsent(marker, functionDecl);
|
||||
if (previous != null) {
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(
|
||||
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
[Doc(markdown = """
|
||||
Fixed-capacity zero-initialized bytes for memcard transfers and icons. Copies alias
|
||||
one buffer. Capacity is 0..4096; values are 0..255; invalid access traps before mutation.
|
||||
The compiler emits concrete Array<Int32> storage, distinct from ordinary PBS arrays.
|
||||
""")]
|
||||
[SdkMemcardBuffer]
|
||||
declare struct MemcardBuffer() {
|
||||
ctor make(capacity: int) {}
|
||||
[StoragePrimitive(name = "memcard_buffer_capacity")]
|
||||
fn capacity() -> int { return 0; }
|
||||
[StoragePrimitive(name = "memcard_buffer_read")]
|
||||
fn read(index: int) -> int { return 0; }
|
||||
[StoragePrimitive(name = "memcard_buffer_write")]
|
||||
fn write(index: int, value: int) -> void {}
|
||||
}
|
||||
|
||||
[Doc(markdown = """Memcard v1 exact host ABI. Check leading status before reading payloads; errors leave unused payload positions Null.""")]
|
||||
declare host LowMem {
|
||||
[Doc(markdown = """Compiler-owned once-per-boot gate. Game source must use [MemcardBoot], not invoke this gate.""")]
|
||||
[Host(module = "mem", name = "bootstrap", version = 1)]
|
||||
[Capability(name = "memcard")]
|
||||
fn bootstrap() -> int;
|
||||
|
||||
[Doc(markdown = """Returns the admitted local slot count. Check status before inspecting payloads.""")]
|
||||
[Host(module = "mem", name = "slot_count", version = 1)]
|
||||
[Capability(name = "memcard")]
|
||||
fn slot_count(context: long) -> (status: long, count: long);
|
||||
|
||||
[Doc(markdown = """Reports durable descriptor and RAM length/dirty state. has_payload is numeric 0/1; CRC is not a checksum of unsaved RAM.""")]
|
||||
[Host(module = "mem", name = "slot_stat", version = 1)]
|
||||
[Capability(name = "memcard")]
|
||||
fn slot_stat(context: long, slot: int) -> (status: long, has_payload: long, used_bytes: long, durable: (generation: long, update_at: long, crc32c: long), dirty: bool);
|
||||
|
||||
[Doc(markdown = """Copies at most 4096 bytes to MemcardBuffer (native Array<Int32>). Check status first; invalid carrier/range may trap.""")]
|
||||
[Host(module = "mem", name = "slot_read", version = 1)]
|
||||
[Capability(name = "memcard")]
|
||||
fn slot_read(context: long, slot: int, offset: int, bytes: MemcardBuffer, array_offset: int, count: int) -> (status: long, bytes_read: long);
|
||||
|
||||
[Doc(markdown = """Writes RAM only; bytes must be 0..255, transfer at most 4096. Gaps are zero-filled; commit is explicit.""")]
|
||||
[Host(module = "mem", name = "slot_write", version = 1)]
|
||||
[Capability(name = "memcard")]
|
||||
fn slot_write(context: long, slot: int, offset: int, bytes: MemcardBuffer, array_offset: int, count: int) -> (status: long, bytes_written: long);
|
||||
|
||||
[Doc(markdown = """Submits a frozen-slot commit. Status OK accepts the request; query determines durability. The source rejects writes/clear with BUSY until safe completion.""")]
|
||||
[Host(module = "mem", name = "slot_commit", version = 1)]
|
||||
[Capability(name = "memcard")]
|
||||
fn slot_commit(context: long, slot: int) -> (status: long, request: long);
|
||||
|
||||
[Doc(markdown = """Clears RAM while retaining ownership. Call commit explicitly to persist the clear.""")]
|
||||
[Host(module = "mem", name = "slot_clear", version = 1)]
|
||||
[Capability(name = "memcard")]
|
||||
fn slot_clear(context: long, slot: int) -> long;
|
||||
|
||||
[Doc(markdown = """States: 0 PENDING, 1 SUCCESS, 2 FAILURE, 3 INDETERMINATE, 4 MEMORY_ONLY. Reason 15 is deadline/restart, independent of state. No busy-wait in lifecycle hooks.""")]
|
||||
[Host(module = "mem", name = "query", version = 1)]
|
||||
[Capability(name = "memcard")]
|
||||
fn query(context: long, request: long) -> (status: long, state: long, reason: long);
|
||||
|
||||
[Doc(markdown = """Releases the single retained terminal result. It never frees resources still used by in-flight IO.""")]
|
||||
[Host(module = "mem", name = "release", version = 1)]
|
||||
[Capability(name = "memcard")]
|
||||
fn release(context: long, request: long) -> long;
|
||||
|
||||
[Doc(markdown = """Mode 0 PERSISTENT or 1 MEMORY_ONLY. RAM-only commits make no persistence claim and perform no IO.""")]
|
||||
[Host(module = "mem", name = "info", version = 1)]
|
||||
[Capability(name = "memcard")]
|
||||
fn info(context: long) -> (status: long, mode: long, is_new: bool, recovered: bool, degraded: bool, write_blocked: bool);
|
||||
|
||||
[Doc(markdown = """Returns public game metadata. Timestamp/generation long values preserve unsigned 64-bit bit patterns.""")]
|
||||
[Host(module = "mem", name = "metadata", version = 1)]
|
||||
[Capability(name = "memcard")]
|
||||
fn metadata(context: long) -> (status: long, title: str, data_format_version: long, created_at: long);
|
||||
|
||||
[Doc(markdown = """Sets title/format and icon (48-byte RGB palette plus 512 bytes per 32x32 frame, 1..4 frames). Initial publication follows READY; updates require publish_presentation.""")]
|
||||
[Host(module = "mem", name = "presentation", version = 1)]
|
||||
[Capability(name = "memcard")]
|
||||
fn presentation(context: long, title: str, data_format_version: long, frames: int, duration: int, bytes: MemcardBuffer, offset: int, count: int) -> long;
|
||||
|
||||
[Doc(markdown = """Sets a bounded diagnostic of at most 1024 UTF-8 bytes for bootstrap admission.""")]
|
||||
[Host(module = "mem", name = "diagnostic", version = 1)]
|
||||
[Capability(name = "memcard")]
|
||||
fn diagnostic(context: long, message: str) -> long;
|
||||
|
||||
[Doc(markdown = """Explicitly publishes a presentation update using the same single request/result entry.""")]
|
||||
[Host(module = "mem", name = "publish_presentation", version = 1)]
|
||||
[Capability(name = "memcard")]
|
||||
fn publish_presentation(context: long) -> (status: long, request: long);
|
||||
|
||||
}
|
||||
|
||||
[Doc(markdown = """Explicit RAM access and asynchronous save publication. Check status, poll query across normal frames, release the terminal result. No autosave, retry, disk wait or codec is hidden by this facade.""")]
|
||||
declare service Mem {
|
||||
[Doc(markdown = """Compiler-owned once-per-boot gate. Game source must use [MemcardBoot], not invoke this gate.""")]
|
||||
[HostForward]
|
||||
fn bootstrap() -> int {
|
||||
return LowMem.bootstrap();
|
||||
}
|
||||
|
||||
[Doc(markdown = """Returns the admitted local slot count. Check status before inspecting payloads.""")]
|
||||
[HostForward]
|
||||
fn slot_count(context: long) -> (status: long, count: long) {
|
||||
return LowMem.slot_count(context);
|
||||
}
|
||||
|
||||
[Doc(markdown = """Reports durable descriptor and RAM length/dirty state. has_payload is numeric 0/1; CRC is not a checksum of unsaved RAM.""")]
|
||||
[HostForward]
|
||||
fn slot_stat(context: long, slot: int) -> (status: long, has_payload: long, used_bytes: long, durable: (generation: long, update_at: long, crc32c: long), dirty: bool) {
|
||||
return LowMem.slot_stat(context, slot);
|
||||
}
|
||||
|
||||
[Doc(markdown = """Copies at most 4096 bytes to MemcardBuffer (native Array<Int32>). Check status first; invalid carrier/range may trap.""")]
|
||||
[HostForward]
|
||||
fn slot_read(context: long, slot: int, offset: int, bytes: MemcardBuffer, array_offset: int, count: int) -> (status: long, bytes_read: long) {
|
||||
return LowMem.slot_read(context, slot, offset, bytes, array_offset, count);
|
||||
}
|
||||
|
||||
[Doc(markdown = """Writes RAM only; bytes must be 0..255, transfer at most 4096. Gaps are zero-filled; commit is explicit.""")]
|
||||
[HostForward]
|
||||
fn slot_write(context: long, slot: int, offset: int, bytes: MemcardBuffer, array_offset: int, count: int) -> (status: long, bytes_written: long) {
|
||||
return LowMem.slot_write(context, slot, offset, bytes, array_offset, count);
|
||||
}
|
||||
|
||||
[Doc(markdown = """Submits a frozen-slot commit. Status OK accepts the request; query determines durability. The source rejects writes/clear with BUSY until safe completion.""")]
|
||||
[HostForward]
|
||||
fn slot_commit(context: long, slot: int) -> (status: long, request: long) {
|
||||
return LowMem.slot_commit(context, slot);
|
||||
}
|
||||
|
||||
[Doc(markdown = """Clears RAM while retaining ownership. Call commit explicitly to persist the clear.""")]
|
||||
[HostForward]
|
||||
fn slot_clear(context: long, slot: int) -> long {
|
||||
return LowMem.slot_clear(context, slot);
|
||||
}
|
||||
|
||||
[Doc(markdown = """States: 0 PENDING, 1 SUCCESS, 2 FAILURE, 3 INDETERMINATE, 4 MEMORY_ONLY. Reason 15 is deadline/restart, independent of state. No busy-wait in lifecycle hooks.""")]
|
||||
[HostForward]
|
||||
fn query(context: long, request: long) -> (status: long, state: long, reason: long) {
|
||||
return LowMem.query(context, request);
|
||||
}
|
||||
|
||||
[Doc(markdown = """Releases the single retained terminal result. It never frees resources still used by in-flight IO.""")]
|
||||
[HostForward]
|
||||
fn release(context: long, request: long) -> long {
|
||||
return LowMem.release(context, request);
|
||||
}
|
||||
|
||||
[Doc(markdown = """Mode 0 PERSISTENT or 1 MEMORY_ONLY. RAM-only commits make no persistence claim and perform no IO.""")]
|
||||
[HostForward]
|
||||
fn info(context: long) -> (status: long, mode: long, is_new: bool, recovered: bool, degraded: bool, write_blocked: bool) {
|
||||
return LowMem.info(context);
|
||||
}
|
||||
|
||||
[Doc(markdown = """Returns public game metadata. Timestamp/generation long values preserve unsigned 64-bit bit patterns.""")]
|
||||
[HostForward]
|
||||
fn metadata(context: long) -> (status: long, title: str, data_format_version: long, created_at: long) {
|
||||
return LowMem.metadata(context);
|
||||
}
|
||||
|
||||
[Doc(markdown = """Sets title/format and icon (48-byte RGB palette plus 512 bytes per 32x32 frame, 1..4 frames). Initial publication follows READY; updates require publish_presentation.""")]
|
||||
[HostForward]
|
||||
fn presentation(context: long, title: str, data_format_version: long, frames: int, duration: int, bytes: MemcardBuffer, offset: int, count: int) -> long {
|
||||
return LowMem.presentation(context, title, data_format_version, frames, duration, bytes, offset, count);
|
||||
}
|
||||
|
||||
[Doc(markdown = """Sets a bounded diagnostic of at most 1024 UTF-8 bytes for bootstrap admission.""")]
|
||||
[HostForward]
|
||||
fn diagnostic(context: long, message: str) -> long {
|
||||
return LowMem.diagnostic(context, message);
|
||||
}
|
||||
|
||||
[Doc(markdown = """Explicitly publishes a presentation update using the same single request/result entry.""")]
|
||||
[HostForward]
|
||||
fn publish_presentation(context: long) -> (status: long, request: long) {
|
||||
return LowMem.publish_presentation(context);
|
||||
}
|
||||
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
pub struct MemcardBuffer;
|
||||
mod host LowMem;
|
||||
pub service Mem;
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
# Memcard example (explicit opt-in)
|
||||
|
||||
The `memcard/` subproject is separate from the default example. Build its own
|
||||
prometeu.json; do not copy its hook into an ordinary image without declaring slots.
|
||||
Its explicit app_id survives renames/upgrades. A copied manifest represents the
|
||||
same game; assign a distinct explicit uint32 identity when creating another game.
|
||||
|
||||
The compiler emits the bootstrap gate automatically after Init. [MemcardBoot]
|
||||
receives a session context, sets presentation and reads already admitted RAM.
|
||||
A commit submitted there must not be awaited: registration is provisional until
|
||||
READY. This example submits in Frame, polls across frames, checks leading status
|
||||
before reading any payload and releases the one retained result. Slot data is
|
||||
private game data; the four-byte example is not a general serialization codec.
|
||||
|
||||
The runtime owns PERSISTENT / clean MEMORY_ONLY / load-existing MEMORY_ONLY,
|
||||
media creation, mounting, concurrency, dirty-session discard and reconciliation.
|
||||
The development image is `.studio/memcard.pmc`, outside build output, or an
|
||||
explicitly chosen shared image through a supported host surface. Creating media
|
||||
is explicit and never replaces existing files. Studio does not implement a host
|
||||
or invent CLI/JSONL options when the configured runtime lacks that surface.
|
||||
|
||||
SDK `@sdk:mem` exports Mem and MemcardBuffer. LowMem is the ABI binding. Numeric results and
|
||||
context/request use long, flags use bool, bytes use MemcardBuffer (0..255, maximum
|
||||
4096 per call). The opaque buffer is zero initialized, fixed capacity 0..4096;
|
||||
capacity(), read(index) and write(index,value) use int. Invalid accesses trap.
|
||||
Copies alias the same native Array<Int32>, without Dynamic boxing or a wrapper.
|
||||
Ordinary PBS arrays keep their vacancy/optional semantics. Domain failures leave unused payload positions Null: inspect only
|
||||
status on error. slot_stat.has_payload is numeric 0/1, while dirty is bool. The facade groups generation/update_at/crc32c under
|
||||
`stat.durable`; flattening preserves all seven native results in their exact order.
|
||||
|
||||
Query states: 0 pending, 1 durable success, 2 failure with proven no publication,
|
||||
3 indeterminate requiring runtime reconciliation, 4 memory-only without IO.
|
||||
Reason 15 reports a deadline/restart independently of state; Success/15 is valid.
|
||||
Submitting a request is not durable success. Releasing a result never releases
|
||||
resources still held by IO. A committing slot rejects write/clear with BUSY;
|
||||
other slots and reads can continue. Hooks may submit/query but never busy-wait.
|
||||
|
||||
BeforePause can submit and return; BeforeResume can query. Neither restarts Init
|
||||
or bootstrap or saves implicitly. Process/transport loss does not prove rollback.
|
||||
Keep dirty/pending/discard choices owned by the runtime. In memory-only mode,
|
||||
completion ends the request without labeling it durable.
|
||||
|
||||
Qualification must save successfully, end the process, reopen the same image in
|
||||
a new configured runtime process and read exactly 00 7f 80 ff, including after a
|
||||
project-version change with the same app_id. Native tests are separate evidence.
|
||||
|
||||
Studio headless integration requires runtime protocol 1.1 and capability memcard.
|
||||
After building, boot with an explicit memcardChoice and optional memcard mount
|
||||
configuration. For example, Studio MCP boot accepts:
|
||||
|
||||
```json
|
||||
{"projectRoot":"/absolute/project","taskId":"current-task","buildId":"current-build","memcard":{"action":"open","access":"read_write"},"memcardChoice":"persistent"}
|
||||
```
|
||||
|
||||
Omitted image path selects `.studio/memcard.pmc`. Open never creates; deliberate
|
||||
first creation uses action `create`. An explicit path selects an external image.
|
||||
Use `studio_headless_memcard_state` to observe native state. Shutdown/reset may
|
||||
refuse with MEMCARD_ERROR and native reason/state; the session remains usable.
|
||||
Only a later explicit decision may supply discardUnsaved/pendingWrites. RAM-only
|
||||
boot is explicitly `memory_fresh`, without a mount. The runtime owns these choices.
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"name":"Memcard example","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","app_id":1296387395,"memcard_slots":1,"dependencies":[]}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import {Mem, MemcardBuffer} from @sdk:mem;
|
||||
|
||||
declare global saveContext: long = 0;
|
||||
declare global saveRequest: long = 0;
|
||||
declare global saved: bool = false;
|
||||
declare global completed: bool = false;
|
||||
declare global lastSaveState: long = 0;
|
||||
declare global loaded: bool = false;
|
||||
declare global initialized: bool = false;
|
||||
|
||||
[Init] fn initialize() -> void { initialized = true; }
|
||||
|
||||
[MemcardBoot] fn restore(context: long) -> int {
|
||||
if initialized == false { return 1; }
|
||||
saveContext = context;
|
||||
let icon = new MemcardBuffer(560);
|
||||
let status = Mem.presentation(context, "Memcard example", 1 as long, 1, 1, icon, 0, 560);
|
||||
if status != 0 as long { Mem.diagnostic(context, "Presentation rejected"); return 1; }
|
||||
let stat = Mem.slot_stat(context, 0);
|
||||
if stat.status != 0 as long { return 1; }
|
||||
if stat.used_bytes > 0 as long {
|
||||
let bytes = new MemcardBuffer(4);
|
||||
let read = Mem.slot_read(context, 0, 0, bytes, 0, 4);
|
||||
if read.status != 0 as long { return 1; }
|
||||
if read.bytes_read != 4 as long { return 1; }
|
||||
if bytes.read(0) != 0 or bytes.read(1) != 127 or bytes.read(2) != 128 or bytes.read(3) != 255 {
|
||||
Mem.diagnostic(context, "Unexpected saved payload"); return 1;
|
||||
}
|
||||
loaded = true;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
[Frame] fn frame() -> void {
|
||||
if completed or loaded { return; }
|
||||
if saveRequest == 0 as long {
|
||||
let bytes = new MemcardBuffer(4);
|
||||
bytes.write(0, 0); bytes.write(1, 127); bytes.write(2, 128); bytes.write(3, 255);
|
||||
let write = Mem.slot_write(saveContext, 0, 0, bytes, 0, 4);
|
||||
if write.status != 0 as long { completed = true; return; }
|
||||
let commit = Mem.slot_commit(saveContext, 0);
|
||||
if commit.status == 0 as long { saveRequest = commit.request; }
|
||||
else { completed = true; }
|
||||
return;
|
||||
}
|
||||
let observation = Mem.query(saveContext, saveRequest);
|
||||
if observation.status != 0 as long { return; }
|
||||
if observation.state == 0 as long { return; }
|
||||
// A memory-only result is complete, but does not claim disk persistence.
|
||||
saved = observation.state == 1 as long;
|
||||
lastSaveState = observation.state;
|
||||
completed = true;
|
||||
Mem.release(saveContext, saveRequest);
|
||||
saveRequest = 0 as long;
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
pub fn frame() -> void;
|
||||
+27
@@ -14,6 +14,33 @@ import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsGuestLifecycleSemanticsTest {
|
||||
@Test void memcardRequiresExactTypedSignatureAndKeepsSourceDiagnostics() {
|
||||
var valid = "[MemcardBoot] fn arbitrary(context: long) -> int { return 0; }";
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(9), valid, diagnostics);
|
||||
assertFalse(diagnostics.hasErrors(), diagnostics.stream().map(d -> d.getMessage()).toList().toString());
|
||||
assertTrue(new PBSSemanticTokenProvider().tokenize(valid).stream().anyMatch(t -> t.semanticKey().equals("pbs-lifecycle")));
|
||||
for (var source : List.of(
|
||||
"[MemcardBoot] fn bad() -> int { return 0; }",
|
||||
"[MemcardBoot] fn bad(c: int) -> int { return 0; }",
|
||||
"[MemcardBoot] fn bad(c: long) -> long { return 0 as long; }",
|
||||
"[MemcardBoot] fn bad<T>(c: long) -> int { return 0; }",
|
||||
"[MemcardBoot(value = 1)] fn bad(c: long) -> int { return 0; }",
|
||||
"[MemcardBoot][BeforePause] fn bad(c: long) -> int { return 0; }",
|
||||
"declare service Bad { [MemcardBoot] fn bad(c: long) -> int { return 0; } }")) {
|
||||
var errors = DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(9), source, errors);
|
||||
assertTrue(errors.hasErrors(), source);
|
||||
}
|
||||
var first = file(1, valid);
|
||||
var second = file(2, valid.replace("arbitrary", "conflict"));
|
||||
var frame = file(0, "[Frame] fn frame() -> void {}");
|
||||
diagnostics = DiagnosticSink.empty();
|
||||
new PbsProjectLifecycleSemanticsValidator().validate(List.of(frame, first, first), diagnostics);
|
||||
assertFalse(diagnostics.hasErrors());
|
||||
new PbsProjectLifecycleSemanticsValidator().validate(List.of(frame, first, second), diagnostics);
|
||||
assertTrue(diagnostics.stream().anyMatch(d -> d.getCode().equals("E_SEM_DUPLICATE_LIFECYCLE_ROLE")));
|
||||
}
|
||||
@Test void permitsGlobalsClosuresAndDocOnBothHooks() {
|
||||
var source = """
|
||||
declare global state: int = 0;
|
||||
|
||||
+16
-1
@@ -156,6 +156,15 @@ public final class LifecycleAssemblerService {
|
||||
0,
|
||||
frameExecutable.span()));
|
||||
}
|
||||
for (final var bootstrap : declaration.bootstrapCalls()) {
|
||||
wrapperInstructions.add(new IRBackendExecutableFunction.Instruction(
|
||||
IRBackendExecutableFunction.InstructionKind.CALL_HOST, "", null, bootstrap, null,
|
||||
bootstrap.argSlots(), bootstrap.retSlots(), frameExecutable.span()));
|
||||
for (int i = 0; i < bootstrap.retSlots(); i++) {
|
||||
wrapperInstructions.add(new IRBackendExecutableFunction.Instruction(
|
||||
IRBackendExecutableFunction.InstructionKind.POP, "", null, null, frameExecutable.span()));
|
||||
}
|
||||
}
|
||||
wrapperInstructions.add(pushBoolInstruction(true, frameExecutable.span()));
|
||||
wrapperInstructions.add(setGlobalInstruction(bootGuardSlot, frameExecutable.span()));
|
||||
wrapperInstructions.add(labelInstruction("bootstrap_done", frameExecutable.span()));
|
||||
@@ -171,7 +180,7 @@ public final class LifecycleAssemblerService {
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
2,
|
||||
Math.max(2, declaration.bootstrapCalls().stream().mapToInt(IRBackendExecutableFunction.HostCallMetadata::retSlots).max().orElse(0)),
|
||||
ReadOnlyList.wrap(wrapperInstructions),
|
||||
frameExecutable.span()));
|
||||
syntheticFunctions.add(new IRSyntheticFunction(
|
||||
@@ -221,6 +230,12 @@ public final class LifecycleAssemblerService {
|
||||
final IRLifecycleDeclaration declaration,
|
||||
final BuildingIssueSink issues) {
|
||||
var valid = true;
|
||||
for (final var bootstrap : declaration.bootstrapCalls()) {
|
||||
if (bootstrap.argSlots() != 0) {
|
||||
report(issues, null, "bootstrap boundary must not require operands from initialization");
|
||||
valid = false;
|
||||
}
|
||||
}
|
||||
for (final var synthetic : backend.getSyntheticFunctions()) {
|
||||
if (synthetic.kind() != IRSyntheticCallableKind.FILE_INIT_FRAGMENT) {
|
||||
report(issues, synthetic.origin().span(),
|
||||
|
||||
+21
@@ -22,6 +22,27 @@ public final class AssembleLifecyclePipelineStage implements PipelineStage {
|
||||
@Override
|
||||
public BuildingIssueSink run(final BuilderPipelineContext ctx, final LogAggregator logs) {
|
||||
final var issues = BuildingIssueSink.empty();
|
||||
if (ctx.rootProjectPathCanon != null && ctx.irBackend != null) {
|
||||
final var slots = p.studio.compiler.utilities.PrometeuManifestUtils.memcardSlots(
|
||||
ctx.rootProjectPathCanon.resolve("prometeu.json"), issues);
|
||||
final var roles = ctx.irBackend.getExecutableFunctions().stream().filter(f -> f.metadata() != null
|
||||
&& f.metadata().role() == p.studio.compiler.models.registry.IRRegistry.Role.MEMCARD_BOOT).count();
|
||||
final var capability = ctx.irBackend.getReservedMetadata().requiredCapabilities().contains("memcard");
|
||||
final var boundary = ctx.irBackend.getLifecycleDeclaration() != null
|
||||
&& ctx.irBackend.getLifecycleDeclaration().bootstrapCalls().stream().anyMatch(c ->
|
||||
c.module().equals("mem") && c.name().equals("bootstrap") && c.version() == 1
|
||||
&& c.argSlots() == 0 && c.retSlots() == 1);
|
||||
if ((slots != null || roles != 0 || capability || boundary)
|
||||
&& (slots == null || roles != 1 || !capability || !boundary)) {
|
||||
issues.report(b -> b.error(true).phase("lifecycle-assembly").code("COMMON_MEMCARD_CONFIGURATION")
|
||||
.message("memcard requires memcard_slots (1..64), capability, one MemcardBoot role and a bootstrap boundary"));
|
||||
}
|
||||
if (slots != null && ctx.resolvedWorkspace != null && ctx.resolvedWorkspace.target() != p.studio.AppMode.Game) {
|
||||
issues.report(b -> b.error(true).phase("lifecycle-assembly").code("COMMON_MEMCARD_CONFIGURATION")
|
||||
.message("memcard is available only to the runtime Game profile"));
|
||||
}
|
||||
if (issues.hasErrors()) return issues;
|
||||
}
|
||||
final var assembled = assembler.assemble(ctx.irBackend, issues);
|
||||
if (!issues.hasErrors()) {
|
||||
ctx.irBackend = assembled;
|
||||
|
||||
+21
@@ -30,6 +30,27 @@ import java.util.Arrays;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class LifecycleAssemblerServiceTest {
|
||||
@Test void neutralHostBootstrapRunsAfterInitializersBeforeGuardAndFrame() {
|
||||
final var original = declarativeBackend().getLifecycleDeclaration();
|
||||
final var request = new IRBackendExecutableFunction.HostCallMetadata("neutral-provider", "prepare", 7, 0, 1);
|
||||
final var backend = backendWithDeclaration(new IRLifecycleDeclaration(original.modules(), original.projectInit(),
|
||||
original.frameRoot(), ReadOnlyList.from(request)));
|
||||
final var issues = BuildingIssueSink.empty();
|
||||
final var assembled = new LifecycleAssemblerService().assemble(backend, issues);
|
||||
assertFalse(issues.hasErrors(), issues.asCollection().toString());
|
||||
final var instructions = executable(assembled, assembled.getEntryPointCallableName()).instructions();
|
||||
int index = -1;
|
||||
for (int i = 0; i < instructions.size(); i++) {
|
||||
if (instructions.get(i).kind() == IRBackendExecutableFunction.InstructionKind.CALL_HOST) index = i;
|
||||
}
|
||||
assertTrue(index > 0);
|
||||
assertEquals(request, instructions.get(index).hostCall());
|
||||
assertEquals(IRBackendExecutableFunction.InstructionKind.CALL_FUNC, instructions.get(index - 1).kind());
|
||||
assertEquals(IRBackendExecutableFunction.InstructionKind.POP, instructions.get(index + 1).kind());
|
||||
assertEquals(IRBackendExecutableFunction.InstructionKind.SET_GLOBAL, instructions.get(index + 3).kind());
|
||||
assertEquals(IRBackendExecutableFunction.InstructionKind.LABEL, instructions.get(index + 4).kind());
|
||||
assertEquals("frame", instructions.get(index + 5).calleeCallableName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void assembleMustMaterializeNeutralLifecycleArtifactsInDeclaredOrder() {
|
||||
|
||||
+3
-1
@@ -11,7 +11,9 @@ public record PrometeuManifestDTO(
|
||||
String language,
|
||||
String stdlib,
|
||||
String target,
|
||||
List<DependencyDeclaration> dependencies) {
|
||||
List<DependencyDeclaration> dependencies,
|
||||
@JsonProperty("app_id") com.fasterxml.jackson.databind.JsonNode appId,
|
||||
@JsonProperty("memcard_slots") com.fasterxml.jackson.databind.JsonNode memcardSlots) {
|
||||
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
|
||||
@JsonSubTypes({
|
||||
|
||||
+7
-1
@@ -10,5 +10,11 @@ public record PrometeuManifest(
|
||||
String language,
|
||||
int stdlib,
|
||||
AppMode target,
|
||||
ReadOnlyList<DependencyReference> dependencies) {
|
||||
ReadOnlyList<DependencyReference> dependencies,
|
||||
Long appId,
|
||||
Integer memcardSlots) {
|
||||
public PrometeuManifest(String name, String version, String language, int stdlib, AppMode target,
|
||||
ReadOnlyList<DependencyReference> dependencies) {
|
||||
this(name, version, language, stdlib, target, dependencies, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
+19
-1
@@ -63,11 +63,29 @@ public final class PrometeuManifestUtils {
|
||||
? FrontendRegistryService.getDefaultProvider().specification().getLanguageId()
|
||||
: dto.language();
|
||||
final var dependencies = DependencyResolver.resolveDependencies(mainProjectRootPathCanon, dto.dependencies(), issuesLocal);
|
||||
final var appId = optionalInteger(dto.appId(), "app_id", 0, 0xffff_ffffL, issuesLocal);
|
||||
final var slots = optionalInteger(dto.memcardSlots(), "memcard_slots", 1, 64, issuesLocal);
|
||||
if (ReadOnlyCollection.isNotEmpty(issuesLocal)) {
|
||||
issues.merge(issuesLocal);
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new PrometeuManifest(dto.name(), dto.version(), language, stdlibMaybe.getAsInt(), target, ReadOnlyList.wrap(dependencies)));
|
||||
return Optional.of(new PrometeuManifest(dto.name(), dto.version(), language, stdlibMaybe.getAsInt(), target,
|
||||
ReadOnlyList.wrap(dependencies), appId, slots == null ? null : slots.intValue()));
|
||||
}
|
||||
|
||||
private static Long optionalInteger(com.fasterxml.jackson.databind.JsonNode value, String name,
|
||||
long min, long max, BuildingIssueSink issues) {
|
||||
if (value == null) return null;
|
||||
if (!value.isIntegralNumber() || !value.canConvertToLong() || value.longValue() < min || value.longValue() > max) {
|
||||
issues.report(b -> b.error(true).message("[DEPS]: '" + name + "' must be an integer in " + min + ".." + max));
|
||||
return null;
|
||||
}
|
||||
return value.longValue();
|
||||
}
|
||||
|
||||
public static Integer memcardSlots(Path manifestPath, BuildingIssueSink issues) {
|
||||
Long slots = optionalInteger(read(manifestPath).memcardSlots(), "memcard_slots", 1, 64, issues);
|
||||
return slots == null ? null : slots.intValue();
|
||||
}
|
||||
|
||||
private static OptionalInt parseStdlib(
|
||||
|
||||
+2
-1
@@ -21,7 +21,8 @@ public record HostAdmissionContext(
|
||||
"fs",
|
||||
"log",
|
||||
"asset",
|
||||
"bank"));
|
||||
"bank",
|
||||
"memcard"));
|
||||
|
||||
public HostAdmissionContext {
|
||||
knownCapabilities = knownCapabilities == null || knownCapabilities.isEmpty()
|
||||
|
||||
+6
-2
@@ -250,7 +250,8 @@ public class IRBackend implements IRBackendReader {
|
||||
declaration.fileId(),
|
||||
remapLifecycleCallable(declaration.fileInitFragment(), moduleRemap, callableRemap),
|
||||
remapLifecycleCallable(declaration.projectInit(), moduleRemap, callableRemap),
|
||||
remapLifecycleCallable(declaration.frameRoot(), moduleRemap, callableRemap));
|
||||
remapLifecycleCallable(declaration.frameRoot(), moduleRemap, callableRemap),
|
||||
declaration.bootstrapCalls());
|
||||
}
|
||||
|
||||
private IRLifecycleCallableReference remapLifecycleCallable(
|
||||
@@ -349,6 +350,7 @@ public class IRBackend implements IRBackendReader {
|
||||
final var modules = new ArrayList<IRLifecycleModuleDeclaration>();
|
||||
IRLifecycleCallableReference projectInit = null;
|
||||
IRLifecycleCallableReference frameRoot = null;
|
||||
final var bootstrapCalls = new java.util.LinkedHashSet<IRBackendExecutableFunction.HostCallMetadata>();
|
||||
for (final var moduleId : lifecycleModuleOrder) {
|
||||
final var fragments = new ArrayList<IRLifecycleCallableReference>();
|
||||
var hasLifecycleContribution = false;
|
||||
@@ -357,6 +359,7 @@ public class IRBackend implements IRBackendReader {
|
||||
continue;
|
||||
}
|
||||
hasLifecycleContribution = true;
|
||||
bootstrapCalls.addAll(lifecycleFile.bootstrapCalls().asList());
|
||||
if (lifecycleFile.fileInitFragment() != null) {
|
||||
fragments.add(lifecycleFile.fileInitFragment());
|
||||
}
|
||||
@@ -371,7 +374,8 @@ public class IRBackend implements IRBackendReader {
|
||||
modules.add(new IRLifecycleModuleDeclaration(moduleId, ReadOnlyList.wrap(fragments)));
|
||||
}
|
||||
}
|
||||
return new IRLifecycleDeclaration(ReadOnlyList.wrap(modules), projectInit, frameRoot);
|
||||
return new IRLifecycleDeclaration(ReadOnlyList.wrap(modules), projectInit, frameRoot,
|
||||
ReadOnlyList.wrap(new ArrayList<>(bootstrapCalls)));
|
||||
}
|
||||
|
||||
private boolean sameModuleId(final ModuleId left, final ModuleId right) {
|
||||
|
||||
+7
-1
@@ -5,8 +5,14 @@ import p.studio.utilities.structures.ReadOnlyList;
|
||||
public record IRLifecycleDeclaration(
|
||||
ReadOnlyList<IRLifecycleModuleDeclaration> modules,
|
||||
IRLifecycleCallableReference projectInit,
|
||||
IRLifecycleCallableReference frameRoot) {
|
||||
IRLifecycleCallableReference frameRoot,
|
||||
ReadOnlyList<IRBackendExecutableFunction.HostCallMetadata> bootstrapCalls) {
|
||||
public IRLifecycleDeclaration(ReadOnlyList<IRLifecycleModuleDeclaration> modules,
|
||||
IRLifecycleCallableReference projectInit, IRLifecycleCallableReference frameRoot) {
|
||||
this(modules, projectInit, frameRoot, ReadOnlyList.empty());
|
||||
}
|
||||
public IRLifecycleDeclaration {
|
||||
modules = modules == null ? ReadOnlyList.empty() : modules;
|
||||
bootstrapCalls = bootstrapCalls == null ? ReadOnlyList.empty() : bootstrapCalls;
|
||||
}
|
||||
}
|
||||
|
||||
+10
-2
@@ -10,13 +10,21 @@ public record IRLifecycleFileDeclaration(
|
||||
FileId fileId,
|
||||
IRLifecycleCallableReference fileInitFragment,
|
||||
IRLifecycleCallableReference projectInit,
|
||||
IRLifecycleCallableReference frameRoot) {
|
||||
IRLifecycleCallableReference frameRoot,
|
||||
p.studio.utilities.structures.ReadOnlyList<IRBackendExecutableFunction.HostCallMetadata> bootstrapCalls) {
|
||||
public IRLifecycleFileDeclaration(ModuleId moduleId, FileId fileId,
|
||||
IRLifecycleCallableReference fileInitFragment, IRLifecycleCallableReference projectInit,
|
||||
IRLifecycleCallableReference frameRoot) {
|
||||
this(moduleId, fileId, fileInitFragment, projectInit, frameRoot,
|
||||
p.studio.utilities.structures.ReadOnlyList.empty());
|
||||
}
|
||||
public IRLifecycleFileDeclaration {
|
||||
moduleId = Objects.requireNonNull(moduleId, "moduleId");
|
||||
fileId = Objects.requireNonNull(fileId, "fileId");
|
||||
bootstrapCalls = bootstrapCalls == null ? p.studio.utilities.structures.ReadOnlyList.empty() : bootstrapCalls;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return fileInitFragment == null && projectInit == null && frameRoot == null;
|
||||
return fileInitFragment == null && projectInit == null && frameRoot == null && bootstrapCalls.isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user