feat(pbs): add explicit guest lifecycle hooks
This commit is contained in:
+1
-1
@@ -353,7 +353,7 @@ public final class PBSSemanticTokenProvider implements FrontendSemanticTokenProv
|
||||
final ReadOnlyList<PbsToken> tokens,
|
||||
final int index,
|
||||
final PbsToken token) {
|
||||
if (!"Init".equals(token.lexeme()) && !"Frame".equals(token.lexeme())) {
|
||||
if (PbsAst.LifecycleMarker.forAttribute(token.lexeme()) == PbsAst.LifecycleMarker.NONE) {
|
||||
return false;
|
||||
}
|
||||
if (index == 0 || index + 1 >= tokens.size()) {
|
||||
|
||||
+18
-3
@@ -133,9 +133,24 @@ public final class PbsAst {
|
||||
}
|
||||
|
||||
public enum LifecycleMarker {
|
||||
NONE,
|
||||
INIT,
|
||||
FRAME
|
||||
NONE(""),
|
||||
INIT("Init"),
|
||||
FRAME("Frame"),
|
||||
BEFORE_PAUSE("BeforePause"),
|
||||
BEFORE_RESUME("BeforeResume");
|
||||
|
||||
private final String attributeName;
|
||||
|
||||
LifecycleMarker(String attributeName) { this.attributeName = attributeName; }
|
||||
|
||||
public String attributeName() { return attributeName; }
|
||||
|
||||
public static LifecycleMarker forAttribute(String name) {
|
||||
for (var marker : values()) {
|
||||
if (marker != NONE && marker.attributeName.equals(name)) return marker;
|
||||
}
|
||||
return NONE;
|
||||
}
|
||||
}
|
||||
|
||||
public record FunctionDecl(
|
||||
|
||||
+5
-1
@@ -231,7 +231,11 @@ final class PbsRuntimeTypes {
|
||||
var returns=f.returnKind()==PbsAst.ReturnKind.PLAIN ? results(f.returnType()) : List.<IRRegistry.TypeRef>of();
|
||||
var captures = capturesByFunction.getOrDefault(f.name(), List.of()).stream().flatMap(c -> results(c.typeRef()).stream()).toList();
|
||||
return new IRRegistry.FunctionMetadata(new IRRegistry.Signature(ReadOnlyList.wrap(params),ReadOnlyList.wrap(returns)),
|
||||
ReadOnlyList.wrap(captures), IRRegistry.Role.NONE);
|
||||
ReadOnlyList.wrap(captures), switch (f.lifecycleMarker()) {
|
||||
case BEFORE_PAUSE -> IRRegistry.Role.BEFORE_PAUSE;
|
||||
case BEFORE_RESUME -> IRRegistry.Role.BEFORE_RESUME;
|
||||
default -> IRRegistry.Role.NONE;
|
||||
});
|
||||
}
|
||||
IRRegistry registry() { return new IRRegistry(ReadOnlyList.wrap(new ArrayList<>(used.values())),ReadOnlyList.wrap(runtimeImplementations)); }
|
||||
Integer enumValue(String owner,String label) {
|
||||
|
||||
+17
-9
@@ -170,7 +170,7 @@ final class PbsDeclarationParser {
|
||||
PbsAst.FunctionDecl parseFunction(
|
||||
final PbsToken fnToken,
|
||||
final ReadOnlyList<PbsAst.Attribute> pendingAttributes) {
|
||||
return parseFunctionLike(fnToken, pendingAttributes);
|
||||
return parseFunctionLike(fnToken, pendingAttributes, true);
|
||||
}
|
||||
|
||||
PbsAst.ImplementsDecl parseImplementsDeclaration(final PbsToken implementsToken) {
|
||||
@@ -570,7 +570,18 @@ final class PbsDeclarationParser {
|
||||
private PbsAst.FunctionDecl parseFunctionLike(
|
||||
final PbsToken fnToken,
|
||||
final ReadOnlyList<PbsAst.Attribute> pendingAttributes) {
|
||||
final var lifecycleMarker = validateAndResolveLifecycleMarker(pendingAttributes);
|
||||
return parseFunctionLike(fnToken, pendingAttributes, false);
|
||||
}
|
||||
|
||||
private PbsAst.FunctionDecl parseFunctionLike(
|
||||
final PbsToken fnToken,
|
||||
final ReadOnlyList<PbsAst.Attribute> pendingAttributes,
|
||||
final boolean topLevel) {
|
||||
var lifecycleMarker = validateAndResolveLifecycleMarker(pendingAttributes);
|
||||
if (!topLevel && lifecycleMarker != PbsAst.LifecycleMarker.NONE) {
|
||||
reportAttributesNotAllowed(pendingAttributes, "Lifecycle markers are valid only on top-level userland functions");
|
||||
lifecycleMarker = PbsAst.LifecycleMarker.NONE;
|
||||
}
|
||||
final var name = consumeCallableName();
|
||||
final var typeParameters = typeParser.parseTypeParameters();
|
||||
consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after function name");
|
||||
@@ -731,12 +742,9 @@ final class PbsDeclarationParser {
|
||||
reportAttributesNotAllowed(attributes, "Only [Doc] is allowed before interface executable methods");
|
||||
return PbsAst.LifecycleMarker.NONE;
|
||||
}
|
||||
if ("Init".equals(attribute.name())) {
|
||||
nextMarker = PbsAst.LifecycleMarker.INIT;
|
||||
} else if ("Frame".equals(attribute.name())) {
|
||||
nextMarker = PbsAst.LifecycleMarker.FRAME;
|
||||
} else {
|
||||
reportAttributesNotAllowed(attributes, "Only marker attributes [Init] and [Frame] are allowed before top-level functions");
|
||||
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");
|
||||
return PbsAst.LifecycleMarker.NONE;
|
||||
}
|
||||
|
||||
@@ -746,7 +754,7 @@ final class PbsDeclarationParser {
|
||||
}
|
||||
|
||||
if (marker != PbsAst.LifecycleMarker.NONE && marker != nextMarker) {
|
||||
reportAttributesNotAllowed(attributes, "Top-level functions cannot combine [Init] and [Frame]");
|
||||
reportAttributesNotAllowed(attributes, "Top-level functions cannot combine lifecycle markers");
|
||||
return PbsAst.LifecycleMarker.NONE;
|
||||
}
|
||||
marker = nextMarker;
|
||||
|
||||
+1
-1
@@ -969,7 +969,7 @@ public final class PbsDeclarationSemanticsValidator {
|
||||
}
|
||||
|
||||
private boolean isReservedAttribute(final String name) {
|
||||
return RESERVED_ATTRIBUTES.contains(name);
|
||||
return RESERVED_ATTRIBUTES.contains(name) || PbsAst.LifecycleMarker.forAttribute(name) != PbsAst.LifecycleMarker.NONE;
|
||||
}
|
||||
|
||||
private void validateReservedAttributeTarget(
|
||||
|
||||
+4
-3
@@ -45,7 +45,8 @@ public final class PbsLifecycleSemanticsValidator {
|
||||
private void validateLifecycleSignature(
|
||||
final PbsAst.FunctionDecl functionDecl,
|
||||
final p.studio.compiler.source.diagnostics.DiagnosticSink diagnostics) {
|
||||
final var valid = functionDecl.parameters().isEmpty()
|
||||
final var valid = functionDecl.typeParameters().isEmpty()
|
||||
&& functionDecl.parameters().isEmpty()
|
||||
&& functionDecl.returnKind() == PbsAst.ReturnKind.EXPLICIT_UNIT
|
||||
&& functionDecl.returnType() != null
|
||||
&& functionDecl.returnType().kind() == PbsAst.TypeRefKind.UNIT
|
||||
@@ -56,8 +57,8 @@ public final class PbsLifecycleSemanticsValidator {
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(
|
||||
diagnostics,
|
||||
PbsSemanticsErrors.E_SEM_INVALID_LIFECYCLE_SIGNATURE.name(),
|
||||
"Lifecycle functions marked with [%s] must have signature 'fn name() -> void'".formatted(
|
||||
functionDecl.lifecycleMarker() == PbsAst.LifecycleMarker.INIT ? "Init" : "Frame"),
|
||||
"Lifecycle functions marked with [%s] must be non-generic with signature 'fn name() -> void'".formatted(
|
||||
functionDecl.lifecycleMarker().attributeName()),
|
||||
functionDecl.span());
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -18,6 +18,7 @@ public enum PbsSemanticsErrors {
|
||||
E_SEM_INVALID_LIFECYCLE_SIGNATURE,
|
||||
E_SEM_DUPLICATE_FILE_INIT,
|
||||
E_SEM_DUPLICATE_PROJECT_FRAME,
|
||||
E_SEM_DUPLICATE_LIFECYCLE_ROLE,
|
||||
E_SEM_MISSING_PROJECT_FRAME,
|
||||
E_SEM_INIT_HOST_CALL_NOT_ALLOWED,
|
||||
E_SEM_MISSING_CONST_TYPE_ANNOTATION,
|
||||
|
||||
+19
@@ -13,6 +13,8 @@ final class PbsProjectLifecycleSemanticsValidator {
|
||||
final java.util.List<PbsParsedSourceFile> parsedSourceFiles,
|
||||
final DiagnosticSink diagnostics) {
|
||||
final var frames = new ArrayList<PbsAst.FunctionDecl>();
|
||||
final var hooks = new java.util.EnumMap<PbsAst.LifecycleMarker, PbsAst.FunctionDecl>(PbsAst.LifecycleMarker.class);
|
||||
final var declarations = new java.util.HashSet<String>();
|
||||
var sawExecutableSource = false;
|
||||
|
||||
for (final var parsedSource : parsedSourceFiles) {
|
||||
@@ -24,6 +26,23 @@ final class PbsProjectLifecycleSemanticsValidator {
|
||||
if (!(topDecl instanceof PbsAst.FunctionDecl functionDecl)) {
|
||||
continue;
|
||||
}
|
||||
final var span = functionDecl.span();
|
||||
if (!declarations.add(span.getFileId().getId() + ":" + span.getStart() + ":" + span.getEnd())) {
|
||||
continue;
|
||||
}
|
||||
final var marker = functionDecl.lifecycleMarker();
|
||||
if (marker == PbsAst.LifecycleMarker.BEFORE_PAUSE || marker == PbsAst.LifecycleMarker.BEFORE_RESUME) {
|
||||
final var previous = hooks.putIfAbsent(marker, functionDecl);
|
||||
if (previous != null) {
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(
|
||||
diagnostics,
|
||||
PbsSemanticsErrors.E_SEM_DUPLICATE_LIFECYCLE_ROLE.name(),
|
||||
"Only one [%s] target is allowed per image: '%s' conflicts with '%s' (file %d, span %d..%d)".formatted(
|
||||
marker.attributeName(), functionDecl.name(), previous.name(),
|
||||
previous.span().getFileId().getId(), previous.span().getStart(), previous.span().getEnd()),
|
||||
span);
|
||||
}
|
||||
}
|
||||
if (functionDecl.lifecycleMarker() == PbsAst.LifecycleMarker.FRAME) {
|
||||
frames.add(functionDecl);
|
||||
}
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
# Controlled pause and resume
|
||||
|
||||
`src/lifecycle.pbs` declares both optional hooks. Each marker selects one
|
||||
nongeneric top-level function with no parameters, results or captures. It can
|
||||
be in a different file from `[Frame]`. Names are arbitrary; globals are shared
|
||||
game state, not captures. Normal closures remain usable inside a hook.
|
||||
|
||||
Home's existing handoff completes before BeforePause, which returns before
|
||||
suspension. BeforeResume runs after reactivation and before the next gameplay
|
||||
instruction. Runtime preserves the continuation, globals and init guard;
|
||||
resume does not rerun Init. Each hook has bounded virtual fuel and cannot sync,
|
||||
including through its callees. A fatal failure blocks the session.
|
||||
|
||||
Calling `preparePause()` directly runs an ordinary function; it does not pause
|
||||
the game or acquire the OS controlled-call context. To share work, an ordinary
|
||||
helper can be called from gameplay and hooks. A marker does not grant service
|
||||
capabilities or perform automatic saving, flushing or disk waiting.
|
||||
|
||||
MemcardBoot and persistence have a separate contract. These two markers do not
|
||||
select MemcardBoot or define a termination hook.
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
// These functions are selected by attributes, independently of their names.
|
||||
// Globals belong to the game state; they are not function captures.
|
||||
declare global pauseCount: int = 0;
|
||||
declare global resumeCount: int = 0;
|
||||
|
||||
[BeforePause]
|
||||
fn preparePause() -> void {
|
||||
pauseCount += 1;
|
||||
}
|
||||
|
||||
[BeforeResume]
|
||||
fn prepareResume() -> void {
|
||||
resumeCount += 1;
|
||||
}
|
||||
|
||||
fn lifecycleExample() -> int {
|
||||
return pauseCount + resumeCount;
|
||||
}
|
||||
+1
@@ -8,3 +8,4 @@ pub fn setExample() -> int;
|
||||
pub fn hashingExample() -> int;
|
||||
pub fn mapsExample() -> int;
|
||||
pub fn stackQueueExample() -> int;
|
||||
pub fn lifecycleExample() -> int;
|
||||
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package p.studio.compiler.services;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.PBSSemanticTokenProvider;
|
||||
import p.studio.compiler.models.SourceKind;
|
||||
import p.studio.compiler.pbs.PbsFrontendCompiler;
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.pbs.lexer.PbsLexer;
|
||||
import p.studio.compiler.pbs.parser.PbsParser;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import p.studio.compiler.source.identifiers.ModuleId;
|
||||
import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsGuestLifecycleSemanticsTest {
|
||||
@Test void permitsGlobalsClosuresAndDocOnBothHooks() {
|
||||
var source = """
|
||||
declare global state: int = 0;
|
||||
[Doc(markdown = \"\"\"Pause preparation.\"\"\")]
|
||||
[BeforePause] fn arbitraryName() -> void {
|
||||
let delta = 2;
|
||||
let effect = fn [delta]() -> int { return delta; };
|
||||
state += effect();
|
||||
}
|
||||
[BeforeResume] fn anotherName() -> void { state += 3; }
|
||||
""";
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
|
||||
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getMessage()).toList().toString());
|
||||
var tokens = new PBSSemanticTokenProvider().tokenize(source);
|
||||
for (var name : List.of("BeforePause", "BeforeResume")) {
|
||||
assertTrue(tokens.stream().anyMatch(t -> t.startOffset() == source.indexOf(name) && t.semanticKey().equals("pbs-lifecycle")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void rejectsInvalidSourceSurfacesWithSourceLocations() {
|
||||
for (var marker : List.of("BeforePause", "BeforeResume")) {
|
||||
for (var source : List.of(
|
||||
"["+marker+"] fn bad(x: int) -> void {}",
|
||||
"["+marker+"] fn bad() -> int { return 1; }",
|
||||
"["+marker+"] fn bad<T>() -> void {}",
|
||||
"["+marker+"(value = 1)] fn bad() -> void {}",
|
||||
"["+marker+"][Init] fn bad() -> void {}",
|
||||
"["+marker+"][Frame] fn bad() -> void {}",
|
||||
"[BeforePause][BeforeResume] fn bad() -> void {}",
|
||||
"declare struct Box() { ["+marker+"] fn bad() -> void {} }",
|
||||
"declare service Box { ["+marker+"] fn bad() -> void {} }",
|
||||
"declare contract Box { ["+marker+"] fn bad() -> void; }",
|
||||
"["+marker+"] declare global bad: int = 0;")) {
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(7), source, diagnostics);
|
||||
assertTrue(diagnostics.hasErrors(), source);
|
||||
assertTrue(diagnostics.stream().anyMatch(d -> d.getSpan().getFileId().getId() == 7
|
||||
&& d.getSpan().getEnd() > d.getSpan().getStart()), source);
|
||||
}
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
var id = new FileId(8);
|
||||
PbsParser.parse(PbsLexer.lex("["+marker+"] fn bad() -> void {}", id, diagnostics), id, diagnostics,
|
||||
PbsParser.ParseMode.INTERFACE_MODULE);
|
||||
assertTrue(diagnostics.hasErrors());
|
||||
}
|
||||
}
|
||||
|
||||
private PbsParsedSourceFile file(int id, String source) {
|
||||
var file = new FileId(id);
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
var ast = PbsParser.parse(PbsLexer.lex(source, file, diagnostics), file, diagnostics);
|
||||
assertFalse(diagnostics.hasErrors());
|
||||
return new PbsParsedSourceFile(file, ast, new ModuleId(id), SourceKind.PROJECT);
|
||||
}
|
||||
|
||||
@Test void uniquenessIsPerImageAndRepeatedDeclarationsAreNotCountedTwice() {
|
||||
var frame = file(0, "[Frame] fn frame() -> void {}");
|
||||
for (var marker : List.of("BeforePause", "BeforeResume")) {
|
||||
var first = file(1, "["+marker+"] fn first() -> void {}");
|
||||
var second = file(2, "["+marker+"] fn second() -> void {}");
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
new PbsProjectLifecycleSemanticsValidator().validate(List.of(frame, first, first), diagnostics);
|
||||
assertFalse(diagnostics.hasErrors());
|
||||
new PbsProjectLifecycleSemanticsValidator().validate(List.of(frame, first, second), diagnostics);
|
||||
var duplicates = diagnostics.stream().filter(d -> d.getCode().equals("E_SEM_DUPLICATE_LIFECYCLE_ROLE")).toList();
|
||||
assertEquals(1, duplicates.size());
|
||||
assertEquals(2, duplicates.getFirst().getSpan().getFileId().getId());
|
||||
assertTrue(duplicates.getFirst().getMessage().contains("first"));
|
||||
assertTrue(duplicates.getFirst().getMessage().contains("second"));
|
||||
assertTrue(duplicates.getFirst().getMessage().contains(marker));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user