feat(pbs): add sprite animation and shared Studio authoring
Implement DEC-0084 with factory-only Sprite/Animator structs, complete result lowering, validated animation sidecars, generated PBS factories and JavaFX/MCP authoring through shared services. Qualify native dev/release with ordinary and optimized producers, zero-allocation playback, private-cycle reclamation, canonical Composer pixels, installed JARs and JavaFX lifecycle. Preserve the runtime checkout and existing host ABI.
This commit is contained in:
+10
-3
@@ -82,13 +82,20 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService
|
||||
if (text.isEmpty()) return Optional.empty();
|
||||
final boolean bundled = surface.sourceKindByFile().get(entry.getKey()) == SourceKind.SDK_INTERFACE;
|
||||
final Path owner = surface.ownerRootByFile().get(entry.getKey());
|
||||
final boolean external = bundled || owner == null || !owner.toAbsolutePath().normalize().equals(request.projectRoot().toAbsolutePath().normalize());
|
||||
final boolean generated = path.toAbsolutePath().normalize().startsWith(Path.of("/virtual/generated/animations"));
|
||||
final boolean external = generated || bundled || owner == null || !owner.toAbsolutePath().normalize().equals(request.projectRoot().toAbsolutePath().normalize());
|
||||
final var source = new FrontendSourceDocument(path, text.orElseThrow(),
|
||||
bundled ? "bundled" : external ? "dependency" : "project",
|
||||
generated ? "generated" : bundled ? "bundled" : external ? "dependency" : "project",
|
||||
handle.getRelativePath().toString(), "pbs", external,
|
||||
new FrontendEditorialContext(entry.getValue(),
|
||||
surface.supplementalTopDeclsByFile().getOrDefault(entry.getKey(), ReadOnlyList.empty()),
|
||||
context.semanticContext(), files, surface));
|
||||
context.semanticContext(), files, surface),
|
||||
generated && context.semanticContext() instanceof FESurfaceContext animationContext
|
||||
? animationContext.animations().stream().map(p.studio.compiler.services.PbsAnimationProjection::generate)
|
||||
.filter(g->g.path().equals(path)).flatMap(g->g.origins().stream()).toList() : List.of(),
|
||||
generated && context.semanticContext() instanceof FESurfaceContext animationContext
|
||||
? animationContext.animations().stream().map(p.studio.compiler.services.PbsAnimationProjection::generate)
|
||||
.filter(g->g.path().equals(path)).map(p.studio.compiler.services.PbsAnimationProjection.Generated::revision).findFirst().orElse("") : "");
|
||||
// A dependency may physically overlap a project source root. External
|
||||
// ownership wins even if another file-table entry treats it as local.
|
||||
if (external) return Optional.of(source);
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ public final class PbsCallableSlotCounter {
|
||||
final PbsAst.TypeRef returnType) {
|
||||
return switch (returnKind) {
|
||||
case INFERRED_UNIT, EXPLICIT_UNIT -> 0;
|
||||
case RESULT -> 1;
|
||||
case RESULT -> 1 + Math.max(0, typeSlots(returnType));
|
||||
case PLAIN -> Math.max(0, typeSlots(returnType));
|
||||
};
|
||||
}
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
|
||||
/** Trusted declaration identity survives aliases/reexports; same-module admission is explicit. */
|
||||
public final class PbsStdlibConstruction {
|
||||
private PbsStdlibConstruction() {}
|
||||
public static boolean factoryOnly(PbsAst.TopDecl declaration) {
|
||||
return declaration instanceof PbsAst.StructDecl s
|
||||
&& PbsSdkCollections.attribute(s.attributes(), "StdlibFactoryOnly") != null;
|
||||
}
|
||||
public static boolean allowed(PbsAst.TopDecl declaration, PbsAst.File file, ReadOnlyList<PbsAst.TopDecl> supplemental) {
|
||||
if (!factoryOnly(declaration)) return true;
|
||||
if (file.topDecls().stream().anyMatch(d -> d.span().equals(declaration.span()))) return true;
|
||||
return supplemental.stream().anyMatch(d -> d instanceof PbsAst.TypeBindingDecl binding
|
||||
&& binding.sameModule() && binding.span().getFileId().equals(file.span().getFileId()) && binding.declaration().span().equals(declaration.span()));
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -227,7 +227,9 @@ public final class PbsAst {
|
||||
}
|
||||
|
||||
/** Imported lexical binding; retains the original declaration and the importing source scope. */
|
||||
public record TypeBindingDecl(String name, TopDecl declaration, Span span) implements TopDecl {}
|
||||
public record TypeBindingDecl(String name, TopDecl declaration, Span span, boolean sameModule) implements TopDecl {
|
||||
public TypeBindingDecl(String name, TopDecl declaration, Span span) { this(name, declaration, span, false); }
|
||||
}
|
||||
|
||||
public record HostDecl(
|
||||
String name,
|
||||
|
||||
+1
-1
@@ -44,7 +44,7 @@ public class PbsAstRewriter {
|
||||
map(b.signatures(), this::signature), b.attributes(), b.span());
|
||||
case PbsAst.GlobalDecl g -> new PbsAst.GlobalDecl(g.name(), type(g.explicitType()), expression(g.initializer(), type(g.explicitType())), g.span());
|
||||
case PbsAst.ConstDecl c -> new PbsAst.ConstDecl(c.name(), type(c.explicitType()), expression(c.initializer(), type(c.explicitType())), c.attributes(), c.span());
|
||||
case PbsAst.TypeBindingDecl b -> new PbsAst.TypeBindingDecl(b.name(), declaration(b.declaration()), b.span());
|
||||
case PbsAst.TypeBindingDecl b -> new PbsAst.TypeBindingDecl(b.name(), declaration(b.declaration()), b.span(), b.sameModule());
|
||||
case PbsAst.EnumDecl e -> e;
|
||||
case PbsAst.ErrorDecl e -> e;
|
||||
case PbsAst.InvalidDecl i -> i;
|
||||
|
||||
+141
-17
@@ -49,6 +49,8 @@ final class PbsExecutableBodyLowerer {
|
||||
var separator=callableName.indexOf('.');
|
||||
if(separator>0 && metadataIndex.types().services.containsKey(callableName.substring(0,separator))) context.serviceOwner=callableName.substring(0,separator);
|
||||
context.returnType = functionDecl.returnType();
|
||||
context.returnKind = functionDecl.returnKind();
|
||||
context.resultErrorType = functionDecl.resultErrorType();
|
||||
int captureIndex = 0;
|
||||
for (var capture : metadataIndex.types().capturesByFunction.getOrDefault(functionDecl.name(), java.util.List.of())) {
|
||||
var type = capture.typeRef();
|
||||
@@ -91,7 +93,7 @@ final class PbsExecutableBodyLowerer {
|
||||
} else terminated = lowerBlock(functionDecl.body(), context);
|
||||
finalizeFunctionInstructions(functionDecl, context, terminated);
|
||||
|
||||
final var returnSlots = functionDecl.returnKind() == PbsAst.ReturnKind.PLAIN ? context.types().slots(functionDecl.returnType()) : 0;
|
||||
final var returnSlots = context.types().returnSlots(functionDecl.returnKind(), functionDecl.returnType());
|
||||
final int maxStackSlots;
|
||||
try {
|
||||
maxStackSlots = stackAnalyzer.analyzeMaxStackSlots(ReadOnlyList.wrap(context.instructions()), returnSlots);
|
||||
@@ -450,14 +452,10 @@ final class PbsExecutableBodyLowerer {
|
||||
case PbsAst.ElseExpr elseExpr -> lowerOptionalFallback(elseExpr, context);
|
||||
case PbsAst.IfExpr ifExpr -> lowerIfExpression(ifExpr, context);
|
||||
case PbsAst.SwitchExpr switchExpr -> lowerSwitch(switchExpr, context);
|
||||
case PbsAst.HandleExpr handleExpr -> lowerUnsupportedExpression(
|
||||
handleExpr.value(),
|
||||
"handle expression is not lowerable in executable lowering v1",
|
||||
handleExpr.span(),
|
||||
context);
|
||||
case PbsAst.HandleExpr handleExpr -> lowerHandle(handleExpr, context);
|
||||
case PbsAst.AsExpr asExpr -> lowerConversion(asExpr, context);
|
||||
case PbsAst.MemberExpr memberExpr -> lowerMemberExpression(memberExpr, context);
|
||||
case PbsAst.PropagateExpr propagateExpr -> lowerExpression(propagateExpr.expression(), context);
|
||||
case PbsAst.PropagateExpr propagateExpr -> lowerPropagate(propagateExpr, context);
|
||||
case PbsAst.GroupExpr groupExpr -> lowerExpression(groupExpr.expression(), context);
|
||||
case PbsAst.NewExpr newExpr -> {
|
||||
if (newExpr.typeName().equals("array")) {
|
||||
@@ -479,7 +477,12 @@ final class PbsExecutableBodyLowerer {
|
||||
lowerExpected(someExpr.value(), payload, context);
|
||||
wrapOptional(payload, someExpr.span(), context);
|
||||
}
|
||||
case PbsAst.OkExpr okExpr -> lowerExpression(okExpr.value(), context);
|
||||
case PbsAst.OkExpr okExpr -> {
|
||||
lowerExpected(okExpr.value(), context.returnType, context);
|
||||
int payload = save(context.types().slots(context.returnType), okExpr.span(), context);
|
||||
emitPushI32(0, okExpr.span(), context);
|
||||
emitLoadLocalSlots(payload, context.types().slots(context.returnType), okExpr.span(), context);
|
||||
}
|
||||
case PbsAst.TupleExpr tupleExpr -> {
|
||||
var expected = context.expectedType;
|
||||
for (int index=0; index<tupleExpr.items().size(); index++) {
|
||||
@@ -500,8 +503,7 @@ final class PbsExecutableBodyLowerer {
|
||||
else lowerServiceValue(context.serviceOwner,value.span(),context);
|
||||
}
|
||||
case PbsAst.NoneExpr value -> emitDefault(context.types().registryType(context.expectedType), 1, value.span(), context);
|
||||
case PbsAst.ErrExpr ignored -> {
|
||||
}
|
||||
case PbsAst.ErrExpr error -> emitResultError(error.errorPath(), error.span(), context);
|
||||
case PbsAst.UnitExpr ignored -> {
|
||||
}
|
||||
}
|
||||
@@ -663,7 +665,7 @@ final class PbsExecutableBodyLowerer {
|
||||
return;
|
||||
}
|
||||
if (receiverType != null && receiverType.kind() == PbsAst.TypeRefKind.NAMED_TUPLE) {
|
||||
lowerExpression(memberExpr.receiver(),context);
|
||||
lowerExpected(memberExpr.receiver(),receiverType,context);
|
||||
int slot=save(context.types().slots(receiverType),memberExpr.span(),context);
|
||||
int offset=0;
|
||||
for(var field:receiverType.fields()) {
|
||||
@@ -886,6 +888,8 @@ final class PbsExecutableBodyLowerer {
|
||||
if (expression == null) {
|
||||
return 0;
|
||||
}
|
||||
var resultSignature = resultSignature(expression, context);
|
||||
if (resultSignature != null) return context.types().returnSlots(resultSignature.returnKind(), resultSignature.returnType());
|
||||
var resolvedType = expressionType(expression, context);
|
||||
if (resolvedType != null) return context.types().slots(resolvedType);
|
||||
return switch (expression) {
|
||||
@@ -1171,6 +1175,8 @@ final class PbsExecutableBodyLowerer {
|
||||
|
||||
private PbsAst.TypeRef expressionType(PbsAst.Expression e, PbsExecutableLoweringContext c) {
|
||||
if (e == null) return null;
|
||||
if (e instanceof PbsAst.PropagateExpr p) return expressionType(p.expression(), c);
|
||||
if (e instanceof PbsAst.HandleExpr h) return expressionType(h.value(), c);
|
||||
if (e instanceof PbsAst.LambdaExpr lambda) return lambda.functionType();
|
||||
if (e instanceof PbsAst.ArrayLiteralExpr || e instanceof PbsAst.NoneExpr) return c.expectedType;
|
||||
if (e instanceof PbsAst.TupleExpr tuple) return PbsAst.TypeRef.namedTuple(ReadOnlyList.wrap(tuple.items().stream()
|
||||
@@ -1751,6 +1757,115 @@ final class PbsExecutableBodyLowerer {
|
||||
null, "", null, null, null, "", "", pops, pushes, span,
|
||||
new IRRegistryInstruction(kind,type,null,null,field)));
|
||||
}
|
||||
private PbsAst.FunctionSignature resultSignature(PbsAst.Expression expression, PbsExecutableLoweringContext c) {
|
||||
if (expression instanceof PbsAst.GroupExpr group) return resultSignature(group.expression(), c);
|
||||
if (expression instanceof PbsAst.ApplyExpr apply) return resultSignature(applyCall(apply), c);
|
||||
if (!(expression instanceof PbsAst.CallExpr call)) return null;
|
||||
PbsAst.FunctionSignature signature = null;
|
||||
var free = sourceFunction(call, c);
|
||||
if (free != null) signature = new PbsAst.FunctionSignature(free.name(), free.parameters(), free.returnKind(),
|
||||
free.returnType(), free.resultErrorType(), free.attributes(), free.span());
|
||||
if (call.callee() instanceof PbsAst.MemberExpr member) {
|
||||
var owner = PbsRuntimeTypes.unwrap(expressionType(member.receiver(), c));
|
||||
if (owner != null) {
|
||||
var contract = c.types().contract(owner);
|
||||
if (contract != null) signature = contract.signatures().stream().filter(m ->
|
||||
m.name().equals(member.memberName()) && parametersMatch(m.parameters(), call.arguments(), c))
|
||||
.findFirst().orElse(null);
|
||||
else signature = c.types().signatures.get(owner.name() + "." + member.memberName() + "#" + call.arguments().size());
|
||||
}
|
||||
}
|
||||
if (signature == null) signature = c.types().signatures.get(PbsRuntimeTypes.path(call.callee()) + "#" + call.arguments().size());
|
||||
return signature != null && signature.returnKind() == PbsAst.ReturnKind.RESULT ? signature : null;
|
||||
}
|
||||
|
||||
private void clearPendingStack(Span span, PbsExecutableLoweringContext c) {
|
||||
int pending = stackAnalyzer.pendingStackSlots(ReadOnlyList.wrap(c.instructions()));
|
||||
for (int i = 0; i < pending; i++)
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.POP, "", null, null, span));
|
||||
}
|
||||
|
||||
private void emitInactivePayload(PbsAst.TypeRef payload, Span span, PbsExecutableLoweringContext c) {
|
||||
for (var part : c.types().results(payload)) {
|
||||
var declaration = c.types().registry().types().stream().filter(d -> d.identity().equals(part)).findFirst().orElseThrow();
|
||||
if (declaration.body() instanceof IRRegistry.Builtin builtin) {
|
||||
switch (builtin.id()) {
|
||||
case 0x10 -> emitPushI32(0, span, c);
|
||||
case 0x11, 1 -> emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_I64, "0", span, c);
|
||||
case 0x12 -> emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_F64, "0.0", span, c);
|
||||
case 0x13 -> emitPushBool(false, span, c);
|
||||
case 2 -> { emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_F64, "0.0", span, c); emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_F64, "0.0", span, c); }
|
||||
case 3 -> { for (int i = 0; i < 3; i++) emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_I64, "0", span, c); }
|
||||
default -> emitNullGroup(registryWidth(part, c), span, c);
|
||||
}
|
||||
} else emitNullGroup(registryWidth(part, c), span, c);
|
||||
}
|
||||
}
|
||||
|
||||
/** Extra locals start Null in the existing VM; these reserved slots are never assigned. */
|
||||
private void emitNullGroup(int width, Span span, PbsExecutableLoweringContext c) {
|
||||
int slot = c.declareLocalSlots(c.nextLabel("inactive_null"), width);
|
||||
emitLoadLocalSlots(slot, width, span, c);
|
||||
}
|
||||
|
||||
private void emitResultError(PbsAst.ErrorPath path, Span span, PbsExecutableLoweringContext c) {
|
||||
emitPushI32(c.types().errorCode(path), span, c);
|
||||
emitInactivePayload(c.returnType, span, c);
|
||||
}
|
||||
|
||||
private void lowerPropagate(PbsAst.PropagateExpr expression, PbsExecutableLoweringContext c) {
|
||||
var signature = resultSignature(expression.expression(), c);
|
||||
if (signature == null) { reportUnsupportedLowering("Propagation requires an exact result signature", expression.span(), c); return; }
|
||||
lowerExpected(expression.expression(), signature.returnType(), c);
|
||||
int width = c.types().slots(signature.returnType());
|
||||
int group = save(1 + width, expression.span(), c);
|
||||
var success = c.nextLabel("result_success");
|
||||
emitGetLocal(group, expression.span(), c); emitPushI32(0, expression.span(), c);
|
||||
emitBinaryOperatorInstruction("==", expression.span(), c);
|
||||
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_TRUE, success, expression.span(), c);
|
||||
clearPendingStack(expression.span(), c);
|
||||
emitGetLocal(group, expression.span(), c); emitInactivePayload(c.returnType, expression.span(), c);
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.RET, "", null, null, expression.span()));
|
||||
emitLabel(success, expression.span(), c); emitLoadLocalSlots(group + 1, width, expression.span(), c);
|
||||
}
|
||||
|
||||
private void lowerHandle(PbsAst.HandleExpr expression, PbsExecutableLoweringContext c) {
|
||||
var signature = resultSignature(expression.value(), c);
|
||||
if (signature == null) { reportUnsupportedLowering("Handle requires an exact result signature", expression.span(), c); return; }
|
||||
lowerExpected(expression.value(), signature.returnType(), c);
|
||||
int width = c.types().slots(signature.returnType());
|
||||
int group = save(1 + width, expression.span(), c);
|
||||
var success = c.nextLabel("handle_success"); var end = c.nextLabel("handle_end");
|
||||
emitGetLocal(group, expression.span(), c); emitPushI32(0, expression.span(), c);
|
||||
emitBinaryOperatorInstruction("==", expression.span(), c);
|
||||
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_TRUE, success, expression.span(), c);
|
||||
for (var arm : expression.arms()) {
|
||||
var next = c.nextLabel("handle_next");
|
||||
if (arm.pattern() instanceof PbsAst.ErrorPathHandlePattern pattern) {
|
||||
emitGetLocal(group, arm.span(), c); emitPushI32(c.types().errorCode(pattern.path()), arm.span(), c);
|
||||
emitBinaryOperatorInstruction("==", arm.span(), c);
|
||||
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE, next, arm.span(), c);
|
||||
}
|
||||
var scope = c.snapshotScope();
|
||||
if (arm.block() != null) for (var statement : arm.block().statements()) lowerStatement(statement, c);
|
||||
var terminal = arm.block() == null ? null : arm.block().tailExpression();
|
||||
while (terminal instanceof PbsAst.GroupExpr g) terminal = g.expression();
|
||||
var error = arm.remapTarget() != null ? arm.remapTarget() : terminal instanceof PbsAst.ErrExpr e ? e.errorPath() : null;
|
||||
if (error != null) {
|
||||
clearPendingStack(arm.span(), c); emitResultError(error, arm.span(), c);
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.RET, "", null, null, arm.span()));
|
||||
} else if (terminal instanceof PbsAst.OkExpr ok) {
|
||||
lowerExpected(ok.value(), signature.returnType(), c);
|
||||
emitJump(IRBackendExecutableFunction.InstructionKind.JMP, end, arm.span(), c);
|
||||
}
|
||||
c.restoreScope(scope); emitLabel(next, arm.span(), c);
|
||||
}
|
||||
// Static semantics proves exhaustiveness. An invalid code cannot become a payload.
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.TRAP, "", null, null, expression.span()));
|
||||
emitLabel(success, expression.span(), c); emitLoadLocalSlots(group + 1, width, expression.span(), c);
|
||||
emitLabel(end, expression.span(), c);
|
||||
}
|
||||
|
||||
private void emitDefault(IRRegistry.TypeRef type, int width, Span span, PbsExecutableLoweringContext c) {
|
||||
var holder = c.types().holder(type);
|
||||
registry(STRUCT_NEW,holder,0,0,1,span,c);
|
||||
@@ -1899,7 +2014,11 @@ final class PbsExecutableBodyLowerer {
|
||||
return hasElseBranch(stmt)&&yes&&no;
|
||||
}
|
||||
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()));
|
||||
var declaration=c.types().structs.get(expr.typeName());
|
||||
if (p.studio.compiler.pbs.PbsStdlibConstruction.factoryOnly(declaration) && !c.types().allowedFactoryOrigins.contains(declaration.span())) {
|
||||
reportUnsupportedLowering("Stdlib construction requires its canonical declaring module", expr.span(), c); return;
|
||||
}
|
||||
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);
|
||||
@@ -1975,7 +2094,7 @@ final class PbsExecutableBodyLowerer {
|
||||
pops += c.types().slots(type);
|
||||
}
|
||||
emitStructuredFunction(name.name(),method.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),
|
||||
method.returnType(),pops,c.types().slots(method.returnType()),call.span(),c);
|
||||
method.returnType(),method.returnKind(),method.resultErrorType(),pops,c.types().returnSlots(method.returnKind(),method.returnType()),call.span(),c);
|
||||
return true;
|
||||
}
|
||||
if(!(call.callee() instanceof PbsAst.MemberExpr member))return false;
|
||||
@@ -1994,7 +2113,7 @@ final class PbsExecutableBodyLowerer {
|
||||
int pops=2;
|
||||
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);}
|
||||
emitLoadLocalSlots(receiverView, 2, member.receiver().span(), c);
|
||||
registry(CALL_TRAIT,c.types().registryType(owner),ordinal,pops,c.types().slots(method.returnType()),call.span(),c);return true;
|
||||
registry(CALL_TRAIT,c.types().registryType(owner),ordinal,pops,c.types().returnSlots(method.returnKind(),method.returnType()),call.span(),c);return true;
|
||||
}
|
||||
var service=c.types().services.get(owner.name());
|
||||
if(service!=null) {
|
||||
@@ -2010,7 +2129,7 @@ final class PbsExecutableBodyLowerer {
|
||||
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;
|
||||
emitStructuredFunction(owner.name()+"."+method.name(),method.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),method.returnKind(),method.resultErrorType(),pops,c.types().returnSlots(method.returnKind(),method.returnType()),call.span(),c);return true;
|
||||
}
|
||||
var struct=c.types().structs.get(owner.name());if(struct==null)return false;
|
||||
boolean listIndex=p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(struct) && java.util.Set.of("insert","clearAt","removeAt","resize","reserve").contains(member.memberName());
|
||||
@@ -2018,7 +2137,7 @@ final class PbsExecutableBodyLowerer {
|
||||
if(method==null)return false;
|
||||
lowerExpected(member.receiver(),owner,c);int pops=1;
|
||||
for(int i=0;i<call.arguments().size();i++){var type=PbsTypeSubstitution.replaceSelf(method.parameters().get(i).typeRef(),owner.name());if(listIndex&&i==0)lowerArrayIndex(call.arguments().get(i),c);else lowerExpected(call.arguments().get(i),type,c);pops+=c.types().slots(type);}
|
||||
emitStructuredFunction(owner.name()+"."+method.name(),receiverParameters(owner.name(),method.parameters()),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),pops,c.types().slots(method.returnType()),call.span(),c);return true;
|
||||
emitStructuredFunction(owner.name()+"."+method.name(),receiverParameters(owner.name(),method.parameters()),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),method.returnKind(),method.resultErrorType(),pops,c.types().returnSlots(method.returnKind(),method.returnType()),call.span(),c);return true;
|
||||
}
|
||||
private java.util.List<PbsAst.TypeRef> receiverParameters(String owner, ReadOnlyList<PbsAst.Parameter> parameters) {
|
||||
var types = new java.util.ArrayList<PbsAst.TypeRef>();
|
||||
@@ -2102,7 +2221,12 @@ final class PbsExecutableBodyLowerer {
|
||||
|
||||
private void emitStructuredFunction(String name, java.util.List<PbsAst.TypeRef> parameters, PbsAst.TypeRef returnType,
|
||||
int pops, int pushes, Span span, PbsExecutableLoweringContext c) {
|
||||
var callableId = c.exactLocalCallable(name, parameters, returnType);
|
||||
emitStructuredFunction(name, parameters, returnType, PbsAst.ReturnKind.PLAIN, null, pops, pushes, span, c);
|
||||
}
|
||||
|
||||
private void emitStructuredFunction(String name, java.util.List<PbsAst.TypeRef> parameters, PbsAst.TypeRef returnType,
|
||||
PbsAst.ReturnKind kind, PbsAst.TypeRef errorType, int pops, int pushes, Span span, PbsExecutableLoweringContext c) {
|
||||
var callableId = c.exactLocalCallable(name, parameters, returnType, kind, errorType);
|
||||
if (callableId == null) {
|
||||
reportUnsupportedLowering("Structured call requires exact overload: " + name, span, c);
|
||||
return;
|
||||
|
||||
+17
-2
@@ -27,6 +27,8 @@ final class PbsExecutableLoweringContext {
|
||||
p.studio.compiler.pbs.ast.PbsAst.TypeRef returnType;
|
||||
PbsExecutableCallableRegistry callableRegistry() { return callableRegistry; }
|
||||
PbsRuntimeTypes types() { return metadataIndex.types(); }
|
||||
p.studio.compiler.pbs.ast.PbsAst.ReturnKind returnKind;
|
||||
p.studio.compiler.pbs.ast.PbsAst.TypeRef resultErrorType;
|
||||
String serviceOwner;
|
||||
private int nextLabelId = 0;
|
||||
private int nextLocalSlot;
|
||||
@@ -97,10 +99,20 @@ final class PbsExecutableLoweringContext {
|
||||
p.studio.compiler.source.identifiers.CallableId exactLocalCallable(String name,
|
||||
java.util.List<p.studio.compiler.pbs.ast.PbsAst.TypeRef> parameterTypes,
|
||||
p.studio.compiler.pbs.ast.PbsAst.TypeRef returnType) {
|
||||
return exactLocalCallable(name, parameterTypes, returnType, p.studio.compiler.pbs.ast.PbsAst.ReturnKind.PLAIN, null);
|
||||
}
|
||||
|
||||
p.studio.compiler.source.identifiers.CallableId exactLocalCallable(String name,
|
||||
java.util.List<p.studio.compiler.pbs.ast.PbsAst.TypeRef> parameterTypes,
|
||||
p.studio.compiler.pbs.ast.PbsAst.TypeRef returnType,
|
||||
p.studio.compiler.pbs.ast.PbsAst.ReturnKind kind,
|
||||
p.studio.compiler.pbs.ast.PbsAst.TypeRef errorType) {
|
||||
for (var callable : callableRegistry.localCallables()) {
|
||||
var parameters = callable.functionDecl().parameters();
|
||||
if (!callable.callableName().equals(name) || parameters.size() != parameterTypes.size()) continue;
|
||||
boolean matches = true;
|
||||
boolean matches = (callable.functionDecl().returnKind() == p.studio.compiler.pbs.ast.PbsAst.ReturnKind.RESULT)
|
||||
== (kind == p.studio.compiler.pbs.ast.PbsAst.ReturnKind.RESULT)
|
||||
&& types().key(callable.functionDecl().resultErrorType()).equals(types().key(errorType));
|
||||
for (int i = 0; i < parameters.size(); i++)
|
||||
matches &= types().key(parameters.get(i).typeRef()).equals(types().key(parameterTypes.get(i)));
|
||||
matches &= types().shapeKey(callable.functionDecl().returnType()).equals(types().shapeKey(returnType));
|
||||
@@ -111,10 +123,13 @@ final class PbsExecutableLoweringContext {
|
||||
.collect(java.util.stream.Collectors.joining(",")) + ")->";
|
||||
var output = returnType == null || returnType.kind() == p.studio.compiler.pbs.ast.PbsAst.TypeRefKind.UNIT
|
||||
? "unit" : formatter.typeSurfaceKey(returnType);
|
||||
if (kind == p.studio.compiler.pbs.ast.PbsAst.ReturnKind.RESULT)
|
||||
output = "result<" + formatter.typeSurfaceKey(errorType) + ">" + formatter.typeSurfaceKey(returnType);
|
||||
final var expectedOutput = output;
|
||||
var importedIds = callableIdsByNameAndArity().getOrDefault(new PbsCallableResolutionKey(nameTable().register(name), parameterTypes.size()), java.util.List.of());
|
||||
var candidates = callableSignatureByCallableId().entrySet().stream().filter(entry ->
|
||||
importedIds.contains(entry.getKey()) && entry.getValue().arity() == parameterTypes.size()
|
||||
&& normalizeShape(entry.getValue().typeShape()).equals(normalizeShape(inputs + output))).toList();
|
||||
&& normalizeShape(entry.getValue().typeShape()).equals(normalizeShape(inputs + expectedOutput))).toList();
|
||||
if (candidates.size() == 1) return candidates.getFirst().getKey();
|
||||
return null;
|
||||
}
|
||||
|
||||
+5
-3
@@ -49,12 +49,12 @@ public final class PbsExecutableLoweringService {
|
||||
importedCallables, metadataIndex.types());
|
||||
for (var entry : callableRegistry.callableSignatureByCallableId().entrySet()) {
|
||||
var signature = metadataIndex.types().signatures.get(entry.getValue().callableName()+"#"+entry.getValue().arity());
|
||||
if (signature != null) callableRegistry.returnSlotsByCallableId().put(entry.getKey(), signature.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(signature.returnType()) : 0);
|
||||
if (signature != null) callableRegistry.returnSlotsByCallableId().put(entry.getKey(), metadataIndex.types().returnSlots(signature.returnKind(), signature.returnType()));
|
||||
}
|
||||
for (var callable : callableRegistry.localCallables()) {
|
||||
var f=callable.functionDecl();
|
||||
callableRegistry.returnSlotsByCallableId().put(callableRegistry.callableIdByDeclaration().get(callable),
|
||||
f.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(f.returnType()) : 0);
|
||||
metadataIndex.types().returnSlots(f.returnKind(), f.returnType()));
|
||||
metadataIndex.types().signatures.put(callable.callableName()+"#"+f.parameters().size(),
|
||||
new PbsAst.FunctionSignature(f.name(),f.parameters(),f.returnKind(),f.returnType(),f.resultErrorType(),f.attributes(),f.span()));
|
||||
}
|
||||
@@ -65,6 +65,8 @@ public final class PbsExecutableLoweringService {
|
||||
var candidates = callableRegistry.localCallables().stream().filter(callable ->
|
||||
callable.callableName().equals(metadataIndex.types().implementationCallableName(implementation, signature.name()))
|
||||
&& callable.functionDecl().parameters().size()==signature.parameters().size()+1
|
||||
&& callable.functionDecl().returnKind() == signature.returnKind()
|
||||
&& metadataIndex.types().key(callable.functionDecl().resultErrorType()).equals(metadataIndex.types().key(signature.resultErrorType()))
|
||||
&& metadataIndex.types().shapeKey(callable.functionDecl().returnType()).equals(metadataIndex.types().shapeKey(signature.returnType()))
|
||||
&& java.util.stream.IntStream.range(0, signature.parameters().size()).allMatch(i ->
|
||||
metadataIndex.types().key(callable.functionDecl().parameters().get(i+1).typeRef()).equals(
|
||||
@@ -151,7 +153,7 @@ public final class PbsExecutableLoweringService {
|
||||
safeToInt(functionDecl.span().getEnd()),
|
||||
functionDecl.parameters().stream().mapToInt(p -> metadataIndex.types().slots(p.typeRef())).sum(),
|
||||
loweredBody.localSlots(),
|
||||
functionDecl.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(functionDecl.returnType()) : 0,
|
||||
metadataIndex.types().returnSlots(functionDecl.returnKind(), functionDecl.returnType()),
|
||||
loweredBody.maxStackSlots(),
|
||||
loweredBody.instructions(),
|
||||
functionDecl.span(),
|
||||
|
||||
+19
-8
@@ -10,8 +10,17 @@ final class PbsExecutableStackAnalyzer {
|
||||
int analyzeMaxStackSlots(
|
||||
final ReadOnlyList<IRBackendExecutableFunction.Instruction> instructions,
|
||||
final int returnSlots) {
|
||||
return analyze(instructions, returnSlots, false)[0];
|
||||
}
|
||||
|
||||
int pendingStackSlots(ReadOnlyList<IRBackendExecutableFunction.Instruction> instructions) {
|
||||
return analyze(instructions, 0, true)[1];
|
||||
}
|
||||
|
||||
private int[] analyze(ReadOnlyList<IRBackendExecutableFunction.Instruction> instructions,
|
||||
int returnSlots, boolean prefix) {
|
||||
if (instructions.isEmpty()) {
|
||||
return Math.max(1, returnSlots);
|
||||
return new int[]{Math.max(1, returnSlots), 0};
|
||||
}
|
||||
|
||||
final var labelToIndex = new HashMap<String, Integer>();
|
||||
@@ -31,6 +40,7 @@ final class PbsExecutableStackAnalyzer {
|
||||
worklist.add(0);
|
||||
|
||||
var maxHeight = 0;
|
||||
var tailHeight = 0;
|
||||
while (!worklist.isEmpty()) {
|
||||
final var index = worklist.removeFirst();
|
||||
visited.add(index);
|
||||
@@ -43,7 +53,7 @@ final class PbsExecutableStackAnalyzer {
|
||||
case POP, SET_LOCAL, SET_GLOBAL -> {
|
||||
if (outHeight <= 0) {
|
||||
throw new ExecutableLoweringAnalysisException(
|
||||
"stack underflow at " + instruction.kind().name().toLowerCase() + ": need=1 have=" + outHeight);
|
||||
"stack underflow at " + index + " " + instruction.kind().name().toLowerCase() + " " + instruction.span().getStart() + ": need=1 have=" + outHeight);
|
||||
}
|
||||
outHeight -= 1;
|
||||
}
|
||||
@@ -57,7 +67,7 @@ final class PbsExecutableStackAnalyzer {
|
||||
case NOT, NEG -> {
|
||||
if (outHeight <= 0) {
|
||||
throw new ExecutableLoweringAnalysisException(
|
||||
"stack underflow at " + instruction.kind().name().toLowerCase() + ": need=1 have=" + outHeight);
|
||||
"stack underflow at " + index + " " + instruction.kind().name().toLowerCase() + " " + instruction.span().getStart() + ": need=1 have=" + outHeight);
|
||||
}
|
||||
}
|
||||
case REGISTRY, CALL_FUNC -> {
|
||||
@@ -110,17 +120,18 @@ final class PbsExecutableStackAnalyzer {
|
||||
|| instruction.kind() == IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE) {
|
||||
final var targetIndex = labelToIndex.get(instruction.targetLabel());
|
||||
if (targetIndex == null) {
|
||||
throw new ExecutableLoweringAnalysisException("missing jump target label: " + instruction.targetLabel());
|
||||
if (!prefix) throw new ExecutableLoweringAnalysisException("missing jump target label: " + instruction.targetLabel());
|
||||
}
|
||||
successors.add(targetIndex);
|
||||
if (targetIndex != null) successors.add(targetIndex);
|
||||
if (instruction.kind() == IRBackendExecutableFunction.InstructionKind.JMP) {
|
||||
mergeIncomingHeights(incomingHeightByInstruction, worklist, targetIndex, outHeight);
|
||||
if (targetIndex != null) mergeIncomingHeights(incomingHeightByInstruction, worklist, targetIndex, outHeight);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
final var nextIndex = index + 1;
|
||||
if (nextIndex >= instructions.size()) {
|
||||
if (prefix) { tailHeight = outHeight; continue; }
|
||||
throw new ExecutableLoweringAnalysisException("reachable path ends without terminal instruction");
|
||||
}
|
||||
successors.add(nextIndex);
|
||||
@@ -129,10 +140,10 @@ final class PbsExecutableStackAnalyzer {
|
||||
}
|
||||
}
|
||||
|
||||
if (!visited.contains(instructions.size() - 1)) {
|
||||
if (!prefix && !visited.contains(instructions.size() - 1)) {
|
||||
throw new ExecutableLoweringAnalysisException("entrypoint does not reach function tail");
|
||||
}
|
||||
return Math.max(1, Math.max(maxHeight, returnSlots));
|
||||
return new int[]{Math.max(1, Math.max(maxHeight, returnSlots)), tailHeight};
|
||||
}
|
||||
|
||||
private void mergeIncomingHeights(
|
||||
|
||||
+29
-2
@@ -14,12 +14,14 @@ final class PbsRuntimeTypes {
|
||||
final Map<String, String> builtinNames;
|
||||
final Map<String, String> aliases = new HashMap<>();
|
||||
final Map<String, ReadOnlyList<PbsAst.BuiltinFieldDecl>> fields = new HashMap<>();
|
||||
final Map<String, PbsAst.ErrorDecl> errors = new LinkedHashMap<>();
|
||||
final Map<String, PbsAst.EnumDecl> enums = new HashMap<>();
|
||||
final Map<String, PbsAst.FunctionSignature> signatures = new HashMap<>();
|
||||
final Map<String, List<PbsAst.FunctionDecl>> functions = new HashMap<>();
|
||||
final Map<String, PbsAst.TypeRef> values = new HashMap<>();
|
||||
final Map<String, PbsAst.ConstDecl> constants = new HashMap<>();
|
||||
private final Map<String, IRRegistry.TypeDeclaration> used = new TreeMap<>();
|
||||
final Set<Span> allowedFactoryOrigins = new HashSet<>();
|
||||
final Map<String, PbsAst.StructDecl> structs = new LinkedHashMap<>();
|
||||
final Map<String, PbsAst.ContractDecl> contracts = new LinkedHashMap<>();
|
||||
final p.studio.compiler.pbs.PbsContractTypes contractTypes;
|
||||
@@ -29,6 +31,8 @@ final class PbsRuntimeTypes {
|
||||
|
||||
PbsRuntimeTypes(PbsAst.File ast, ReadOnlyList<PbsAst.TopDecl> supplemental, Map<String,String> builtins) {
|
||||
builtinNames = builtins;
|
||||
ast.topDecls().forEach(d -> allowedFactoryOrigins.add(d.span()));
|
||||
supplemental.forEach(d -> { if (d instanceof PbsAst.TypeBindingDecl b && b.sameModule() && b.span().getFileId().equals(ast.span().getFileId())) allowedFactoryOrigins.add(b.declaration().span()); });
|
||||
contractTypes = new p.studio.compiler.pbs.PbsContractTypes(ast, supplemental, p.studio.compiler.source.diagnostics.DiagnosticSink.empty());
|
||||
for (var declaration : ast.topDecls()) if (declaration instanceof PbsAst.ImplementsDecl implementation)
|
||||
implementations.add(implementation);
|
||||
@@ -43,6 +47,7 @@ final class PbsRuntimeTypes {
|
||||
if (decl instanceof PbsAst.ContractDecl c) contracts.put(c.name(), c);
|
||||
if (decl instanceof PbsAst.ServiceDecl s) services.put(s.name(), s);
|
||||
if (decl instanceof PbsAst.EnumDecl e) enums.put(e.name(), e);
|
||||
if (decl instanceof PbsAst.ErrorDecl e) errors.put(e.name(), e);
|
||||
if (decl instanceof PbsAst.ConstDecl c) values.put(c.name(), c.explicitType());
|
||||
if (decl instanceof PbsAst.GlobalDecl g) values.put(g.name(), g.explicitType());
|
||||
if (decl instanceof PbsAst.FunctionDecl f) {
|
||||
@@ -119,6 +124,7 @@ final class PbsRuntimeTypes {
|
||||
if (origin != null) return nominal + ":" + origin.key();
|
||||
return t.arguments().isEmpty() ? nominal : nominal + ":" + contractTypes.key(t);
|
||||
}
|
||||
if (contractTypes.declaration(t) instanceof PbsAst.ErrorDecl error) return nominalKey("error", error.span());
|
||||
return canonical(t);
|
||||
}
|
||||
String shapeKey(PbsAst.TypeRef type) {
|
||||
@@ -206,7 +212,7 @@ final class PbsRuntimeTypes {
|
||||
for (var method : contract(t).signatures()) {
|
||||
var args = new ArrayList<IRRegistry.NamedType>();
|
||||
for(var arg : method.parameters()) for(var part : results(arg.typeRef())) args.add(new IRRegistry.NamedType(part,arg.name()));
|
||||
methods.add(new IRRegistry.Method(method.name(),new IRRegistry.Signature(ReadOnlyList.wrap(args),ReadOnlyList.wrap(results(method.returnType())))));
|
||||
methods.add(new IRRegistry.Method(method.name(),new IRRegistry.Signature(ReadOnlyList.wrap(args),ReadOnlyList.wrap(returnTypes(method.returnKind(), method.returnType())))));
|
||||
}
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,contractTypes.display(t),new IRRegistry.Trait(ReadOnlyList.wrap(methods))));
|
||||
}
|
||||
@@ -227,6 +233,27 @@ final class PbsRuntimeTypes {
|
||||
if(t.kind()==PbsAst.TypeRefKind.NAMED_TUPLE) return t.fields().stream().flatMap(f->results(f.typeRef()).stream()).toList();
|
||||
return List.of(registryType(t));
|
||||
}
|
||||
int returnSlots(PbsAst.ReturnKind kind, PbsAst.TypeRef payload) {
|
||||
return switch (kind) {
|
||||
case RESULT -> 1 + slots(payload);
|
||||
case PLAIN -> slots(payload);
|
||||
default -> 0;
|
||||
};
|
||||
}
|
||||
List<IRRegistry.TypeRef> returnTypes(PbsAst.ReturnKind kind, PbsAst.TypeRef payload) {
|
||||
if (kind == PbsAst.ReturnKind.PLAIN) return results(payload);
|
||||
if (kind != PbsAst.ReturnKind.RESULT) return List.of();
|
||||
var group = new ArrayList<IRRegistry.TypeRef>();
|
||||
group.add(builtin(0x10)); group.addAll(results(payload)); return List.copyOf(group);
|
||||
}
|
||||
int errorCode(PbsAst.ErrorPath path) {
|
||||
var resolved=contractTypes.declaration(PbsAst.TypeRef.simple(path.segments().getFirst(),path.span()));
|
||||
var declaration=resolved instanceof PbsAst.ErrorDecl error?error:errors.get(aliases.getOrDefault(path.segments().getFirst(),path.segments().getFirst()));
|
||||
if (declaration == null) throw new IllegalStateException("Missing canonical error declaration: " + path);
|
||||
int index = declaration.cases().asList().indexOf(path.segments().getLast());
|
||||
if (index < 0) throw new IllegalStateException("Missing error case: " + path);
|
||||
return index + 1;
|
||||
}
|
||||
IRRegistry.FunctionMetadata metadata(PbsAst.FunctionDecl f) {
|
||||
// Preserve the pre-existing unsupported executable boundary for types outside this port.
|
||||
// The common backend still rejects missing typed metadata; never infer a carrier by width.
|
||||
@@ -235,7 +262,7 @@ final class PbsRuntimeTypes {
|
||||
private IRRegistry.FunctionMetadata supportedMetadata(PbsAst.FunctionDecl f) {
|
||||
var params=new ArrayList<IRRegistry.NamedType>();
|
||||
for(var p:f.parameters()) for(var type:results(p.typeRef())) params.add(new IRRegistry.NamedType(type,p.name()));
|
||||
var returns=f.returnKind()==PbsAst.ReturnKind.PLAIN ? results(f.returnType()) : List.<IRRegistry.TypeRef>of();
|
||||
var returns=returnTypes(f.returnKind(), f.returnType());
|
||||
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), switch (f.lifecycleMarker()) {
|
||||
|
||||
+1
-1
@@ -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", "SdkMemcardBuffer").contains(attribute.name()) && "struct declarations".equals(targetSurface)) {
|
||||
java.util.Set.of("SdkList", "SdkLinked", "SdkSet", "SdkMap", "SdkStack", "SdkQueue", "SdkMemcardBuffer", "StdlibFactoryOnly").contains(attribute.name()) && "struct declarations".equals(targetSurface)) {
|
||||
continue;
|
||||
}
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(),
|
||||
|
||||
+1
@@ -1483,6 +1483,7 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
|
||||
private List<PbsEditorialSignature> constructorSignaturesForTopDecl(final PbsAst.TopDecl topDecl) {
|
||||
if (!p.studio.compiler.pbs.PbsStdlibConstruction.allowed(topDecl, ast, editorialSupplementalTopDecls)) return List.of();
|
||||
if (topDecl instanceof PbsAst.StructDecl structDecl) {
|
||||
if (structDecl.ctors().isEmpty()) {
|
||||
return List.of(new PbsEditorialSignature(structDecl.name(), structDecl.name() + "()", List.of(), "unit"));
|
||||
|
||||
+4
@@ -217,6 +217,7 @@ final class PbsFlowSemanticSupport {
|
||||
return declaration instanceof PbsAst.StructDecl owner && owner.methods().stream()
|
||||
.anyMatch(m -> m.name().equals(member) && p.studio.compiler.pbs.PbsSdkCollections.attribute(m.attributes(), "SdkPrivate") != null);
|
||||
}
|
||||
final Set<p.studio.compiler.source.Span> allowedFactoryOrigins = new HashSet<>();
|
||||
final Map<String, List<CallableSymbol>> topLevelCallables = new HashMap<>();
|
||||
final Map<String, StructInfo> structs = new HashMap<>();
|
||||
final Map<String, ServiceInfo> services = new HashMap<>();
|
||||
@@ -248,6 +249,9 @@ final class PbsFlowSemanticSupport {
|
||||
final var model = new Model();
|
||||
model.contractTypes = new p.studio.compiler.pbs.PbsContractTypes(ast, supplementalTopDecls, diagnostics);
|
||||
model.contractTypes.validate(ast);
|
||||
for (var declaration : ast.topDecls()) model.allowedFactoryOrigins.add(declaration.span());
|
||||
for (var declaration : supplementalTopDecls) if (declaration instanceof PbsAst.TypeBindingDecl binding && binding.sameModule() && binding.span().getFileId().equals(ast.span().getFileId()))
|
||||
model.allowedFactoryOrigins.add(binding.declaration().span());
|
||||
for (final var topDecl : ast.topDecls()) {
|
||||
model.registerKnownTopDecl(topDecl);
|
||||
}
|
||||
|
||||
+7
@@ -230,6 +230,13 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
return ExprResult.type(TypeView.optional(payloadExpected == null ? payload : payloadExpected));
|
||||
}
|
||||
if (expression instanceof PbsAst.NewExpr newExpr) {
|
||||
var declaredType = model.contractTypes.declaration(PbsAst.TypeRef.simple(newExpr.typeName(), newExpr.span()));
|
||||
if (p.studio.compiler.pbs.PbsStdlibConstruction.factoryOnly(declaredType)
|
||||
&& !model.allowedFactoryOrigins.contains(declaredType.span())) {
|
||||
Diagnostics.error(diagnostics, "E_SEM_STDLIB_FACTORY_ONLY",
|
||||
"Construct this stdlib type through its public factory", newExpr.span());
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
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",
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package p.studio.compiler.services;
|
||||
|
||||
import p.animation.*;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
/** PBS-only deterministic projection; canonical persistence remains the JSON sidecar. */
|
||||
public final class PbsAnimationProjection {
|
||||
public static final String VERSION="1";
|
||||
public record Generated(String moduleName,Path path,String source,String barrel,String revision,List<FrontendSourceDocument.OriginSpan> origins) {
|
||||
public Generated { origins=List.copyOf(origins); }
|
||||
}
|
||||
public static Generated generate(AnimationSource source) {
|
||||
var text=new StringBuilder("import { Animator, AnimationError, PlaybackMode, animator_builder } from @core:animation;\n\n");
|
||||
var barrel=new StringBuilder();var origins=new ArrayList<FrontendSourceDocument.OriginSpan>();
|
||||
var binding=new HashMap<String,AnimationDocument.Binding>();source.document().bindings().forEach(b->binding.put(b.artifactId(),b));
|
||||
var definitions=new ArrayList<>(source.document().animators());definitions.sort(Comparator.comparing(AnimationDocument.Animator::id));
|
||||
for(var animator:definitions) {
|
||||
int index=source.document().animators().indexOf(animator);String pointer="/animators/"+index;
|
||||
String name="create_"+animator.id();String signature=name+"(bank_id: int) -> result<AnimationError> Animator";
|
||||
barrel.append("pub fn ").append(signature).append(";\n");
|
||||
int begin=bytes(text);text.append("fn ").append(signature).append(" {\n");
|
||||
origins.add(new FrontendSourceDocument.OriginSpan(begin,bytes(text),source.definitionPath(),pointer+"/id",source.bank().assetUuid().toString()));
|
||||
line(text,origins,source.definitionPath(),pointer+"/initial_clip"," let builder = animator_builder(bank_id, "+quote(animator.initialClip())+")!;\n");
|
||||
for(int c=0;c<animator.clips().size();c++) {
|
||||
var clip=animator.clips().get(c);String cp=pointer+"/clips/"+c;
|
||||
line(text,origins,source.definitionPath(),cp," builder.begin_clip("+quote(clip.name())+", PlaybackMode."+(clip.mode().equals("once")?"Once":"Loop")+")!;\n");
|
||||
for(int f=0;f<clip.frames().size();f++){
|
||||
var frame=clip.frames().get(f);var glyph=binding.get(frame.artifactId());
|
||||
if(glyph==null)throw new IllegalArgumentException("Unvalidated animation frame");
|
||||
line(text,origins,source.definitionPath(),cp+"/frames/"+f," builder.add_frame("+glyph.glyphId()+", "+frame.durationTicks()+")!;\n");
|
||||
}
|
||||
text.append(" builder.end_clip()!;\n");
|
||||
}
|
||||
text.append(" return ok(builder.build()!);\n}\n\n");
|
||||
}
|
||||
String revision=AnimationRevision.of(VERSION+"\n"+source.documentRevision()+"\n"+source.bank().revision()+"\n"+text);
|
||||
String module="b_"+source.bank().assetUuid().toString().replace("-","");
|
||||
var path=Path.of("/virtual/generated/animations").resolve(source.projectName()).resolve(module).resolve(revision).resolve("main.pbs");
|
||||
return new Generated(module,path,text.toString(),barrel.toString(),revision,origins.stream().map(o->new FrontendSourceDocument.OriginSpan(o.startOffset(),o.endOffset(),o.definitionPath(),o.jsonPointer(),source.bank().assetUuid().toString())).toList());
|
||||
}
|
||||
private static int bytes(StringBuilder s){return s.toString().getBytes(StandardCharsets.UTF_8).length;}
|
||||
private static void line(StringBuilder out,List<FrontendSourceDocument.OriginSpan> spans,Path path,String pointer,String line){int start=bytes(out);out.append(line);spans.add(new FrontendSourceDocument.OriginSpan(start,bytes(out),path,pointer));}
|
||||
public static String quote(String value){
|
||||
var out=new StringBuilder("\"");
|
||||
for(int i=0;i<value.length();i++){char c=value.charAt(i);switch(c){
|
||||
case '\\'->out.append("\\\\");case '"'->out.append("\\\"");case '\n'->out.append("\\n");case '\r'->out.append("\\r");case '\t'->out.append("\\t");
|
||||
default->out.append(c);
|
||||
}}return out.append('"').toString();
|
||||
}
|
||||
}
|
||||
+32
-1
@@ -84,7 +84,7 @@ final class PbsImportedSemanticContextService {
|
||||
if (sibling.fileId().equals(parsedSource.fileId())) continue;
|
||||
for (var declaration : sibling.ast().topDecls()) {
|
||||
if (isTypeDecl(declaration) || declaration instanceof PbsAst.FunctionDecl f && !f.typeParameters().isEmpty()) appendSupplementalTopDecl(
|
||||
new PbsAst.TypeBindingDecl(topDeclName(declaration), declaration, parsedSource.ast().span()), supplementalTopDecls, supplementalKeys);
|
||||
new PbsAst.TypeBindingDecl(topDeclName(declaration), declaration, parsedSource.ast().span(), true), supplementalTopDecls, supplementalKeys);
|
||||
if (declaration instanceof PbsAst.ImplementsDecl) appendSupplementalTopDecl(declaration, supplementalTopDecls, supplementalKeys);
|
||||
}
|
||||
}
|
||||
@@ -228,6 +228,37 @@ final class PbsImportedSemanticContextService {
|
||||
ReadOnlyList.wrap(declarations), context.importedCallables(), context.importedGlobals(), context.importedReservedMetadata()));
|
||||
}
|
||||
} while (changed);
|
||||
// Factories expose usable concrete values even when callers do not import the
|
||||
// return type explicitly. Preserve the declaring module for all such methods.
|
||||
for(var source:parsedSourceFiles) {
|
||||
var context=contexts.get(source.fileId());
|
||||
var declarations=new ArrayList<>(context.supplementalTopDecls().asList());
|
||||
var declarationKeys=new HashSet<String>();declarations.forEach(d->declarationKeys.add(topDeclKey(d)));
|
||||
var callables=new ArrayList<>(context.importedCallables().asList());var callableKeys=new HashSet<String>();
|
||||
callables.forEach(c->callableKeys.add(c.moduleId().getIndex()+"#"+c.callableName()+"#"+c.arity()+"#"+c.shapeSurface()));
|
||||
for(int index=0;index<declarations.size();index++) {
|
||||
var bound=declarations.get(index);
|
||||
var declaration=bound instanceof PbsAst.TypeBindingDecl binding?binding.declaration():bound;
|
||||
if(!(declaration instanceof PbsAst.StructDecl struct)||struct.span().getFileId().equals(source.fileId()))continue;
|
||||
var definingModule=moduleBySource.get(struct.span().getFileId());if(definingModule==null)continue;
|
||||
String local=bound instanceof PbsAst.TypeBindingDecl binding?binding.name():struct.name();
|
||||
var methods=new ArrayList<>(struct.methods().asList());
|
||||
for(var ctor:struct.ctors())methods.add(new PbsAst.FunctionDecl("$ctor."+ctor.name(),ctor.parameters(),PbsAst.ReturnKind.EXPLICIT_UNIT,
|
||||
PbsAst.TypeRef.unit(ctor.span()),null,ReadOnlyList.empty(),PbsAst.LifecycleMarker.NONE,ctor.body(),ctor.span()));
|
||||
for(var method:methods) {
|
||||
var executable=p.studio.compiler.pbs.lowering.PbsExecutableCallableRegistryFactory.withReceiver(method,struct.name(),"this");
|
||||
appendImportedCallable(callables,callableKeys,new PbsFrontendCompiler.ImportedCallableSurface(definingModule,local+"."+method.name(),
|
||||
executable.parameters().size(),returnSlotsFor(executable),executable.returnKind(),executable.returnType(),
|
||||
frontendCompiler.callableShapeSurfaceOf(executable),struct.name()+"."+method.name()));
|
||||
}
|
||||
for(var provider:sourcesByModule.getOrDefault(definingModule,new ArrayList<>()))for(var member:provider.ast().topDecls())
|
||||
if(member instanceof PbsAst.ImplementsDecl implementation&&implementation.ownerName().equals(struct.name())) {
|
||||
appendSupplementalTopDecl(implementation,declarations,declarationKeys);
|
||||
appendTypeDependencyDecls(implementation,topDeclsByNameByModule.getOrDefault(definingModule,Map.of()),declarations,declarationKeys);
|
||||
}
|
||||
}
|
||||
contexts.put(source.fileId(),new PbsImportedSemanticContext(ReadOnlyList.wrap(declarations),ReadOnlyList.wrap(callables),context.importedGlobals(),context.importedReservedMetadata()));
|
||||
}
|
||||
return contexts;
|
||||
}
|
||||
|
||||
|
||||
+35
@@ -72,6 +72,7 @@ final class PbsModuleAssemblyService {
|
||||
|
||||
for (final var fileId : fileIds) {
|
||||
final var sourceHandle = ctx.fileTable.get(fileId);
|
||||
if(sourceHandle.getRelativePath().startsWith("@generated"))continue;
|
||||
sourceHandle.readUtf8().ifPresentOrElse(
|
||||
utf8Content -> consumeSourceFile(
|
||||
projectDescriptor,
|
||||
@@ -91,6 +92,9 @@ final class PbsModuleAssemblyService {
|
||||
}
|
||||
}
|
||||
|
||||
loadAnimationModules(ctx, writableFileTable, projectIdByName, modulesByCoordinates,
|
||||
parsedSourceFiles, moduleIdByFile, moduleTable, failedModuleIds, diagnostics);
|
||||
|
||||
loadReservedStdlibModules(
|
||||
modulesByCoordinates,
|
||||
parsedSourceFiles,
|
||||
@@ -199,6 +203,37 @@ final class PbsModuleAssemblyService {
|
||||
}
|
||||
}
|
||||
|
||||
private void loadAnimationModules(FrontendPhaseContext ctx, FileTable files,
|
||||
Map<String,ProjectId> owners, Map<PbsModuleVisibilityValidator.ModuleCoordinates,MutableModuleUnit> modules,
|
||||
ArrayList<PbsParsedSourceFile> parsed, Map<FileId,ModuleId> moduleByFile, ModuleTable table,
|
||||
Set<ModuleId> failed, DiagnosticSink diagnostics) {
|
||||
for(var entry:modules.entrySet()) {
|
||||
var path=entry.getKey().pathSegments();
|
||||
if(path.size()>=2&&path.get(0).equals("generated")&&path.get(1).equals("animations")) {
|
||||
var span=entry.getValue().sources.isEmpty()?Span.none():entry.getValue().sources.getFirst().ast().span();
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics,"E_LINK_GENERATED_COLLISION",
|
||||
"generated/animations is reserved for read-only animation projection",span);
|
||||
failed.add(moduleId(table,entry.getKey()));
|
||||
}
|
||||
}
|
||||
for(var source:ctx.feSurfaceContext().animations()) {
|
||||
var owner=owners.get(source.projectName());if(owner==null)continue;
|
||||
var generated=PbsAnimationProjection.generate(source);
|
||||
var coordinates=new PbsModuleVisibilityValidator.ModuleCoordinates(source.projectName(),ReadOnlyList.from("generated","animations",generated.moduleName()));
|
||||
if(modules.containsKey(coordinates))continue;
|
||||
var unit=new MutableModuleUnit();var module=moduleId(table,coordinates);
|
||||
byte[] utf8=generated.source().getBytes(StandardCharsets.UTF_8);
|
||||
var file=files.register(new SourceHandle(owner,Path.of("@generated/animations").resolve(generated.moduleName()).resolve("main.pbs"),generated.path(),utf8.length,0,ignored->()->utf8));
|
||||
var ast=parseSourceFile(file,generated.source(),diagnostics,SourceKind.PROJECT);
|
||||
unit.sources.add(new PbsModuleVisibilityValidator.SourceFile(file,ast));moduleByFile.put(file,module);
|
||||
parsed.add(new PbsParsedSourceFile(file,ast,module,SourceKind.PROJECT));
|
||||
byte[] barrel=generated.barrel().getBytes(StandardCharsets.UTF_8);
|
||||
var barrelId=files.register(new SourceHandle(owner,Path.of("@generated/animations").resolve(generated.moduleName()).resolve("mod.barrel"),generated.path().resolveSibling("mod.barrel"),barrel.length,0,ignored->()->barrel));
|
||||
unit.barrels.add(new PbsModuleVisibilityValidator.BarrelFile(barrelId,parseBarrelFile(barrelId,generated.barrel(),diagnostics)));
|
||||
moduleByFile.put(barrelId,module);modules.put(coordinates,unit);
|
||||
}
|
||||
}
|
||||
|
||||
private void loadReservedStdlibModules(
|
||||
final Map<PbsModuleVisibilityValidator.ModuleCoordinates, MutableModuleUnit> modulesByCoordinates,
|
||||
final ArrayList<PbsParsedSourceFile> parsedSourceFiles,
|
||||
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
import { SpriteView } from @core:sprite;
|
||||
|
||||
declare enum PlaybackMode(Once = 0, Loop = 1);
|
||||
declare enum PlaybackState(Stopped = 0, Playing = 1, Paused = 2, Finished = 3);
|
||||
declare error AnimationError {
|
||||
invalid_bank; invalid_name; duplicate_clip; clip_already_open; no_open_clip;
|
||||
empty_clip; unfinished_clip; empty_animator; initial_clip_missing; unknown_clip;
|
||||
invalid_glyph; invalid_duration; invalid_ticks; index_out_of_range;
|
||||
limit_exceeded; overflow;
|
||||
}
|
||||
|
||||
// Module-private nodes never appear in the public barrel or API. Published frame
|
||||
// rings are immutable. Direct links avoid array/optional wrappers while advancing.
|
||||
declare struct _AnimationFrame(pub glyph: int, pub duration: long, pub end: long, pub mut next: _AnimationFrame) {
|
||||
ctor make(glyph: int, duration: long, end: long) {
|
||||
this.glyph = glyph; this.duration = duration; this.end = end; this.next = this;
|
||||
}
|
||||
}
|
||||
declare struct _AnimationClip(pub name: str, pub mode: PlaybackMode,
|
||||
pub mut head: _AnimationFrame, pub mut tail: _AnimationFrame,
|
||||
pub mut count: long, pub mut total: long, pub mut next: _AnimationClip) {
|
||||
ctor make(name: str, mode: PlaybackMode) {
|
||||
let empty = new _AnimationFrame.make(0, 0, 0);
|
||||
this.name = name; this.mode = mode; this.head = empty; this.tail = empty;
|
||||
this.count = 0; this.total = 0; this.next = this;
|
||||
}
|
||||
}
|
||||
|
||||
[StdlibFactoryOnly]
|
||||
declare struct Animator(bank: int, first: _AnimationClip, selected: _AnimationClip,
|
||||
cursor: _AnimationFrame, phase: long, playback: PlaybackState, count: long) {
|
||||
fn sprite() -> (bank_id: int, glyph_id: int) { return (bank_id: this.bank, glyph_id: this.cursor.glyph); }
|
||||
fn state() -> PlaybackState { return this.playback; }
|
||||
fn active_clip() -> str { return this.selected.name; }
|
||||
fn clip_count() -> long { return this.count; }
|
||||
fn frame_count(name: str) -> result<AnimationError> long {
|
||||
if name == "" { return err(AnimationError.invalid_name); }
|
||||
let clip = this.first; let index: long = 0;
|
||||
while index < this.count {
|
||||
if clip.name == name { return ok(clip.count); }
|
||||
clip = clip.next; index = index + 1;
|
||||
}
|
||||
return err(AnimationError.unknown_clip);
|
||||
}
|
||||
fn frame_at(name: str, index: long) -> result<AnimationError> (glyph_id: int, duration_ticks: long) {
|
||||
if name == "" { return err(AnimationError.invalid_name); }
|
||||
let clip = this.first; let ordinal: long = 0;
|
||||
while ordinal < this.count {
|
||||
if clip.name == name {
|
||||
if index < (0 as long) || index >= clip.count { return err(AnimationError.index_out_of_range); }
|
||||
let frame = clip.head; let offset: long = 0;
|
||||
while offset < index { frame = frame.next; offset = offset + 1; }
|
||||
return ok((glyph_id: frame.glyph, duration_ticks: frame.duration));
|
||||
}
|
||||
clip = clip.next; ordinal = ordinal + 1;
|
||||
}
|
||||
return err(AnimationError.unknown_clip);
|
||||
}
|
||||
fn select(name: str) -> result<AnimationError> {
|
||||
if name == "" { return err(AnimationError.invalid_name); }
|
||||
let clip = this.first; let index: long = 0;
|
||||
while index < this.count {
|
||||
if clip.name == name {
|
||||
this.selected = clip; this.cursor = clip.head; this.phase = 0;
|
||||
this.playback = PlaybackState.Stopped; return ok(());
|
||||
}
|
||||
clip = clip.next; index = index + 1;
|
||||
}
|
||||
return err(AnimationError.unknown_clip);
|
||||
}
|
||||
fn play(name: str) -> result<AnimationError> { this.select(name)!; this.playback = PlaybackState.Playing; return ok(()); }
|
||||
fn pause() { if this.playback == PlaybackState.Playing { this.playback = PlaybackState.Paused; } }
|
||||
fn resume() { if this.playback == PlaybackState.Paused { this.playback = PlaybackState.Playing; } }
|
||||
fn stop() { this.cursor = this.selected.head; this.phase = 0; this.playback = PlaybackState.Stopped; }
|
||||
fn restart() { this.cursor = this.selected.head; this.phase = 0; this.playback = PlaybackState.Playing; }
|
||||
fn advance(ticks: int) -> result<AnimationError> {
|
||||
if ticks < 0 { return err(AnimationError.invalid_ticks); }
|
||||
if ticks == 0 || this.playback != PlaybackState.Playing { return ok(()); }
|
||||
let delta: long = ticks as long; let maximum: long = 9223372036854775807;
|
||||
if this.phase > maximum - delta { return err(AnimationError.overflow); }
|
||||
let nextPhase: long = this.phase + delta;
|
||||
let nextState = this.playback; let nextFrame = this.selected.head;
|
||||
if this.selected.mode == PlaybackMode.Loop { nextPhase = nextPhase % this.selected.total; }
|
||||
else {
|
||||
if nextPhase >= this.selected.total {
|
||||
nextPhase = this.selected.total; nextState = PlaybackState.Finished;
|
||||
nextFrame = this.selected.tail;
|
||||
}
|
||||
}
|
||||
if nextState != PlaybackState.Finished {
|
||||
while nextPhase >= nextFrame.end { nextFrame = nextFrame.next; }
|
||||
}
|
||||
this.phase = nextPhase; this.cursor = nextFrame; this.playback = nextState;
|
||||
return ok(());
|
||||
}
|
||||
}
|
||||
implements SpriteView for Animator using value {
|
||||
fn sprite() -> (bank_id: int, glyph_id: int) { return value.sprite(); }
|
||||
}
|
||||
|
||||
[StdlibFactoryOnly]
|
||||
declare struct AnimatorBuilder(bank: int, initial: str, first: _AnimationClip,
|
||||
last: _AnimationClip, draft: _AnimationClip, count: long, open: bool) {
|
||||
fn begin_clip(name: str, mode: PlaybackMode) -> result<AnimationError> {
|
||||
if this.open { return err(AnimationError.clip_already_open); }
|
||||
if name == "" { return err(AnimationError.invalid_name); }
|
||||
let clip = this.first; let index: long = 0;
|
||||
while index < this.count {
|
||||
if clip.name == name { return err(AnimationError.duplicate_clip); }
|
||||
clip = clip.next; index = index + 1;
|
||||
}
|
||||
let maximum: long = 4294967295;
|
||||
if this.count == maximum { return err(AnimationError.limit_exceeded); }
|
||||
let candidate = new _AnimationClip.make(name, mode);
|
||||
this.draft = candidate; this.open = true; return ok(());
|
||||
}
|
||||
fn add_frame(glyph_id: int, duration_ticks: long) -> result<AnimationError> {
|
||||
if !this.open { return err(AnimationError.no_open_clip); }
|
||||
if glyph_id < 0 || glyph_id > 65535 { return err(AnimationError.invalid_glyph); }
|
||||
if duration_ticks <= (0 as long) { return err(AnimationError.invalid_duration); }
|
||||
let countMaximum: long = 4294967295; let durationMaximum: long = 9223372036854775807;
|
||||
if this.draft.count == countMaximum { return err(AnimationError.limit_exceeded); }
|
||||
if this.draft.total > durationMaximum - duration_ticks { return err(AnimationError.overflow); }
|
||||
let total: long = this.draft.total + duration_ticks;
|
||||
let candidate = new _AnimationFrame.make(glyph_id, duration_ticks, total);
|
||||
if this.draft.count == (0 as long) { this.draft.head = candidate; }
|
||||
else { this.draft.tail.next = candidate; }
|
||||
candidate.next = this.draft.head;
|
||||
this.draft.tail = candidate; this.draft.count = this.draft.count + 1; this.draft.total = total;
|
||||
return ok(());
|
||||
}
|
||||
fn end_clip() -> result<AnimationError> {
|
||||
if !this.open { return err(AnimationError.no_open_clip); }
|
||||
if this.draft.count == (0 as long) { return err(AnimationError.empty_clip); }
|
||||
if this.count == (0 as long) { this.first = this.draft; }
|
||||
else { this.last.next = this.draft; }
|
||||
this.draft.next = this.first; this.last = this.draft;
|
||||
this.count = this.count + 1; this.open = false; return ok(());
|
||||
}
|
||||
fn discard_clip() -> result<AnimationError> {
|
||||
if !this.open { return err(AnimationError.no_open_clip); }
|
||||
this.open = false; return ok(());
|
||||
}
|
||||
fn remove_clip(name: str) -> result<AnimationError> {
|
||||
if this.open { return err(AnimationError.unfinished_clip); }
|
||||
if name == "" { return err(AnimationError.invalid_name); }
|
||||
let previous = this.last; let clip = this.first; let index: long = 0;
|
||||
while index < this.count {
|
||||
if clip.name == name {
|
||||
if this.count > (1 as long) {
|
||||
previous.next = clip.next;
|
||||
if index == (0 as long) { this.first = clip.next; }
|
||||
if index == this.count - (1 as long) { this.last = previous; }
|
||||
}
|
||||
this.count = this.count - 1; return ok(());
|
||||
}
|
||||
previous = clip; clip = clip.next; index = index + 1;
|
||||
}
|
||||
return err(AnimationError.unknown_clip);
|
||||
}
|
||||
fn build() -> result<AnimationError> Animator {
|
||||
if this.open { return err(AnimationError.unfinished_clip); }
|
||||
if this.count == (0 as long) { return err(AnimationError.empty_animator); }
|
||||
let source = this.first; let index: long = 0; let found = false;
|
||||
while index < this.count {
|
||||
if source.name == this.initial { found = true; }
|
||||
source = source.next; index = index + 1;
|
||||
}
|
||||
if !found { return err(AnimationError.initial_clip_missing); }
|
||||
// No domain errors remain. Copy every mutable node before publishing.
|
||||
let first = new _AnimationClip.make("", PlaybackMode.Once); let last = first; let selected = first;
|
||||
source = this.first; index = 0;
|
||||
while index < this.count {
|
||||
let copy = new _AnimationClip.make(source.name, source.mode);
|
||||
let frame = source.head; let ordinal: long = 0;
|
||||
while ordinal < source.count {
|
||||
let fresh = new _AnimationFrame.make(frame.glyph, frame.duration, frame.end);
|
||||
if ordinal == (0 as long) { copy.head = fresh; }
|
||||
else { copy.tail.next = fresh; }
|
||||
fresh.next = copy.head; copy.tail = fresh;
|
||||
frame = frame.next; ordinal = ordinal + 1;
|
||||
}
|
||||
copy.count = source.count; copy.total = source.total;
|
||||
if index == (0 as long) { first = copy; }
|
||||
else { last.next = copy; }
|
||||
copy.next = first; last = copy;
|
||||
if source.name == this.initial { selected = copy; }
|
||||
source = source.next; index = index + 1;
|
||||
}
|
||||
return ok(new Animator(this.bank, first, selected, selected.head, 0, PlaybackState.Stopped, this.count));
|
||||
}
|
||||
}
|
||||
|
||||
fn animator_builder(bank_id: int, initial_clip: str) -> result<AnimationError> AnimatorBuilder {
|
||||
if bank_id < 0 || bank_id > 255 { return err(AnimationError.invalid_bank); }
|
||||
if initial_clip == "" { return err(AnimationError.invalid_name); }
|
||||
let empty = new _AnimationClip.make("", PlaybackMode.Once);
|
||||
return ok(new AnimatorBuilder(bank_id, initial_clip, empty, empty, empty, 0, false));
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
pub struct Animator;
|
||||
pub struct AnimatorBuilder;
|
||||
pub enum PlaybackMode;
|
||||
pub enum PlaybackState;
|
||||
pub error AnimationError;
|
||||
pub fn animator_builder(bank_id: int, initial_clip: str) -> result<AnimationError> AnimatorBuilder;
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
[Doc(markdown = """
|
||||
A pure visual query. Bank slots are already loaded by the caller; position and
|
||||
palette belong to the emission. Querying never advances time or allocates a Sprite.
|
||||
""")]
|
||||
declare contract SpriteView { fn sprite() -> (bank_id: int, glyph_id: int); }
|
||||
|
||||
declare error SpriteError { invalid_bank; invalid_glyph; }
|
||||
|
||||
[StdlibFactoryOnly]
|
||||
declare struct Sprite(bank_id: int, glyph_id: int) {
|
||||
fn sprite() -> (bank_id: int, glyph_id: int) {
|
||||
return (bank_id: this.bank_id, glyph_id: this.glyph_id);
|
||||
}
|
||||
}
|
||||
|
||||
implements SpriteView for Sprite using value {
|
||||
fn sprite() -> (bank_id: int, glyph_id: int) { return value.sprite(); }
|
||||
}
|
||||
|
||||
fn make_sprite(bank_id: int, glyph_id: int) -> result<SpriteError> Sprite {
|
||||
if bank_id < 0 || bank_id > 255 { return err(SpriteError.invalid_bank); }
|
||||
if glyph_id < 0 || glyph_id > 65535 { return err(SpriteError.invalid_glyph); }
|
||||
return ok(new Sprite(bank_id, glyph_id));
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
pub struct Sprite;
|
||||
pub contract SpriteView;
|
||||
pub error SpriteError;
|
||||
pub fn make_sprite(bank_id: int, glyph_id: int) -> result<SpriteError> Sprite;
|
||||
+6
-6
@@ -19,14 +19,14 @@ declare host LowComposer {
|
||||
""")]
|
||||
[Host(module = "composer", name = "bind_scene", version = 1)]
|
||||
[Capability(name = "composer")]
|
||||
fn bind_scene(scene_bank_id: int) -> int;
|
||||
fn bind_scene(scene_bank_id: int) -> long;
|
||||
|
||||
[Doc(markdown = """
|
||||
Unbinds the active scene bank.
|
||||
""")]
|
||||
[Host(module = "composer", name = "unbind_scene", version = 1)]
|
||||
[Capability(name = "composer")]
|
||||
fn unbind_scene() -> int;
|
||||
fn unbind_scene() -> long;
|
||||
|
||||
[Doc(markdown = """
|
||||
Emits a sprite command into the active scene.
|
||||
@@ -53,7 +53,7 @@ declare host LowComposer {
|
||||
flip_x: bool,
|
||||
flip_y: bool,
|
||||
priority: int
|
||||
) -> int;
|
||||
) -> long;
|
||||
}
|
||||
|
||||
[Doc(markdown = """
|
||||
@@ -79,7 +79,7 @@ declare service Composer
|
||||
""")]
|
||||
fn bind_scene(scene_bank_id: int) -> int
|
||||
{
|
||||
return LowComposer.bind_scene(scene_bank_id);
|
||||
return LowComposer.bind_scene(scene_bank_id) as int;
|
||||
}
|
||||
|
||||
[Doc(markdown = """
|
||||
@@ -87,7 +87,7 @@ declare service Composer
|
||||
""")]
|
||||
fn unbind_scene() -> int
|
||||
{
|
||||
return LowComposer.unbind_scene();
|
||||
return LowComposer.unbind_scene() as int;
|
||||
}
|
||||
|
||||
[Doc(markdown = """
|
||||
@@ -115,6 +115,6 @@ declare service Composer
|
||||
priority: int
|
||||
) -> int
|
||||
{
|
||||
return LowComposer.emit_sprite(glyph_id, palette_id, x, y, layer, bank_id, flip_x, flip_y, priority);
|
||||
return LowComposer.emit_sprite(glyph_id, palette_id, x, y, layer, bank_id, flip_x, flip_y, priority) as int;
|
||||
}
|
||||
}
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
# Sprite and animation
|
||||
|
||||
`@core:sprite` and `@core:animation` are ordinary PBS stdlib modules. Use
|
||||
`make_sprite` or `animator_builder`; their private constructors are unavailable
|
||||
to games. `src/animation.pbs` demonstrates a static sprite, Loop and Once clips,
|
||||
external palette/position and two independent animators built from one builder.
|
||||
|
||||
Call `play` when the action changes and call `advance` to continue it. Repeating
|
||||
`play` or `select`, including the current name, resets the cursor and phase.
|
||||
Ticks are explicit game ticks; no timer runs inside Animator. Assignment aliases
|
||||
the same animator; another `build` creates independent clips and playback.
|
||||
A Once clip finishes after the last frame's full duration and retains its image.
|
||||
|
||||
For authored definitions, select a registered glyph bank in Studio Assets and
|
||||
create animators/clips/frames. Save `animations.studio.json` through the editor
|
||||
or task-authorized `studio_animation_update`. Glyph identity and fingerprints are
|
||||
validated against the current bank. Drift blocks preview/build until explicit
|
||||
prepare/apply rebind; review the proposed old/new bindings before applying it.
|
||||
Palette, position and runtime bank slot are never persisted in this definition.
|
||||
|
||||
For bank UUID `12345678-1234-1234-1234-123456789abc` and animator ID `hero`:
|
||||
|
||||
```pbs
|
||||
import { create_hero } from @app:generated/animations/b_12345678123412341234123456789abc;
|
||||
import { AnimationError } from @core:animation;
|
||||
fn render() -> result<AnimationError> {
|
||||
let value = create_hero(3)!;
|
||||
value.play("idle")!;
|
||||
value.advance(2)!;
|
||||
let image = value.sprite();
|
||||
// Supply image.bank_id/image.glyph_id to the existing nine-argument Composer API.
|
||||
return ok(());
|
||||
}
|
||||
```
|
||||
|
||||
The virtual module is reproducible and read-only. Its CodeLens opens the original
|
||||
JSON field in Studio. A changed definition invalidates older source revisions;
|
||||
navigate again to obtain the current definition. Existing projects without a
|
||||
sidecar publish no animation factories. Compilation with included definitions
|
||||
requires the configured Packer layout resolver.
|
||||
|
||||
Result calls preserve a typed status plus the complete payload. Use `!` to
|
||||
propagate the same declared error, or `handle` for a selected recovery/remapping.
|
||||
Neither catches VM traps. See PBS specification chapter 27 for errors, bounds,
|
||||
state transitions, ownership and the zero-allocation playback contract.
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { Sprite, SpriteError, make_sprite } from @core:sprite;
|
||||
import { Animator, AnimatorBuilder, AnimationError, PlaybackMode, animator_builder } from @core:animation;
|
||||
import { Composer } from @sdk:composer;
|
||||
|
||||
// Palette, position and bank lifetime belong to the caller.
|
||||
fn staticSprite(bank: int, palette: int, x: int, y: int) -> result<SpriteError> int {
|
||||
let value = make_sprite(bank, 7)!;
|
||||
let image = value.sprite();
|
||||
return ok(Composer.emit_sprite(image.glyph_id, palette, x, y, 0, image.bank_id, false, false, 0));
|
||||
}
|
||||
fn animationExample() -> result<AnimationError> int {
|
||||
let builder = animator_builder(3, "idle")!;
|
||||
builder.begin_clip("idle", PlaybackMode.Loop)!;
|
||||
builder.add_frame(7, 2)!; builder.add_frame(11, 3)!; builder.add_frame(4, 1)!;
|
||||
builder.end_clip()!;
|
||||
builder.begin_clip("jump", PlaybackMode.Once)!;
|
||||
builder.add_frame(11, 2)!; builder.add_frame(4, 3)!; builder.end_clip()!;
|
||||
let first = builder.build()!; let second = builder.build()!;
|
||||
first.play("idle")!; first.advance(2)!;
|
||||
// Independent playback: advancing first leaves second stopped on glyph 7.
|
||||
if first.sprite().glyph_id != 11 || second.sprite().glyph_id != 7 { let failure=1/0; }
|
||||
first.play("jump")!; first.advance(5)!;
|
||||
if first.sprite().glyph_id != 4 { let failure=1/0; }
|
||||
return ok(42);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ plugins {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":prometeu-animation"))
|
||||
api(project(":prometeu-infra"))
|
||||
implementation(project(":prometeu-compiler:prometeu-deps"))
|
||||
implementation(project(":prometeu-compiler:prometeu-compiler-core"))
|
||||
|
||||
+1
@@ -12,6 +12,7 @@ public class BuilderPipelineContext {
|
||||
public final BuilderPipelineConfig config;
|
||||
public final SourceProviderFactory sourceProviderFactory;
|
||||
|
||||
public p.animation.GlyphBankLayoutSource glyphBankLayoutSource;
|
||||
public Path rootProjectPathCanon;
|
||||
public ResolvedWorkspace resolvedWorkspace;
|
||||
|
||||
|
||||
+24
-3
@@ -18,13 +18,20 @@ public final class AssetSurfaceContextLoader {
|
||||
private static final Path REGISTRY_PATH = Path.of("assets", ".prometeu", "index.json");
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
private final p.animation.GlyphBankLayoutSource layouts;
|
||||
|
||||
public AssetSurfaceContextLoader() {
|
||||
this(new ObjectMapper());
|
||||
this(new ObjectMapper(), null);
|
||||
}
|
||||
|
||||
AssetSurfaceContextLoader(final ObjectMapper mapper) {
|
||||
this.mapper = Objects.requireNonNull(mapper, "mapper");
|
||||
this(mapper, null);
|
||||
}
|
||||
|
||||
public AssetSurfaceContextLoader(p.animation.GlyphBankLayoutSource layouts) { this(new ObjectMapper(), layouts); }
|
||||
|
||||
private AssetSurfaceContextLoader(ObjectMapper mapper, p.animation.GlyphBankLayoutSource layouts) {
|
||||
this.mapper = Objects.requireNonNull(mapper, "mapper"); this.layouts = layouts;
|
||||
}
|
||||
|
||||
public FESurfaceContext load(final Path projectRoot) {
|
||||
@@ -38,15 +45,29 @@ public final class AssetSurfaceContextLoader {
|
||||
try {
|
||||
final var document = mapper.readValue(registryPath.toFile(), RegistryDocument.class);
|
||||
final var addressables = new ArrayList<Addressable>();
|
||||
final var animations = new ArrayList<p.animation.AnimationSource>();
|
||||
if (document.assets != null) {
|
||||
for (final var asset : document.assets) {
|
||||
if (asset == null || !isIncludedInBuild(asset)) {
|
||||
continue;
|
||||
}
|
||||
addressables.add(new Addressable(toAddress(asset.root()), asset.assetId()));
|
||||
var bankRoot=projectRoot.toAbsolutePath().normalize().resolve("assets").resolve(normalizeRoot(asset.root()));
|
||||
var definition=bankRoot.resolve(p.animation.AnimationDocument.FILE_NAME);
|
||||
if (Files.isRegularFile(definition)) {
|
||||
if(layouts==null)throw new IllegalStateException("E_ANIMATION_LAYOUT_RESOLVER: included animation bank requires GlyphBankLayoutSource");
|
||||
String text=Files.readString(definition, java.nio.charset.StandardCharsets.UTF_8);
|
||||
var animation=new p.animation.AnimationCodec().decode(text);
|
||||
var uuid=java.util.UUID.fromString(animation.bankAssetUuid());
|
||||
var bank=layouts.resolve(projectRoot,uuid);
|
||||
if(!bank.assetRoot().toRealPath().equals(bankRoot.toRealPath()))throw new IllegalArgumentException("Animation UUID does not identify its containing registered bank");
|
||||
new p.animation.AnimationValidator().requireValid(animation,bank);
|
||||
String projectName=mapper.readTree(projectRoot.resolve("prometeu.json").toFile()).path("name").asText();
|
||||
animations.add(new p.animation.AnimationSource(projectName,projectRoot.toAbsolutePath().normalize(),definition,p.animation.AnimationRevision.of(text),animation,bank));
|
||||
}
|
||||
}
|
||||
}
|
||||
return new FESurfaceContext(ReadOnlyList.wrap(addressables));
|
||||
return new FESurfaceContext(ReadOnlyList.wrap(addressables),ReadOnlyList.wrap(animations));
|
||||
} catch (IOException exception) {
|
||||
throw new IllegalStateException("Unable to load asset surface registry: " + registryPath, exception);
|
||||
}
|
||||
|
||||
+10
-3
@@ -12,7 +12,6 @@ import p.studio.utilities.logs.LogAggregator;
|
||||
|
||||
@Slf4j
|
||||
public class FrontendPhasePipelineStage implements PipelineStage {
|
||||
private final AssetSurfaceContextLoader assetSurfaceContextLoader = new AssetSurfaceContextLoader();
|
||||
|
||||
@Override
|
||||
public BuildingIssueSink run(final BuilderPipelineContext ctx, final LogAggregator logs) {
|
||||
@@ -20,6 +19,15 @@ public class FrontendPhasePipelineStage implements PipelineStage {
|
||||
final var provider = FrontendRegistryService.require(frontedSpec.getLanguageId());
|
||||
final var projectTable = ctx.resolvedWorkspace.graph().projectTable();
|
||||
final var fileTable = ctx.fileTable;
|
||||
final var issues = BuildingIssueSink.empty();
|
||||
final p.studio.compiler.messages.FESurfaceContext surface;
|
||||
try {
|
||||
surface = new AssetSurfaceContextLoader(ctx.glyphBankLayoutSource).load(ctx.resolvedWorkspace.mainProject().getRootPath());
|
||||
} catch (IllegalArgumentException | IllegalStateException failure) {
|
||||
issues.report(builder -> builder.error(true).phase("frontend").code("E_ANIMATION_SURFACE")
|
||||
.message(failure.getMessage()));
|
||||
return issues;
|
||||
}
|
||||
final var frontendPhaseContext = new FrontendPhaseContext(
|
||||
projectTable,
|
||||
fileTable,
|
||||
@@ -27,9 +35,8 @@ public class FrontendPhasePipelineStage implements PipelineStage {
|
||||
ctx.resolvedWorkspace.stdlib(),
|
||||
ctx.resolvedWorkspace.target(),
|
||||
p.studio.compiler.messages.HostAdmissionContext.permissiveDefault(),
|
||||
assetSurfaceContextLoader.load(ctx.resolvedWorkspace.mainProject().getRootPath()));
|
||||
surface);
|
||||
final var diagnostics = DiagnosticSink.empty();
|
||||
final var issues = BuildingIssueSink.empty();
|
||||
ctx.irBackend = provider.compiler().compile(frontendPhaseContext, diagnostics, logs, issues);
|
||||
logs.using(log).debug("Frontend phase completed successfully!");
|
||||
adaptDiagnostics(diagnostics, issues);
|
||||
|
||||
@@ -3,6 +3,7 @@ plugins {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api(project(":prometeu-animation"))
|
||||
api(project(":prometeu-infra"))
|
||||
|
||||
api(project(":prometeu-compiler:prometeu-compiler-core"))
|
||||
|
||||
+4
-1
@@ -6,10 +6,13 @@ import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public record FESurfaceContext(
|
||||
ReadOnlyList<Addressable> assets) {
|
||||
ReadOnlyList<Addressable> assets, ReadOnlyList<p.animation.AnimationSource> animations) {
|
||||
|
||||
public FESurfaceContext(ReadOnlyList<Addressable> assets) { this(assets, ReadOnlyList.empty()); }
|
||||
|
||||
public FESurfaceContext {
|
||||
assets = normalizeAssets(assets);
|
||||
animations = animations == null ? ReadOnlyList.empty() : animations;
|
||||
}
|
||||
|
||||
public static FESurfaceContext empty() {
|
||||
|
||||
+9
-2
@@ -10,7 +10,13 @@ import java.util.Objects;
|
||||
/** A compiler-known source and the semantic context for exactly that content. */
|
||||
public record FrontendSourceDocument(
|
||||
Path path, String text, String origin, String name, String languageId,
|
||||
boolean readOnly, FrontendEditorialContext context) {
|
||||
boolean readOnly, FrontendEditorialContext context, java.util.List<OriginSpan> origins, String generationRevision) {
|
||||
public record OriginSpan(int startOffset, int endOffset, Path definitionPath, String jsonPointer, String assetUuid) {
|
||||
public OriginSpan(int startOffset,int endOffset,Path path,String pointer){this(startOffset,endOffset,path,pointer,null);}
|
||||
}
|
||||
public FrontendSourceDocument(Path path,String text,String origin,String name,String languageId,boolean readOnly,FrontendEditorialContext context) {
|
||||
this(path,text,origin,name,languageId,readOnly,context,java.util.List.of(),"");
|
||||
}
|
||||
public FrontendSourceDocument {
|
||||
path = Objects.requireNonNull(path).toAbsolutePath().normalize();
|
||||
Objects.requireNonNull(text);
|
||||
@@ -18,12 +24,13 @@ public record FrontendSourceDocument(
|
||||
Objects.requireNonNull(name);
|
||||
Objects.requireNonNull(languageId);
|
||||
Objects.requireNonNull(context);
|
||||
origins=java.util.List.copyOf(origins); generationRevision=Objects.requireNonNull(generationRevision);
|
||||
}
|
||||
|
||||
public String revision() {
|
||||
try {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
|
||||
.digest(text.getBytes(StandardCharsets.UTF_8)));
|
||||
.digest((generationRevision.isEmpty()?text:text+"\n"+generationRevision).getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (NoSuchAlgorithmException impossible) {
|
||||
throw new IllegalStateException(impossible);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user