feat(pbs): align typed values and Pad input facade
Test / Build occurred while executing withChecks step.
Intrepid/Prometeu/Studio/pipeline/pr-master There was a failure building this commit
Intrepid/Prometeu/Studio/pipeline/head There was a failure building this commit

This commit is contained in:
2026-10-15 15:48:50 +01:00
parent 603ed01227
commit 13c0ababbb
48 changed files with 1251 additions and 354 deletions
@@ -13,9 +13,11 @@ dependencies {
// Build-time projection of owner-maintained sources; no second normative copy is edited by Studio.
val pbsSpecs = rootProject.layout.projectDirectory.dir("docs/specs/compiler-languages/pbs")
val pbsAlignmentSpecs = rootProject.layout.projectDirectory.dir("docs/compiler/pbs/specs")
val pbsResources = layout.projectDirectory.dir("src/main/resources")
val generatePbsKnowledge by tasks.registering(Sync::class) {
from(pbsSpecs) { include("*.md"); into("pbs-knowledge/specs") }
from(pbsAlignmentSpecs) { include("*.md"); into("pbs-knowledge/specs") }
into(layout.buildDirectory.dir("generated/pbsKnowledge"))
inputs.files(fileTree(pbsResources) { include("game/stdlib/**/*.pbs", "game/stdlib/**/*.barrel", "pbs-knowledge/examples/**") })
doLast {
@@ -27,7 +29,7 @@ val generatePbsKnowledge by tasks.registering(Sync::class) {
entries.add(linkedMapOf("id" to id, "title" to title, "kind" to kind,
"resource" to resource, "sha256" to digest, "sdkVersion" to sdk, "target" to target))
}
pbsSpecs.asFile.listFiles()!!.filter { it.extension == "md" }.sortedBy { it.name }.forEach { source ->
(pbsSpecs.asFile.listFiles()!!.toList() + (pbsAlignmentSpecs.asFile.listFiles()?.toList() ?: emptyList())).filter { it.extension == "md" }.sortedBy { it.name }.forEach { source ->
val chapter = source.name.substringBefore(". ")
val quickstart = source.name == "README.md"
entry(if (quickstart) "pbs:quickstart" else "pbs:spec:$chapter",
@@ -25,7 +25,7 @@ import java.util.Map;
import java.util.Set;
public final class PBSSemanticTokenProvider implements FrontendSemanticTokenProvider {
private static final Set<String> BUILTIN_TYPE_NAMES = Set.of("int", "float", "bool", "string", "i32", "i64", "f32", "f64");
private static final Set<String> BUILTIN_TYPE_NAMES = Set.of("int", "long", "float", "bool", "string", "i32", "i64", "f32", "f64");
private static final int DEFAULT_STDLIB_VERSION = 1;
private static final AppMode DEFAULT_TARGET = AppMode.Game;
private static final ResourceStdlibEnvironmentResolver STDLIB_RESOLVER = new ResourceStdlibEnvironmentResolver();
@@ -234,7 +234,7 @@ public final class PbsFrontendCompiler {
effectiveModulePool,
ReadOnlyList.wrap(callableSignatures),
executableLowering.intrinsicPool(),
lifecycleDeclaration);
lifecycleDeclaration, executableLowering.registry());
}
public String callableShapeSurfaceOf(final PbsAst.FunctionDecl functionDecl) {
@@ -43,6 +43,12 @@ public final class PbsModuleVisibilityValidator {
}
}
private static String inputMigrationHint(String module, String name) {
return "@sdk:input".equals(module) && java.util.Set.of("Input", "InputType", "InputPad", "InputTouch", "InputButton").contains(name)
? "; migrate to Pad.pressed/released/down/hold(Button.A) or Touch queries. Intermediate input objects are no longer values."
: "";
}
private ModuleExports validateModule(
final ModuleUnit module,
final NameTable nameTable,
@@ -219,7 +225,7 @@ public final class PbsModuleVisibilityValidator {
PbsLinkErrors.E_LINK_IMPORT_SYMBOL_UNRESOLVED.name(),
"Symbol '%s' does not exist in module %s".formatted(
importItem.name(),
displayModule(targetModule)),
displayModule(targetModule)) + inputMigrationHint(displayModule(targetModule), importItem.name()),
importItem.span());
continue;
}
@@ -28,7 +28,7 @@ final class PbsExecutableBodyLowerer {
final PbsExecutableMetadataIndex metadataIndex,
final PbsExecutableCallableRegistry callableRegistry,
final IntrinsicTable intrinsicIdTable) {
final var localSlotByNameId = initialLocalSlots(functionDecl, nameTable);
final var localSlotByNameId = initialLocalSlots(functionDecl, nameTable, metadataIndex.types());
final var localOwnerByNameId = initialLocalOwners(functionDecl, nameTable, metadataIndex);
final var context = new PbsExecutableLoweringContext(
diagnostics,
@@ -38,11 +38,13 @@ final class PbsExecutableBodyLowerer {
intrinsicIdTable,
localSlotByNameId,
localOwnerByNameId,
functionDecl.parameters().size());
functionDecl.parameters().stream().mapToInt(p -> metadataIndex.types().slots(p.typeRef())).sum());
for (var parameter : functionDecl.parameters()) context.localTypes.put(parameter.name(), parameter.typeRef());
context.returnType = functionDecl.returnType();
final var terminated = lowerBlock(functionDecl.body(), context);
finalizeFunctionInstructions(functionDecl, context, terminated);
final var returnSlots = returnSlotsFor(functionDecl);
final var returnSlots = functionDecl.returnKind() == PbsAst.ReturnKind.PLAIN ? context.types().slots(functionDecl.returnType()) : 0;
final int maxStackSlots;
try {
maxStackSlots = stackAnalyzer.analyzeMaxStackSlots(ReadOnlyList.wrap(context.instructions()), returnSlots);
@@ -56,7 +58,7 @@ final class PbsExecutableBodyLowerer {
functionDecl.span());
return null;
}
final var localSlots = Math.max(0, context.nextLocalSlot() - functionDecl.parameters().size());
final var localSlots = Math.max(0, context.nextLocalSlot() - functionDecl.parameters().stream().mapToInt(p -> context.types().slots(p.typeRef())).sum());
return new PbsLoweredExecutableBody(
ReadOnlyList.wrap(context.instructions()),
localSlots,
@@ -65,10 +67,12 @@ final class PbsExecutableBodyLowerer {
private Map<NameId, Integer> initialLocalSlots(
final PbsAst.FunctionDecl functionDecl,
final NameTable nameTable) {
final NameTable nameTable, final PbsRuntimeTypes types) {
final var localSlotByNameId = new HashMap<NameId, Integer>();
for (var paramIndex = 0; paramIndex < functionDecl.parameters().size(); paramIndex++) {
localSlotByNameId.put(nameTable.register(functionDecl.parameters().get(paramIndex).name()), paramIndex);
int slot = 0;
for (var parameter : functionDecl.parameters()) {
localSlotByNameId.put(nameTable.register(parameter.name()), slot);
slot += types.slots(parameter.typeRef());
}
return localSlotByNameId;
}
@@ -155,7 +159,9 @@ final class PbsExecutableBodyLowerer {
final var localOwner = callsiteEmitter.resolveExpressionOwnerForLowering(letStatement.initializer(), context);
final var tupleProjection = tupleProjectionOf(letStatement.initializer(), context);
final var valueSlots = Math.max(1, materializedValueSlots(letStatement.initializer(), context));
lowerExpression(letStatement.initializer(), context);
final var localType = letStatement.explicitType() != null ? letStatement.explicitType() : expressionType(letStatement.initializer(), context);
lowerExpected(letStatement.initializer(), localType, context);
context.localTypes.put(letStatement.name(), localType);
final var localSlot = context.declareLocalSlots(letStatement.name(), valueSlots);
context.bindLocalOwner(letStatement.name(), localOwner);
context.bindLocalTupleProjection(letStatement.name(), tupleProjection);
@@ -185,7 +191,7 @@ final class PbsExecutableBodyLowerer {
final var localOwner = callsiteEmitter.resolveExpressionOwnerForLowering(assignStatement.value(), context);
final var tupleProjection = tupleProjectionOf(assignStatement.value(), context);
final var valueSlots = Math.max(1, materializedValueSlots(assignStatement.value(), context));
lowerExpression(assignStatement.value(), context);
lowerExpected(assignStatement.value(), context.localTypes.getOrDefault(target.rootName(), context.types().values.get(target.rootName())), context);
if (targetLocalSlot != null) {
context.bindLocalOwner(target.rootName(), localOwner);
context.bindLocalTupleProjection(target.rootName(), tupleProjection);
@@ -200,7 +206,7 @@ final class PbsExecutableBodyLowerer {
} else {
emitGetGlobal(targetGlobalSlot, assignStatement.span(), context);
}
lowerExpression(assignStatement.value(), context);
lowerExpected(assignStatement.value(), context.localTypes.getOrDefault(target.rootName(), context.types().values.get(target.rootName())), context);
emitBinaryOperatorInstruction(compoundAssignBinaryOperator(assignStatement.operator()), assignStatement.span(), context);
if (targetLocalSlot != null) {
context.bindLocalOwner(target.rootName(), "");
@@ -235,7 +241,7 @@ final class PbsExecutableBodyLowerer {
final PbsAst.ReturnStatement returnStatement,
final PbsExecutableLoweringContext context) {
if (returnStatement.value() != null) {
lowerExpression(returnStatement.value(), context);
lowerExpected(returnStatement.value(), context.returnType, context);
}
context.instructions().add(new IRBackendExecutableFunction.Instruction(
IRBackendExecutableFunction.InstructionKind.RET,
@@ -363,10 +369,7 @@ final class PbsExecutableBodyLowerer {
}
switch (expression) {
case PbsAst.CallExpr callExpr -> lowerCallExpression(callExpr, context);
case PbsAst.ApplyExpr applyExpr -> {
lowerExpression(applyExpr.callee(), context);
lowerExpression(applyExpr.argument(), context);
}
case PbsAst.ApplyExpr applyExpr -> lowerApply(applyExpr, context);
case PbsAst.BinaryExpr binaryExpr -> {
lowerExpression(binaryExpr.left(), context);
lowerExpression(binaryExpr.right(), context);
@@ -381,36 +384,36 @@ final class PbsExecutableBodyLowerer {
lowerExpression(elseExpr.fallbackExpression(), context);
}
case PbsAst.IfExpr ifExpr -> lowerIfExpression(ifExpr, context);
case PbsAst.SwitchExpr switchExpr -> lowerUnsupportedExpression(
switchExpr.selector(),
"switch expression is not lowerable in executable lowering v1",
switchExpr.span(),
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.AsExpr asExpr -> lowerExpression(asExpr.expression(), 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.GroupExpr groupExpr -> lowerExpression(groupExpr.expression(), context);
case PbsAst.NewExpr newExpr -> lowerExpressionList(newExpr.arguments(), context);
case PbsAst.NewExpr newExpr -> {
var fields = context.types().fields.get(newExpr.typeName());
for(int i=0; i<newExpr.arguments().size(); i++) lowerExpected(newExpr.arguments().get(i), fields != null && i < fields.size() ? fields.get(i).typeRef() : null, context);
}
case PbsAst.BindExpr bindExpr -> lowerExpression(bindExpr.contextExpression(), context);
case PbsAst.SomeExpr someExpr -> lowerExpression(someExpr.value(), context);
case PbsAst.OkExpr okExpr -> lowerExpression(okExpr.value(), context);
case PbsAst.TupleExpr tupleExpr -> {
for (final var item : tupleExpr.items()) {
lowerExpression(item.expression(), context);
var expected = context.expectedType;
for (int index=0; index<tupleExpr.items().size(); index++) {
var item=tupleExpr.items().get(index);
var fieldType=expected != null && expected.kind()==PbsAst.TypeRefKind.NAMED_TUPLE && index<expected.fields().size() ? expected.fields().get(index).typeRef() : null;
lowerExpected(item.expression(), fieldType, context);
}
}
case PbsAst.BlockExpr blockExpr -> lowerBlock(blockExpr.block(), context);
case PbsAst.IdentifierExpr identifierExpr -> lowerIdentifierExpression(identifierExpr, context);
case PbsAst.IntLiteralExpr intLiteralExpr -> lowerIntLiteral(intLiteralExpr, context);
case PbsAst.FloatLiteralExpr ignored -> {
}
case PbsAst.BoundedLiteralExpr ignored -> {
}
case PbsAst.FloatLiteralExpr literal -> emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_F64, Double.toString(literal.value()), literal.span(), context);
case PbsAst.BoundedLiteralExpr literal -> emitPushI32(literal.value(), literal.span(), context);
case PbsAst.StringLiteralExpr stringLiteralExpr -> emitPushConst(stringLiteralExpr.value(), stringLiteralExpr.span(), context);
case PbsAst.BoolLiteralExpr boolLiteralExpr -> emitPushBool(boolLiteralExpr.value(), boolLiteralExpr.span(), context);
case PbsAst.ThisExpr ignored -> {
@@ -437,7 +440,10 @@ final class PbsExecutableBodyLowerer {
final PbsExecutableLoweringContext context) {
final var hostBinding = callsiteEmitter.resolveUniqueHostBinding(callExpr, context);
if (hostBinding == null || hostBinding.assetLoweringParam() == null) {
lowerExpressionList(callExpr.arguments(), context);
final var signature = context.types().signatures.get(PbsRuntimeTypes.path(callExpr.callee())+"#"+callExpr.arguments().size());
for (int i=0; i<callExpr.arguments().size(); i++) {
lowerExpected(callExpr.arguments().get(i), signature != null && i < signature.parameters().size() ? signature.parameters().get(i).typeRef() : null, context);
}
return;
}
for (int i = 0; i < callExpr.arguments().size(); i++) {
@@ -476,6 +482,10 @@ final class PbsExecutableBodyLowerer {
private void lowerMemberExpression(
final PbsAst.MemberExpr memberExpr,
final PbsExecutableLoweringContext context) {
if (memberExpr.receiver() instanceof PbsAst.IdentifierExpr owner) {
final var enumValue = context.types().enumValue(owner.name(), memberExpr.memberName());
if (enumValue != null) { emitPushI32(enumValue, memberExpr.span(), context); return; }
}
final var assetReference = flattenAssetReference(memberExpr);
if (assetReference != null) {
final var assetId = context.resolveAssetId(assetReference);
@@ -492,6 +502,15 @@ final class PbsExecutableBodyLowerer {
if (memberExpr.receiver() instanceof PbsAst.IdentifierExpr identifierExpr) {
final var tupleProjection = context.resolveLocalTupleProjection(identifierExpr.name());
final var localSlot = context.resolveLocalSlot(identifierExpr.name());
var type = context.localTypes.get(identifierExpr.name());
var fields = type == null ? null : context.types().fields.get(type.name());
if (fields != null && localSlot != null) {
int offset = 0;
for (var field : fields) {
if (field.name().equals(memberExpr.memberName())) { emitLoadLocalSlots(localSlot + offset, context.types().slots(field.typeRef()), memberExpr.span(), context); return; }
offset += context.types().slots(field.typeRef());
}
}
if (tupleProjection != null && localSlot != null) {
final var fieldProjection = tupleProjection.fieldsByLabel().get(memberExpr.memberName());
if (fieldProjection != null) {
@@ -562,7 +581,7 @@ final class PbsExecutableBodyLowerer {
if (tupleProjection != null) {
emitLoadLocalSlots(slot, tupleProjection.slotCount(), identifierExpr.span(), context);
} else {
emitGetLocal(slot, identifierExpr.span(), context);
emitLoadLocalSlots(slot, Math.max(1, context.types().slots(context.localTypes.get(identifierExpr.name()))), identifierExpr.span(), context);
}
return;
}
@@ -586,18 +605,10 @@ final class PbsExecutableBodyLowerer {
final p.studio.compiler.models.IRReservedMetadata.BuiltinConstSurface builtinConst,
final p.studio.compiler.source.Span span,
final PbsExecutableLoweringContext context) {
final var canonicalName = builtinConst.canonicalTarget() + "." + builtinConst.canonicalName();
context.instructions().add(new IRBackendExecutableFunction.Instruction(
IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC,
"",
null,
new IRBackendExecutableFunction.IntrinsicCallMetadata(
canonicalName,
builtinConst.canonicalVersion(),
context.intrinsicIdTable().register(canonicalName, builtinConst.canonicalVersion())),
0,
1,
span));
context.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.BUILTIN_CONST,
ModuleId.none(), "", null, null, null,
builtinConst.canonicalTarget() + "." + builtinConst.canonicalName() + "@" + builtinConst.canonicalVersion(), "", null,
context.types().slots(context.types().values.get(builtinConst.sourceConstName())), span));
}
private String flattenAssetReference(final PbsAst.Expression expression) {
@@ -622,7 +633,7 @@ final class PbsExecutableBodyLowerer {
}
return switch (expression) {
case PbsAst.CallExpr callExpr -> callsiteEmitter.returnSlotsOf(callExpr, context);
case PbsAst.ApplyExpr ignored -> 0;
case PbsAst.ApplyExpr apply -> callsiteEmitter.returnSlotsOf(applyCall(apply), context);
case PbsAst.BinaryExpr ignored -> 1;
case PbsAst.UnaryExpr ignored -> 1;
case PbsAst.ElseExpr elseExpr ->
@@ -633,7 +644,7 @@ final class PbsExecutableBodyLowerer {
Math.max(
blockValueSlots(ifExpr.thenBlock(), context),
materializedValueSlots(ifExpr.elseExpression(), context));
case PbsAst.SwitchExpr ignored -> 0;
case PbsAst.SwitchExpr sw -> sw.arms().isEmpty() ? 0 : blockValueSlots(sw.arms().getFirst().block(), context);
case PbsAst.HandleExpr ignored -> 0;
case PbsAst.AsExpr asExpr -> materializedValueSlots(asExpr.expression(), context);
case PbsAst.MemberExpr memberExpr -> {
@@ -642,6 +653,9 @@ final class PbsExecutableBodyLowerer {
yield 1;
}
if (memberExpr.receiver() instanceof PbsAst.IdentifierExpr identifierExpr) {
var type = context.localTypes.get(identifierExpr.name());
var fields = type == null ? null : context.types().fields.get(type.name());
if (fields != null) for (var field : fields) if (field.name().equals(memberExpr.memberName())) yield context.types().slots(field.typeRef());
final var tupleProjection = context.resolveLocalTupleProjection(identifierExpr.name());
if (tupleProjection != null) {
final var fieldProjection = tupleProjection.fieldsByLabel().get(memberExpr.memberName());
@@ -650,6 +664,7 @@ final class PbsExecutableBodyLowerer {
}
}
}
if (memberExpr.receiver() instanceof PbsAst.IdentifierExpr owner && context.types().enumValue(owner.name(), memberExpr.memberName()) != null) yield 1;
yield materializedValueSlots(memberExpr.receiver(), context);
}
case PbsAst.PropagateExpr propagateExpr -> materializedValueSlots(propagateExpr.expression(), context);
@@ -670,8 +685,8 @@ final class PbsExecutableBodyLowerer {
case PbsAst.IntLiteralExpr ignored -> 1;
case PbsAst.StringLiteralExpr ignoredString -> 1;
case PbsAst.BoolLiteralExpr ignoredBool -> 1;
case PbsAst.FloatLiteralExpr ignoredFloat -> 0;
case PbsAst.BoundedLiteralExpr ignoredBounded -> 0;
case PbsAst.FloatLiteralExpr ignoredFloat -> 1;
case PbsAst.BoundedLiteralExpr ignoredBounded -> 1;
case PbsAst.ThisExpr ignoredThis -> 0;
case PbsAst.NoneExpr ignoredNone -> 0;
case PbsAst.ErrExpr ignoredErr -> 0;
@@ -712,11 +727,11 @@ final class PbsExecutableBodyLowerer {
private int identifierValueSlots(
final PbsAst.IdentifierExpr identifierExpr,
final PbsExecutableLoweringContext context) {
if (!producesIdentifierValue(identifierExpr, context)) {
return 0;
}
var constant = context.builtinConstByNameId().get(context.nameTable().register(identifierExpr.name()));
if (constant != null) return context.types().slots(context.types().values.get(identifierExpr.name()));
if (!producesIdentifierValue(identifierExpr, context)) return 0;
final var tupleProjection = context.resolveLocalTupleProjection(identifierExpr.name());
return tupleProjection == null ? 1 : tupleProjection.slotCount();
return tupleProjection == null ? Math.max(1, context.types().slots(expressionType(identifierExpr, context))) : tupleProjection.slotCount();
}
private PbsTupleProjection tupleProjectionOf(
@@ -774,6 +789,10 @@ final class PbsExecutableBodyLowerer {
private void lowerIntLiteral(
final PbsAst.IntLiteralExpr intLiteralExpr,
final PbsExecutableLoweringContext context) {
if (context.expectedType != null && "long".equals(context.types().canonical(context.expectedType))) {
emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_I64, Long.toString(intLiteralExpr.value()), intLiteralExpr.span(), context);
return;
}
if (intLiteralExpr.value() < Integer.MIN_VALUE || intLiteralExpr.value() > Integer.MAX_VALUE) {
reportUnsupportedLowering(
"int literal exceeds i32 lowering range: " + intLiteralExpr.value(),
@@ -784,6 +803,132 @@ final class PbsExecutableBodyLowerer {
emitPushI32((int) intLiteralExpr.value(), intLiteralExpr.span(), context);
}
private PbsAst.CallExpr applyCall(PbsAst.ApplyExpr apply) {
var argument = apply.argument();
while (argument instanceof PbsAst.GroupExpr group) argument = group.expression();
var values = argument instanceof PbsAst.TupleExpr tuple ? tuple.items().stream().map(PbsAst.TupleItem::expression).toList()
: argument instanceof PbsAst.UnitExpr ? java.util.List.<PbsAst.Expression>of() : java.util.List.of(argument);
return new PbsAst.CallExpr(apply.callee(), ReadOnlyList.wrap(values), apply.span());
}
private void lowerApply(PbsAst.ApplyExpr apply, PbsExecutableLoweringContext c) {
var call = applyCall(apply);
var argument = apply.argument();
while (argument instanceof PbsAst.GroupExpr group) argument = group.expression();
if (!(argument instanceof PbsAst.TupleExpr tuple) || tuple.items().isEmpty() || tuple.items().getFirst().label() == null) {
lowerCallExpression(call, c); return;
}
var signature = c.types().signatures.get(PbsRuntimeTypes.path(call.callee())+"#"+call.arguments().size());
if(signature == null) { reportUnsupportedLowering("Named application requires a resolved signature", apply.span(), c); return; }
var slots = new java.util.HashMap<String,Integer>();
for(var item:tuple.items()) {
var parameter = signature.parameters().stream().filter(p -> p.name().equals(item.label())).findFirst().orElse(null);
if(parameter == null || slots.containsKey(item.label())) { reportUnsupportedLowering("Unknown or duplicate named argument: "+item.label(), item.span(), c); return; }
// Evaluate source order once, then reorder complete value groups, never expressions.
lowerExpected(item.expression(), parameter.typeRef(), c);
int width = c.types().slots(parameter.typeRef());
int slot = c.declareLocalSlots(c.nextLabel("argument"), width);
emitStoreLocalSlots(slot, width, item.span(), c);
slots.put(item.label(), slot);
}
for(var parameter:signature.parameters()) {
var slot=slots.get(parameter.name());
if(slot==null) { reportUnsupportedLowering("Missing named argument: "+parameter.name(), apply.span(), c); return; }
emitLoadLocalSlots(slot,c.types().slots(parameter.typeRef()),apply.span(),c);
}
callsiteEmitter.emitCallsite(call,c);
}
private void lowerExpected(PbsAst.Expression expression, PbsAst.TypeRef expected, PbsExecutableLoweringContext context) {
var previous = context.expectedType;
context.expectedType = expected;
try { lowerExpression(expression, context); } finally { context.expectedType = previous; }
}
private PbsAst.TypeRef expressionType(PbsAst.Expression e, PbsExecutableLoweringContext c) {
if (e instanceof PbsAst.IdentifierExpr i) return c.localTypes.getOrDefault(i.name(), c.types().values.get(i.name()));
if (e instanceof PbsAst.GroupExpr g) return expressionType(g.expression(), c);
if (e instanceof PbsAst.AsExpr a) return PbsRuntimeTypes.type(a.contractName());
if (e instanceof PbsAst.UnaryExpr u) return java.util.Set.of("!", "not").contains(u.operator()) ? PbsRuntimeTypes.type("bool") : expressionType(u.expression(), c);
if (e instanceof PbsAst.BinaryExpr b) return java.util.Set.of("==", "!=", "<", "<=", ">", ">=", "&&", "||", "and", "or").contains(b.operator()) ? PbsRuntimeTypes.type("bool") : expressionType(b.left(), c);
if (e instanceof PbsAst.IfExpr branch) return expressionType(branch.thenBlock().tailExpression(), c);
if (e instanceof PbsAst.SwitchExpr branch && !branch.arms().isEmpty()) return expressionType(branch.arms().getFirst().block().tailExpression(), c);
if (e instanceof PbsAst.ApplyExpr apply) return expressionType(applyCall(apply), c);
if (e instanceof PbsAst.NewExpr value) return PbsRuntimeTypes.type(value.typeName());
if (e instanceof PbsAst.CallExpr call) {
var sig = c.types().signatures.get(PbsRuntimeTypes.path(call.callee())+"#"+call.arguments().size());
return sig == null ? null : sig.returnType();
}
if (e instanceof PbsAst.MemberExpr m && m.receiver() instanceof PbsAst.IdentifierExpr i) {
if (c.types().enums.containsKey(i.name())) return PbsRuntimeTypes.type(i.name());
var owner = c.localTypes.get(i.name());
var fields = owner == null ? null : c.types().fields.get(owner.name());
if (fields != null) for (var field : fields) if (field.name().equals(m.memberName())) return field.typeRef();
if (owner != null && owner.kind() == PbsAst.TypeRefKind.NAMED_TUPLE)
for (var field : owner.fields()) if (field.label().equals(m.memberName())) return field.typeRef();
}
if (e instanceof PbsAst.IntLiteralExpr || e instanceof PbsAst.BoundedLiteralExpr) return PbsRuntimeTypes.type("int");
if (e instanceof PbsAst.FloatLiteralExpr) return PbsRuntimeTypes.type("float");
if (e instanceof PbsAst.BoolLiteralExpr) return PbsRuntimeTypes.type("bool");
if (e instanceof PbsAst.StringLiteralExpr) return PbsRuntimeTypes.type("str");
return null;
}
private void lowerConversion(PbsAst.AsExpr expr, PbsExecutableLoweringContext c) {
var source = c.types().canonical(expressionType(expr.expression(), c));
var target = expr.contractName();
lowerExpected(expr.expression(), null, c);
if (source.equals(target)) return;
String name = switch(source + "->" + target) {
case "int->long" -> "math.i32.to_i64"; case "long->int" -> "math.i64.to_i32";
case "int->float" -> "math.i32.to_float"; case "long->float" -> "math.i64.to_float";
case "float->int" -> "mathf.to_i32"; case "float->long" -> "mathf.to_i64";
default -> null;
};
if (name == null) { reportUnsupportedLowering("Unsupported conversion " + source + " -> " + target, expr.span(), c); return; }
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC,
"", null, new IRBackendExecutableFunction.IntrinsicCallMetadata(name, 1, c.intrinsicIdTable().register(name, 1)), 1, 1, expr.span()));
}
private void lowerSwitch(PbsAst.SwitchExpr expr, PbsExecutableLoweringContext c) {
var slot = c.declareLocalSlot(c.nextLabel("switch_value"));
lowerExpected(expr.selector(), null, c);
emitSetLocal(slot, expr.span(), c);
var end = c.nextLabel("switch_end");
var selectorType = expressionType(expr.selector(), c);
var enumDecl = selectorType == null ? null : c.types().enums.get(selectorType.name());
var coveredCases = new java.util.HashSet<String>();
var coveredBooleans = new java.util.HashSet<Boolean>();
for (var arm : expr.arms()) {
if (arm.pattern() instanceof PbsAst.EnumCaseSwitchPattern pattern) coveredCases.add(pattern.path().segments().get(1));
if (arm.pattern() instanceof PbsAst.LiteralSwitchPattern pattern && pattern.literal() instanceof PbsAst.BoolLiteralExpr literal) coveredBooleans.add(literal.value());
}
boolean exhaustive = enumDecl != null && enumDecl.cases().stream().allMatch(item -> coveredCases.contains(item.name())) || coveredBooleans.size() == 2;
for (int i=0; i<expr.arms().size(); i++) {
var arm = expr.arms().get(i);
var next = c.nextLabel("switch_next");
boolean last = i == expr.arms().size()-1;
boolean checked = !(arm.pattern() instanceof PbsAst.WildcardSwitchPattern) && !(last && exhaustive);
if (checked) {
emitGetLocal(slot, expr.span(), c);
if (arm.pattern() instanceof PbsAst.EnumCaseSwitchPattern pattern) {
var value = c.types().enumValue(pattern.path().segments().get(0), pattern.path().segments().get(1));
emitPushI32(value, pattern.span(), c);
} else if (arm.pattern() instanceof PbsAst.LiteralSwitchPattern literal) lowerExpected(literal.literal(), expressionType(expr.selector(), c), c);
emitBinaryOperatorInstruction("==", expr.span(), c);
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE, next, expr.span(), c);
}
lowerBlock(arm.block(), c);
if (!last) emitJump(IRBackendExecutableFunction.InstructionKind.JMP, end, arm.span(), c);
if (checked) emitLabel(next, arm.span(), c);
}
emitLabel(end, expr.span(), c);
}
private void emitLiteral(IRBackendExecutableFunction.InstructionKind kind, String value, p.studio.compiler.source.Span span, PbsExecutableLoweringContext c) {
c.instructions().add(new IRBackendExecutableFunction.Instruction(kind, ModuleId.none(), "", null, null, null, value, "", null, null, span));
}
private void lowerCallsiteReceiver(
final PbsAst.Expression callee,
final PbsExecutableLoweringContext context) {
@@ -201,7 +201,7 @@ final class PbsExecutableCallsiteEmitter {
final PbsAst.CallExpr callExpr,
final PbsExecutableLoweringContext context,
final IRReservedMetadata.HostMethodBinding host) {
final var effectiveArgSlots = callExpr.arguments().size() + implicitReceiverArgSlots(callExpr.callee(), context);
final var effectiveArgSlots = argumentSlots(callExpr, context) + implicitReceiverArgSlots(callExpr.callee(), context);
context.instructions().add(new IRBackendExecutableFunction.Instruction(
IRBackendExecutableFunction.InstructionKind.CALL_HOST,
"",
@@ -251,7 +251,7 @@ final class PbsExecutableCallsiteEmitter {
reportUnsupportedLowering("executable lowering resolved callable without signature metadata", callExpr.span(), context);
return;
}
final var effectiveArgSlots = callExpr.arguments().size() + implicitReceiverArgSlots(callExpr.callee(), context);
final var effectiveArgSlots = argumentSlots(callExpr, context) + implicitReceiverArgSlots(callExpr.callee(), context);
context.instructions().add(new IRBackendExecutableFunction.Instruction(
IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
calleeSignature.moduleId(),
@@ -411,13 +411,23 @@ final class PbsExecutableCallsiteEmitter {
};
}
private int argumentSlots(PbsAst.CallExpr call, PbsExecutableLoweringContext context) {
var signature = context.types().signatures.get(PbsRuntimeTypes.path(call.callee())+"#"+call.arguments().size());
return signature == null ? call.arguments().size() : signature.parameters().stream().mapToInt(p -> context.types().slots(p.typeRef())).sum();
}
private int implicitReceiverArgSlots(
final PbsAst.Expression callee,
final PbsExecutableLoweringContext context) {
if (!(callee instanceof PbsAst.MemberExpr memberExpr)) {
return 0;
}
return receiverProducesRuntimeValue(memberExpr.receiver(), context) ? 1 : 0;
if (!receiverProducesRuntimeValue(memberExpr.receiver(), context)) return 0;
return switch (resolveExpressionOwner(memberExpr.receiver(), context)) {
case "vec2" -> 2;
case "pixel" -> 3;
default -> 1;
};
}
private boolean receiverProducesRuntimeValue(
@@ -22,6 +22,10 @@ final class PbsExecutableLoweringContext {
private final Map<NameId, String> localOwnerByNameId;
private final ArrayList<IRBackendExecutableFunction.Instruction> instructions = new ArrayList<>();
private final ArrayDeque<PbsLoopTargets> loopTargets = new ArrayDeque<>();
final Map<String, p.studio.compiler.pbs.ast.PbsAst.TypeRef> localTypes = new HashMap<>();
p.studio.compiler.pbs.ast.PbsAst.TypeRef expectedType;
p.studio.compiler.pbs.ast.PbsAst.TypeRef returnType;
PbsRuntimeTypes types() { return metadataIndex.types(); }
private int nextLabelId = 0;
private int nextLocalSlot;
@@ -18,7 +18,8 @@ public class PbsExecutableLoweringModels {
public record PbsExecutableLoweringResult(
ReadOnlyList<IRBackendExecutableFunction> executableFunctions,
ReadOnlyList<CallableSignatureRef> callableSignatures,
ReadOnlyList<IntrinsicReference> intrinsicPool) {
ReadOnlyList<IntrinsicReference> intrinsicPool,
p.studio.compiler.models.registry.IRRegistry registry) {
}
record PbsLowerableCallable(
@@ -42,6 +43,7 @@ public class PbsExecutableLoweringModels {
}
record PbsExecutableMetadataIndex(
PbsRuntimeTypes types,
Map<NameId, List<IRReservedMetadata.HostMethodBinding>> hostByMethodName,
Map<String, String> builtinCanonicalBySourceType,
Map<NameId, String> builtinConstOwnerByNameId,
@@ -47,6 +47,10 @@ public final class PbsExecutableLoweringService {
nameTable,
metadataIndex.builtinCanonicalBySourceType(),
importedCallables);
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);
}
final var intrinsicIdTable = new IntrinsicTable();
final var executableFunctions = new ArrayList<IRBackendExecutableFunction>(callableRegistry.localCallables().size());
@@ -72,7 +76,7 @@ public final class PbsExecutableLoweringService {
return new PbsExecutableLoweringResult(
ReadOnlyList.wrap(executableFunctions),
callableRegistry.callableSignatures(),
ReadOnlyList.wrap(intrinsicPool));
ReadOnlyList.wrap(intrinsicPool), metadataIndex.types().registry());
}
public String callableShapeSurfaceOf(final PbsAst.FunctionDecl functionDecl) {
@@ -110,12 +114,13 @@ public final class PbsExecutableLoweringService {
functionCallableId,
safeToInt(functionDecl.span().getStart()),
safeToInt(functionDecl.span().getEnd()),
functionDecl.parameters().size(),
functionDecl.parameters().stream().mapToInt(p -> metadataIndex.types().slots(p.typeRef())).sum(),
loweredBody.localSlots(),
callableRegistry.returnSlotsByCallableId().getOrDefault(functionCallableId, 0),
functionDecl.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(functionDecl.returnType()) : 0,
loweredBody.maxStackSlots(),
loweredBody.instructions(),
functionDecl.span());
functionDecl.span(),
metadataIndex.types().metadata(functionDecl));
}
private int safeToInt(final long value) {
@@ -48,6 +48,7 @@ final class PbsExecutableMetadataIndexFactory {
intrinsicReturnOwnerByCanonical,
diagnostics);
return new PbsExecutableMetadataIndex(
new PbsRuntimeTypes(ast, supplementalTopDecls, builtinCanonicalBySourceType),
hostByMethodName,
builtinCanonicalBySourceType,
builtinConstOwnerByNameId,
@@ -38,7 +38,8 @@ final class PbsExecutableStackAnalyzer {
var outHeight = incomingHeightByInstruction.get(index);
switch (instruction.kind()) {
case PUSH_I32, PUSH_BOOL, PUSH_CONST, GET_LOCAL, GET_GLOBAL -> outHeight += 1;
case PUSH_I32, PUSH_I64, PUSH_F64, PUSH_BOOL, PUSH_CONST, GET_LOCAL, GET_GLOBAL -> outHeight += 1;
case BUILTIN_CONST -> outHeight += instruction.expectedRetSlots();
case POP, SET_LOCAL, SET_GLOBAL -> {
if (outHeight <= 0) {
throw new ExecutableLoweringAnalysisException(
@@ -0,0 +1,92 @@
package p.studio.compiler.pbs.lowering;
import p.studio.compiler.models.registry.IRRegistry;
import p.studio.compiler.pbs.ast.PbsAst;
import p.studio.compiler.source.Span;
import p.studio.utilities.structures.ReadOnlyList;
import java.util.*;
/** PBS-owned source identities and layouts; never inferred from slot widths. */
final class PbsRuntimeTypes {
final Map<String, String> builtinNames;
final Map<String, ReadOnlyList<PbsAst.BuiltinFieldDecl>> fields = new HashMap<>();
final Map<String, PbsAst.EnumDecl> enums = new HashMap<>();
final Map<String, PbsAst.FunctionSignature> signatures = new HashMap<>();
final Map<String, PbsAst.TypeRef> values = new HashMap<>();
private final Map<Integer, IRRegistry.TypeDeclaration> used = new TreeMap<>();
PbsRuntimeTypes(PbsAst.File ast, ReadOnlyList<PbsAst.TopDecl> supplemental, Map<String,String> builtins) {
builtinNames = builtins;
var declarations = new ArrayList<>(ast.topDecls().asList());
declarations.addAll(supplemental.asList());
for (var decl : declarations) {
if (decl instanceof PbsAst.EnumDecl e) enums.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) addSignature(f.name(), f);
if (decl instanceof PbsAst.ServiceDecl s) for (var f : s.methods()) addSignature(s.name()+"."+f.name(), f);
if (decl instanceof PbsAst.BuiltinTypeDecl b) {
fields.put(b.name(), b.fields());
for(var f:b.signatures()) signatures.put(b.name()+"."+f.name()+"#"+f.parameters().size(), f);
}
if (decl instanceof PbsAst.HostDecl h) for(var f:h.signatures()) signatures.put(h.name()+"."+f.name()+"#"+f.parameters().size(), f);
}
}
private void addSignature(String name, PbsAst.FunctionDecl f) {
signatures.put(name+"#"+f.parameters().size(), new PbsAst.FunctionSignature(f.name(), f.parameters(), f.returnKind(), f.returnType(), f.resultErrorType(), f.attributes(), f.span()));
}
static PbsAst.TypeRef type(String name) { return PbsAst.TypeRef.simple(name, Span.none()); }
String canonical(PbsAst.TypeRef t) {
if(t==null) return "void";
if(t.kind()==PbsAst.TypeRefKind.GROUP) return canonical(t.inner());
return builtinNames.getOrDefault(t.name(), t.name());
}
int slots(PbsAst.TypeRef t) {
if(t==null || t.kind()==PbsAst.TypeRefKind.UNIT) return 0;
if(t.kind()==PbsAst.TypeRefKind.GROUP) return slots(t.inner());
if(t.kind()==PbsAst.TypeRefKind.NAMED_TUPLE) return t.fields().stream().mapToInt(f->slots(f.typeRef())).sum();
return switch(canonical(t)) { case "vec2" -> 2; case "pixel" -> 3; default -> 1; };
}
IRRegistry.TypeRef registryType(PbsAst.TypeRef t) {
int id = switch(canonical(t)) {
case "int" -> 0x10; case "long" -> 0x11; case "float" -> 0x12;
case "bool" -> 0x13; case "str" -> 0x14;
case "color" -> 1; case "vec2" -> 2; case "pixel" -> 3;
default -> { if(enums.containsKey(t.name())) yield 0x10;
throw new UnsupportedOperationException("Unsupported PBS runtime type: "+t.name()); }
};
var ref=IRRegistry.TypeRef.builtin(id);
used.putIfAbsent(id,new IRRegistry.TypeDeclaration(ref,null,new IRRegistry.Builtin(id)));
return ref;
}
List<IRRegistry.TypeRef> results(PbsAst.TypeRef t) {
if(t==null || t.kind()==PbsAst.TypeRefKind.UNIT) return List.of();
if(t.kind()==PbsAst.TypeRefKind.GROUP) return results(t.inner());
if(t.kind()==PbsAst.TypeRefKind.NAMED_TUPLE) return t.fields().stream().flatMap(f->results(f.typeRef()).stream()).toList();
return List.of(registryType(t));
}
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.
try { return supportedMetadata(f); } catch (UnsupportedOperationException unsupported) { return null; }
}
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();
return IRRegistry.FunctionMetadata.ordinary(new IRRegistry.Signature(ReadOnlyList.wrap(params),ReadOnlyList.wrap(returns)));
}
IRRegistry registry() { return new IRRegistry(ReadOnlyList.wrap(new ArrayList<>(used.values())),ReadOnlyList.empty()); }
Integer enumValue(String owner,String label) {
var e=enums.get(owner); if(e==null) return null;
int index=0;
for(var c:e.cases()) { if(c.name().equals(label)) return c.explicitValue()==null?index:Math.toIntExact(c.explicitValue()); index++; }
return null;
}
static String path(PbsAst.Expression e) {
if(e instanceof PbsAst.IdentifierExpr i) return i.name();
if(e instanceof PbsAst.MemberExpr m) {var owner=path(m.receiver());return owner==null?null:owner+"."+m.memberName();}
if(e instanceof PbsAst.GroupExpr g) return path(g.expression());
return null;
}
}
@@ -45,6 +45,7 @@ final class PbsExprLiteralSupport {
try {
return Long.parseLong(text);
} catch (NumberFormatException ignored) {
context.report(cursor.previous(), ParseErrors.E_PARSE_EXPECTED_TOKEN, "Integer literal is outside the Int64 range");
return 0L;
}
}
@@ -159,6 +159,11 @@ final class PbsExprParser {
private PbsAst.Expression parseUnary() {
if (cursor.match(PbsTokenKind.BANG, PbsTokenKind.MINUS, PbsTokenKind.NOT)) {
final var operator = cursor.previous();
if (operator.kind() == PbsTokenKind.MINUS && cursor.check(PbsTokenKind.INT_LITERAL)
&& (cursor.peek().lexeme().equals("9223372036854775808") || cursor.peek().lexeme().equals("2147483648"))) {
final var literal = cursor.advance();
return new PbsAst.IntLiteralExpr(Long.parseLong("-" + literal.lexeme()), span(operator.start(), literal.end()));
}
final var right = parseUnary();
return new PbsAst.UnaryExpr(operator.lexeme(), right, span(operator.start(), right.span().getEnd()));
}
@@ -8,7 +8,7 @@ import p.studio.utilities.structures.ReadOnlyList;
import java.util.*;
public final class PbsBuiltinLayoutResolver {
private static final Set<String> BUILTIN_SCALAR_TYPES = Set.of("int", "float", "bool", "str");
private static final Set<String> BUILTIN_SCALAR_TYPES = Set.of("int", "long", "float", "bool", "str");
private enum ResolveState {
UNVISITED,
@@ -357,6 +357,18 @@ public final class PbsDeclarationSemanticsValidator {
validateSdkExecutableExpression(argument, diagnostics);
}
}
case PbsAst.ApplyExpr apply -> {
validateSdkExecutableExpression(apply.callee(), diagnostics);
validateSdkExecutableExpression(apply.argument(), diagnostics);
}
case PbsAst.AsExpr conversion -> validateSdkExecutableExpression(conversion.expression(), diagnostics);
case PbsAst.SwitchExpr switchExpr -> {
validateSdkExecutableExpression(switchExpr.selector(), diagnostics);
for (var arm : switchExpr.arms()) {
for (var statement : arm.block().statements()) validateSdkExecutableStatement(statement, diagnostics);
validateSdkExecutableExpression(arm.block().tailExpression(), diagnostics);
}
}
case PbsAst.MemberExpr memberExpr ->
validateSdkExecutableExpression(memberExpr.receiver(), diagnostics);
case PbsAst.GroupExpr groupExpr ->
@@ -16,7 +16,7 @@ import java.util.*;
import static p.studio.compiler.pbs.semantics.PbsFlowSemanticSupport.*;
public final class PbsEditorialSupportService {
private static final Set<String> BUILTIN_TYPE_NAMES = Set.of("int", "float", "bool", "str", "string", "i32", "i64", "f32", "f64");
private static final Set<String> BUILTIN_TYPE_NAMES = Set.of("int", "long", "float", "bool", "str", "string", "i32", "i64", "f32", "f64");
private static final List<String> KEYWORDS = List.of(
"fn", "declare", "let", "const", "global", "struct", "service", "host", "contract", "enum", "error", "callback",
"if", "else", "switch", "for", "until", "step", "while", "break", "continue", "return",
@@ -29,15 +29,19 @@ final class PbsFlowCallableResolutionAnalyzer {
final PbsFlowExpressionContext context) {
final var callee = analyzeTargetExpression(callExpr.callee(), context, ExprUse.CALL_TARGET);
final var expectedInputs = callee.callables().size() == 1 ? callee.callables().getFirst().inputTypes() : java.util.List.<TypeView>of();
final TypeView argumentType;
if (callExpr.arguments().isEmpty()) {
argumentType = TypeView.unit();
} else if (callExpr.arguments().size() == 1) {
argumentType = analyzeValueExpression(callExpr.arguments().getFirst(), context, null).type();
argumentType = analyzeValueExpression(callExpr.arguments().getFirst(), context, expectedInputs.size() == 1 ? expectedInputs.getFirst() : null).type();
} else {
final var fields = new ArrayList<TupleField>(callExpr.arguments().size());
int argumentIndex = 0;
for (final var argument : callExpr.arguments()) {
final var itemType = analyzeValueExpression(argument, context, null).type();
final var expected = argumentIndex < expectedInputs.size() ? expectedInputs.get(argumentIndex) : null;
argumentIndex++;
final var itemType = analyzeValueExpression(argument, context, expected).type();
fields.add(new TupleField(null, itemType));
}
argumentType = TypeView.tuple(fields);
@@ -56,7 +60,27 @@ final class PbsFlowCallableResolutionAnalyzer {
final PbsAst.ApplyExpr applyExpr,
final PbsFlowExpressionContext context) {
final var callee = analyzeTargetExpression(applyExpr.callee(), context, ExprUse.APPLY_TARGET);
final var argument = analyzeValueExpression(applyExpr.argument(), context, null).type();
TypeView argument;
if (applyExpr.argument() instanceof PbsAst.TupleExpr tuple && !tuple.items().isEmpty()
&& tuple.items().getFirst().label() != null && callee.callables().size() == 1) {
var candidate = callee.callables().getFirst();
var byName = new java.util.HashMap<String, TypeView>();
for (var item : tuple.items()) {
var parameter = candidate.parameters().stream().filter(p -> p.name().equals(item.label())).findFirst().orElse(null);
if (parameter == null || byName.containsKey(item.label())) {
Diagnostics.error(context.diagnostics(), "E_SEM_NAMED_ARGUMENT", "Unknown or duplicate named argument: " + item.label(), item.span());
}
byName.put(item.label(), analyzeValueExpression(item.expression(), context, parameter == null ? null : parameter.type()).type());
}
var fields = new ArrayList<TupleField>();
for (var parameter : candidate.parameters()) {
if (!byName.containsKey(parameter.name())) Diagnostics.error(context.diagnostics(), "E_SEM_NAMED_ARGUMENT", "Missing named argument: " + parameter.name(), applyExpr.span());
fields.add(new TupleField(parameter.name(), byName.getOrDefault(parameter.name(), TypeView.unknown())));
}
argument = TypeView.tuple(fields);
} else {
argument = analyzeValueExpression(applyExpr.argument(), context, callee.callables().size() == 1 && callee.callables().getFirst().inputTypes().size() == 1 ? callee.callables().getFirst().inputTypes().getFirst() : null).type();
}
return resolveCallableApplication(
applyExpr.span(),
@@ -35,6 +35,7 @@ final class PbsFlowSemanticSupport {
UNKNOWN,
UNIT,
INT,
LONG,
FLOAT,
BOOL,
STR,
@@ -77,6 +78,10 @@ final class PbsFlowSemanticSupport {
return new TypeView(Kind.INT, "int", List.of(), null, null, List.of(), null);
}
static TypeView longType() {
return new TypeView(Kind.LONG, "long", List.of(), null, null, List.of(), null);
}
static TypeView floatType() {
return new TypeView(Kind.FLOAT, "float", List.of(), null, null, List.of(), null);
}
@@ -543,6 +548,9 @@ final class PbsFlowSemanticSupport {
case UNIT -> TypeView.unit();
case SELF, ERROR -> TypeView.unknown();
case SIMPLE -> {
if ("long".equals(typeRef.name())) {
yield TypeView.longType();
}
if ("int".equals(typeRef.name())) {
yield TypeView.intType();
}
@@ -41,7 +41,11 @@ final class PbsFlowStructuralExpressionAnalyzer {
final var model = context.model();
final var diagnostics = context.diagnostics();
if (expression instanceof PbsAst.IntLiteralExpr) {
if (expression instanceof PbsAst.IntLiteralExpr literal) {
if (expectedType != null && expectedType.kind() == Kind.LONG) return ExprResult.type(TypeView.longType());
if (literal.value() < Integer.MIN_VALUE || literal.value() > Integer.MAX_VALUE) {
Diagnostics.error(diagnostics, "E_SEM_INTEGER_RANGE", "Integer literal exceeds int range; use an explicit long context", literal.span());
}
return ExprResult.type(TypeView.intType());
}
if (expression instanceof PbsAst.FloatLiteralExpr) {
@@ -119,8 +123,11 @@ final class PbsFlowStructuralExpressionAnalyzer {
}
if (expression instanceof PbsAst.TupleExpr tupleExpr) {
final var fields = new ArrayList<TupleField>(tupleExpr.items().size());
int itemIndex=0;
for (final var item : tupleExpr.items()) {
final var value = analyzeValueExpression(item.expression(), context, null).type();
var fieldExpected=expectedType != null && expectedType.kind()==Kind.TUPLE && itemIndex<expectedType.tupleFields().size() ? expectedType.tupleFields().get(itemIndex).type() : null;
itemIndex++;
final var value = analyzeValueExpression(item.expression(), context, fieldExpected).type();
fields.add(new TupleField(item.label(), value));
}
return ExprResult.type(TypeView.tuple(fields));
@@ -129,18 +136,22 @@ final class PbsFlowStructuralExpressionAnalyzer {
return ExprResult.type(blockAnalysisDelegate.analyze(blockExpr.block(), context, context.valueContext()));
}
if (expression instanceof PbsAst.UnaryExpr unaryExpr) {
final var operand = analyzeValueExpression(unaryExpr.expression(), context, null).type();
final var operand = analyzeValueExpression(unaryExpr.expression(), context, expectedType).type();
if ("!".equals(unaryExpr.operator()) || "not".equals(unaryExpr.operator())) {
return ExprResult.type(TypeView.bool());
}
if ("-".equals(unaryExpr.operator()) && (typeOps.isInt(operand) || typeOps.isFloat(operand))) {
if ("-".equals(unaryExpr.operator()) && (typeOps.isInt(operand) || operand.kind() == Kind.LONG || typeOps.isFloat(operand))) {
return ExprResult.type(operand);
}
return ExprResult.type(TypeView.unknown());
}
if (expression instanceof PbsAst.BinaryExpr binaryExpr) {
final var left = analyzeValueExpression(binaryExpr.left(), context, null).type();
final var right = analyzeValueExpression(binaryExpr.right(), context, null).type();
final var left = analyzeValueExpression(binaryExpr.left(), context, expectedType != null && expectedType.kind()==Kind.LONG ? expectedType : null).type();
final var right = analyzeValueExpression(binaryExpr.right(), context, expectedType != null && expectedType.kind()==Kind.LONG ? expectedType : null).type();
if ((left.kind() == Kind.LONG || right.kind() == Kind.LONG) && left.kind() != right.kind()
&& left.kind() != Kind.UNKNOWN && right.kind() != Kind.UNKNOWN) {
Diagnostics.error(diagnostics, "E_SEM_NUMERIC_TYPE_MISMATCH", "Mixed numeric types require an explicit as conversion", binaryExpr.span());
}
return ExprResult.type(typeOps.inferBinaryResult(binaryExpr.operator(), left, right));
}
if (expression instanceof PbsAst.NoneExpr noneExpr) {
@@ -167,7 +178,13 @@ final class PbsFlowStructuralExpressionAnalyzer {
return ExprResult.type(TypeView.unknown());
}
if (expression instanceof PbsAst.AsExpr asExpr) {
analyzeValueExpression(asExpr.expression(), context, null);
final var source = analyzeValueExpression(asExpr.expression(), context, null).type();
if ("int".equals(asExpr.contractName()) || "long".equals(asExpr.contractName()) || "float".equals(asExpr.contractName())) {
if (source.kind() != Kind.INT && source.kind() != Kind.LONG && source.kind() != Kind.FLOAT && source.kind() != Kind.UNKNOWN) {
Diagnostics.error(diagnostics, "E_SEM_NUMERIC_TYPE_MISMATCH", "Numeric conversion requires a numeric operand", asExpr.span());
}
return ExprResult.type(typeOps.typeFromTypeRef(PbsAst.TypeRef.simple(asExpr.contractName(), asExpr.span()), model, null));
}
if (model.contracts.containsKey(asExpr.contractName())) {
return ExprResult.type(TypeView.contract(asExpr.contractName()));
}
@@ -15,6 +15,9 @@ final class PbsFlowTypeOps {
if (isFloat(left) || isFloat(right)) {
return TypeView.floatType();
}
if (left.kind() == Kind.LONG && right.kind() == Kind.LONG) {
return TypeView.longType();
}
if (isInt(left) && isInt(right)) {
return TypeView.intType();
}
@@ -46,7 +49,7 @@ final class PbsFlowTypeOps {
return false;
}
return switch (actual.kind()) {
case UNIT, INT, FLOAT, BOOL, STR -> true;
case UNIT, INT, LONG, FLOAT, BOOL, STR -> true;
case STRUCT, SERVICE, CONTRACT, CALLBACK, ENUM, ERROR, TYPE_REF, ASSET_NAMESPACE -> actual.name().equals(expected.name());
case ADDRESSABLE -> true;
case OPTIONAL -> compatible(actual.inner(), expected.inner());
@@ -116,7 +119,7 @@ final class PbsFlowTypeOps {
}
boolean isScalarComparable(final TypeView type) {
return isBool(type) || isInt(type) || isFloat(type) || isStr(type);
return type.kind() == Kind.LONG || isBool(type) || isInt(type) || isFloat(type) || isStr(type);
}
boolean isUnit(final TypeView type) {
@@ -172,6 +175,9 @@ final class PbsFlowTypeOps {
}
private TypeView simpleType(final String name, final Model model) {
if ("long".equals(name)) {
return TypeView.longType();
}
if ("int".equals(name)) {
return TypeView.intType();
}
@@ -11,7 +11,7 @@ final class PbsInlineHintSurfaceFormatter {
return switch (type.kind()) {
case UNKNOWN, ASSET_NAMESPACE -> null;
case UNIT -> "void";
case INT, FLOAT, BOOL, STR -> type.name();
case INT, LONG, FLOAT, BOOL, STR -> type.name();
case STRUCT,
SERVICE,
CONTRACT,
@@ -315,7 +315,7 @@ final class PbsImportedSemanticContextService {
}
private boolean isPrimitiveTypeName(final String typeName) {
return "int".equals(typeName)
return "long".equals(typeName) || "int".equals(typeName)
|| "float".equals(typeName)
|| "bool".equals(typeName)
|| "str".equals(typeName)
@@ -3,7 +3,7 @@ Represents a packed RGBA color.
""")]
[BuiltinType(name = "color", version = 1)]
declare builtin type Color(
pub raw: int
pub raw: long
) {
[Doc(markdown = """
Builds a color from its packed integer representation.
@@ -11,7 +11,7 @@ declare builtin type Color(
- `raw`: packed color value.
""")]
[IntrinsicCall(name = "from_raw", version = 1)]
fn from_raw(raw: int) -> Color;
fn from_raw(raw: long) -> Color;
[Doc(markdown = """
Builds an opaque color from red, green, and blue channels.
@@ -21,7 +21,7 @@ declare builtin type Color(
- `b`: blue channel.
""")]
[IntrinsicCall(name = "rgb", version = 1)]
fn rgb(r: int, g: int, b: int) -> Color;
fn rgb(r: long, g: long, b: long) -> Color;
[Doc(markdown = """
Builds a color from red, green, blue, and alpha channels.
@@ -32,7 +32,7 @@ declare builtin type Color(
- `a`: alpha channel.
""")]
[IntrinsicCall(name = "rgba", version = 1)]
fn rgba(r: int, g: int, b: int, a: int) -> Color;
fn rgba(r: long, g: long, b: long, a: long) -> Color;
[Doc(markdown = """
Parses a CSS-style RGBA color string.
@@ -48,19 +48,19 @@ declare builtin type Color(
- `value`: grayscale channel value.
""")]
[IntrinsicCall(name = "gray_scale", version = 1)]
fn gray_scale(value: int) -> Color;
fn gray_scale(value: long) -> Color;
[Doc(markdown = """
Returns the packed RGB portion of this color.
""")]
[IntrinsicCall(name = "hex", version = 1)]
fn hex() -> int;
fn hex() -> long;
[Doc(markdown = """
Returns the alpha channel of this color.
""")]
[IntrinsicCall(name = "alpha", version = 1)]
fn alpha() -> int;
fn alpha() -> long;
}
[Doc(markdown = """
@@ -1,171 +1,205 @@
[Doc(markdown = """
Root input device provider.
""")]
[BuiltinType(name = "input", version = 1)]
declare builtin type InputType() {
[Doc(markdown = """
Returns the gamepad input state.
""")]
[IntrinsicCall(name = "pad", version = 1)]
fn pad() -> InputPad;
[Doc(markdown = """
Returns the touch input state.
""")]
[IntrinsicCall(name = "touch", version = 1)]
fn touch() -> InputTouch;
}
declare enum Button(Up, Down, Left, Right, A, B, X, Y, L, R, Start, Select);
[Doc(markdown = """
Represents the current gamepad state.
Direct zero-argument gamepad queries. Prefer Pad with a typed Button in game code.
""")]
[BuiltinType(name = "input.pad", version = 1)]
declare builtin type InputPad() {
[Doc(markdown = """
Returns the up directional button.
""")]
[IntrinsicCall(name = "up", version = 1)]
fn up() -> InputButton;
[Doc(markdown = """
Returns the down directional button.
""")]
[IntrinsicCall(name = "down", version = 1)]
fn down() -> InputButton;
[Doc(markdown = """
Returns the left directional button.
""")]
[IntrinsicCall(name = "left", version = 1)]
fn left() -> InputButton;
[Doc(markdown = """
Returns the right directional button.
""")]
[IntrinsicCall(name = "right", version = 1)]
fn right() -> InputButton;
[Doc(markdown = """
Returns the A action button.
""")]
[IntrinsicCall(name = "a", version = 1)]
fn a() -> InputButton;
[Doc(markdown = """
Returns the B action button.
""")]
[IntrinsicCall(name = "b", version = 1)]
fn b() -> InputButton;
[Doc(markdown = """
Returns the X action button.
""")]
[IntrinsicCall(name = "x", version = 1)]
fn x() -> InputButton;
[Doc(markdown = """
Returns the Y action button.
""")]
[IntrinsicCall(name = "y", version = 1)]
fn y() -> InputButton;
[Doc(markdown = """
Returns the left shoulder button.
""")]
[IntrinsicCall(name = "l", version = 1)]
fn l() -> InputButton;
[Doc(markdown = """
Returns the right shoulder button.
""")]
[IntrinsicCall(name = "r", version = 1)]
fn r() -> InputButton;
[Doc(markdown = """
Returns the start button.
""")]
[IntrinsicCall(name = "start", version = 1)]
fn start() -> InputButton;
[Doc(markdown = """
Returns the select button.
""")]
[IntrinsicCall(name = "select", version = 1)]
fn select() -> InputButton;
declare builtin type LowPad() {
[IntrinsicCall(name = "input.pad.up.pressed", version = 1)]
fn up_pressed() -> bool;
[IntrinsicCall(name = "input.pad.up.released", version = 1)]
fn up_released() -> bool;
[IntrinsicCall(name = "input.pad.up.down", version = 1)]
fn up_down() -> bool;
[IntrinsicCall(name = "input.pad.up.hold", version = 1)]
fn up_hold() -> long;
[IntrinsicCall(name = "input.pad.down.pressed", version = 1)]
fn down_pressed() -> bool;
[IntrinsicCall(name = "input.pad.down.released", version = 1)]
fn down_released() -> bool;
[IntrinsicCall(name = "input.pad.down.down", version = 1)]
fn down_down() -> bool;
[IntrinsicCall(name = "input.pad.down.hold", version = 1)]
fn down_hold() -> long;
[IntrinsicCall(name = "input.pad.left.pressed", version = 1)]
fn left_pressed() -> bool;
[IntrinsicCall(name = "input.pad.left.released", version = 1)]
fn left_released() -> bool;
[IntrinsicCall(name = "input.pad.left.down", version = 1)]
fn left_down() -> bool;
[IntrinsicCall(name = "input.pad.left.hold", version = 1)]
fn left_hold() -> long;
[IntrinsicCall(name = "input.pad.right.pressed", version = 1)]
fn right_pressed() -> bool;
[IntrinsicCall(name = "input.pad.right.released", version = 1)]
fn right_released() -> bool;
[IntrinsicCall(name = "input.pad.right.down", version = 1)]
fn right_down() -> bool;
[IntrinsicCall(name = "input.pad.right.hold", version = 1)]
fn right_hold() -> long;
[IntrinsicCall(name = "input.pad.a.pressed", version = 1)]
fn a_pressed() -> bool;
[IntrinsicCall(name = "input.pad.a.released", version = 1)]
fn a_released() -> bool;
[IntrinsicCall(name = "input.pad.a.down", version = 1)]
fn a_down() -> bool;
[IntrinsicCall(name = "input.pad.a.hold", version = 1)]
fn a_hold() -> long;
[IntrinsicCall(name = "input.pad.b.pressed", version = 1)]
fn b_pressed() -> bool;
[IntrinsicCall(name = "input.pad.b.released", version = 1)]
fn b_released() -> bool;
[IntrinsicCall(name = "input.pad.b.down", version = 1)]
fn b_down() -> bool;
[IntrinsicCall(name = "input.pad.b.hold", version = 1)]
fn b_hold() -> long;
[IntrinsicCall(name = "input.pad.x.pressed", version = 1)]
fn x_pressed() -> bool;
[IntrinsicCall(name = "input.pad.x.released", version = 1)]
fn x_released() -> bool;
[IntrinsicCall(name = "input.pad.x.down", version = 1)]
fn x_down() -> bool;
[IntrinsicCall(name = "input.pad.x.hold", version = 1)]
fn x_hold() -> long;
[IntrinsicCall(name = "input.pad.y.pressed", version = 1)]
fn y_pressed() -> bool;
[IntrinsicCall(name = "input.pad.y.released", version = 1)]
fn y_released() -> bool;
[IntrinsicCall(name = "input.pad.y.down", version = 1)]
fn y_down() -> bool;
[IntrinsicCall(name = "input.pad.y.hold", version = 1)]
fn y_hold() -> long;
[IntrinsicCall(name = "input.pad.l.pressed", version = 1)]
fn l_pressed() -> bool;
[IntrinsicCall(name = "input.pad.l.released", version = 1)]
fn l_released() -> bool;
[IntrinsicCall(name = "input.pad.l.down", version = 1)]
fn l_down() -> bool;
[IntrinsicCall(name = "input.pad.l.hold", version = 1)]
fn l_hold() -> long;
[IntrinsicCall(name = "input.pad.r.pressed", version = 1)]
fn r_pressed() -> bool;
[IntrinsicCall(name = "input.pad.r.released", version = 1)]
fn r_released() -> bool;
[IntrinsicCall(name = "input.pad.r.down", version = 1)]
fn r_down() -> bool;
[IntrinsicCall(name = "input.pad.r.hold", version = 1)]
fn r_hold() -> long;
[IntrinsicCall(name = "input.pad.start.pressed", version = 1)]
fn start_pressed() -> bool;
[IntrinsicCall(name = "input.pad.start.released", version = 1)]
fn start_released() -> bool;
[IntrinsicCall(name = "input.pad.start.down", version = 1)]
fn start_down() -> bool;
[IntrinsicCall(name = "input.pad.start.hold", version = 1)]
fn start_hold() -> long;
[IntrinsicCall(name = "input.pad.select.pressed", version = 1)]
fn select_pressed() -> bool;
[IntrinsicCall(name = "input.pad.select.released", version = 1)]
fn select_released() -> bool;
[IntrinsicCall(name = "input.pad.select.down", version = 1)]
fn select_down() -> bool;
[IntrinsicCall(name = "input.pad.select.hold", version = 1)]
fn select_hold() -> long;
}
[Doc(markdown = """
Represents the current touch input state.
Queries the selected gamepad button at the time of the call.
""")]
declare service Pad {
[Doc(markdown = """
Queries pressed for the selected button. Only that endpoint is executed.
""")]
fn pressed(button: Button) -> bool {
return switch button {
Button.Up: { LowPad.up_pressed() },
Button.Down: { LowPad.down_pressed() },
Button.Left: { LowPad.left_pressed() },
Button.Right: { LowPad.right_pressed() },
Button.A: { LowPad.a_pressed() },
Button.B: { LowPad.b_pressed() },
Button.X: { LowPad.x_pressed() },
Button.Y: { LowPad.y_pressed() },
Button.L: { LowPad.l_pressed() },
Button.R: { LowPad.r_pressed() },
Button.Start: { LowPad.start_pressed() },
Button.Select: { LowPad.select_pressed() },
};
}
[Doc(markdown = """
Queries released for the selected button. Only that endpoint is executed.
""")]
fn released(button: Button) -> bool {
return switch button {
Button.Up: { LowPad.up_released() },
Button.Down: { LowPad.down_released() },
Button.Left: { LowPad.left_released() },
Button.Right: { LowPad.right_released() },
Button.A: { LowPad.a_released() },
Button.B: { LowPad.b_released() },
Button.X: { LowPad.x_released() },
Button.Y: { LowPad.y_released() },
Button.L: { LowPad.l_released() },
Button.R: { LowPad.r_released() },
Button.Start: { LowPad.start_released() },
Button.Select: { LowPad.select_released() },
};
}
[Doc(markdown = """
Queries down for the selected button. Only that endpoint is executed.
""")]
fn down(button: Button) -> bool {
return switch button {
Button.Up: { LowPad.up_down() },
Button.Down: { LowPad.down_down() },
Button.Left: { LowPad.left_down() },
Button.Right: { LowPad.right_down() },
Button.A: { LowPad.a_down() },
Button.B: { LowPad.b_down() },
Button.X: { LowPad.x_down() },
Button.Y: { LowPad.y_down() },
Button.L: { LowPad.l_down() },
Button.R: { LowPad.r_down() },
Button.Start: { LowPad.start_down() },
Button.Select: { LowPad.select_down() },
};
}
[Doc(markdown = """
Queries hold for the selected button. Only that endpoint is executed.
""")]
fn hold(button: Button) -> long {
return switch button {
Button.Up: { LowPad.up_hold() },
Button.Down: { LowPad.down_hold() },
Button.Left: { LowPad.left_hold() },
Button.Right: { LowPad.right_hold() },
Button.A: { LowPad.a_hold() },
Button.B: { LowPad.b_hold() },
Button.X: { LowPad.x_hold() },
Button.Y: { LowPad.y_hold() },
Button.L: { LowPad.l_hold() },
Button.R: { LowPad.r_hold() },
Button.Start: { LowPad.start_hold() },
Button.Select: { LowPad.select_hold() },
};
}
}
[Doc(markdown = """
Queries the current touch contact and coordinates.
""")]
[BuiltinType(name = "input.touch", version = 1)]
declare builtin type InputTouch() {
[Doc(markdown = """
Returns the touch contact as a button state.
""")]
[IntrinsicCall(name = "button", version = 1)]
fn button() -> InputButton;
[Doc(markdown = """
Returns the current touch x coordinate.
""")]
[IntrinsicCall(name = "x", version = 1)]
fn x() -> int;
[Doc(markdown = """
Returns the current touch y coordinate.
""")]
[IntrinsicCall(name = "y", version = 1)]
fn y() -> int;
}
[Doc(markdown = """
Represents one digital input button.
""")]
[BuiltinType(name = "input.button", version = 1)]
declare builtin type InputButton() {
[Doc(markdown = """
Returns true on the frame where the button becomes down.
""")]
[IntrinsicCall(name = "pressed", version = 1)]
declare builtin type Touch() {
[IntrinsicCall(name = "input.touch.button.pressed", version = 1)]
fn pressed() -> bool;
[Doc(markdown = """
Returns true on the frame where the button becomes up.
""")]
[IntrinsicCall(name = "released", version = 1)]
[IntrinsicCall(name = "input.touch.button.released", version = 1)]
fn released() -> bool;
[Doc(markdown = """
Returns true while the button is currently down.
""")]
[IntrinsicCall(name = "down", version = 1)]
[IntrinsicCall(name = "input.touch.button.down", version = 1)]
fn down() -> bool;
[Doc(markdown = """
Returns how long the button has been held.
""")]
[IntrinsicCall(name = "hold", version = 1)]
fn hold() -> int;
}
[Doc(markdown = """
High-level access to player input devices.
""")]
declare service Input
{
[Doc(markdown = """
Returns the gamepad input state.
""")]
fn pad() -> InputPad
{
return InputType.pad();
}
[Doc(markdown = """
Returns the touch input state.
""")]
fn touch() -> InputTouch
{
return InputType.touch();
}
[IntrinsicCall(name = "input.touch.button.hold", version = 1)]
fn hold() -> long;
[IntrinsicCall(name = "x", version = 1)]
fn x() -> long;
[IntrinsicCall(name = "y", version = 1)]
fn y() -> long;
}
@@ -1,4 +1,4 @@
pub struct InputPad;
pub struct InputTouch;
pub struct InputButton;
pub service Input;
pub enum Button;
pub service Pad;
pub struct Touch;
pub struct LowPad;
@@ -41,6 +41,15 @@ class PbsGateUSdkInterfaceConformanceTest {
@TempDir
Path tempDir;
@Test
void removedInputObjectsExplainTheirMigration() throws IOException {
final var result = compileWorkspaceModule(tempDir.resolve("removed-input"), """
import { Input } from @sdk:input;
fn main() -> void { let button = Input.pad().a(); }
""", "pub fn main() -> void;", 1, null);
assertTrue(result.diagnostics().stream().anyMatch(d -> d.getMessage().contains("migrate to Pad.pressed")));
}
@Test
void gateU_shouldClassifySourceKindForInterfaceDeclarations() {
final var source = """
@@ -88,12 +97,12 @@ class PbsGateUSdkInterfaceConformanceTest {
import { Color } from @core:color;
import { Composer } from @sdk:composer;
import { Gfx } from @sdk:gfx;
import { Input, InputPad, InputButton } from @sdk:input;
import { Pad, Button, Touch } from @sdk:input;
import { Assets } from @sdk:asset;
import { Log } from @sdk:log;
declare contract Renderer {
fn render(composer: Composer, gfx: Gfx, color: Color, input: Input, pad: InputPad, button: InputButton, assets: Assets, log: Log) -> void;
fn render(composer: Composer, gfx: Gfx, color: Color, pad: Pad, button: Button, assets: Assets, log: Log) -> void;
}
""",
"pub contract Renderer;",
@@ -106,12 +115,12 @@ class PbsGateUSdkInterfaceConformanceTest {
assertTrue(positive.irBackend().getReservedMetadata().builtinTypeSurfaces().stream()
.anyMatch(t -> t.sourceTypeName().equals("Color")));
assertTrue(positive.irBackend().getReservedMetadata().builtinTypeSurfaces().stream()
.anyMatch(t -> t.sourceTypeName().equals("InputType") && t.canonicalTypeName().equals("input")));
.anyMatch(t -> t.sourceTypeName().equals("LowPad") && t.canonicalTypeName().equals("input.pad")));
assertFalse(positive.irBackend().getReservedMetadata().builtinConstSurfaces().stream()
.anyMatch(c -> c.canonicalTarget().equals("input")));
assertTrue(positive.irBackend().getReservedMetadata().builtinTypeSurfaces().stream()
.anyMatch(t -> t.sourceTypeName().equals("InputButton")
&& t.intrinsics().stream().anyMatch(i -> i.canonicalName().equals("input.button.hold"))));
.anyMatch(t -> t.sourceTypeName().equals("LowPad")
&& t.intrinsics().stream().anyMatch(i -> i.canonicalName().equals("input.pad.a.hold"))));
assertTrue(positive.irBackend().getReservedMetadata().hostMethodBindings().stream()
.anyMatch(h -> h.ownerName().equals("LowGfx")
&& h.abiModule().equals("gfx2d")
@@ -133,11 +133,11 @@ final class PbsSemanticPresentationContractTest {
@Test
void shouldClassifyBuiltinTypesExposedByImportedStdlibModules() {
final List<FrontendSemanticToken> semanticTokens = PBSDefinitions.PBS.getSemanticTokenProvider().tokenize("""
import { Input } from @sdk:input;
import { Pad, Button, Touch } from @sdk:input;
fn main() -> void {
let touch : InputTouch = Input.touch();
let pad : InputPad = Input.pad();
let touch : long = Touch.x();
let held : long = Pad.hold(Button.A);
}
""");
@@ -1152,8 +1152,8 @@ class PBSFrontendPhaseServiceTest {
.toList();
assertTrue(intrinsicNames.contains("color.rgba"), "intrinsics=" + intrinsicNames);
assertTrue(intrinsicNames.contains("color.html_rgba"), "intrinsics=" + intrinsicNames);
assertTrue(intrinsicNames.contains("color.red"), "intrinsics=" + intrinsicNames);
assertTrue(intrinsicNames.contains("color.transparent"), "intrinsics=" + intrinsicNames);
assertTrue(irBackend.getExecutableFunctions().stream().flatMap(f -> f.instructions().stream()).anyMatch(i -> i.kind() == IRBackendExecutableFunction.InstructionKind.BUILTIN_CONST && i.label().equals("color.red@1")));
assertTrue(irBackend.getExecutableFunctions().stream().flatMap(f -> f.instructions().stream()).anyMatch(i -> i.kind() == IRBackendExecutableFunction.InstructionKind.BUILTIN_CONST && i.label().equals("color.transparent@1")));
}
@Test
@@ -1647,7 +1647,7 @@ class PBSFrontendPhaseServiceTest {
}
@Test
void shouldResolveImportedBuiltinTypeChainsInExpressionFlowSemantics() throws IOException {
void shouldResolveImportedPadFacadeAndTypedButton() throws IOException {
final var projectRoot = tempDir.resolve("project-builtin-chain");
final var sourceRoot = projectRoot.resolve("src");
Files.createDirectories(sourceRoot);
@@ -1656,12 +1656,12 @@ class PBSFrontendPhaseServiceTest {
final var modBarrel = sourceRoot.resolve("mod.barrel");
Files.writeString(sourceFile, """
import { Log } from @sdk:log;
import { Input } from @sdk:input;
import { Pad, Button, Touch } from @sdk:input;
[Frame]
fn frame() -> void
{
if (Input.pad().a().pressed())
if (Pad.pressed(Button.A))
{
Log.debug("Hello World!");
}
@@ -1722,23 +1722,11 @@ class PBSFrontendPhaseServiceTest {
.filter(instruction ->
instruction.kind() == p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC)
.toList();
final var inputPadExecutable = irBackend.getExecutableFunctions().stream()
.filter(function -> "Input.pad".equals(function.callableName()))
.findFirst()
.orElseThrow();
final var inputPadIntrinsics = inputPadExecutable.instructions().stream()
.filter(instruction ->
instruction.kind() == p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC
&& instruction.intrinsicCall() != null)
.map(instruction -> instruction.intrinsicCall().canonicalName())
.toList();
assertTrue(callableCalls.contains("Input.pad"));
assertTrue(intrinsicCalls.stream().anyMatch(instruction -> Integer.valueOf(1).equals(instruction.expectedArgSlots())));
assertTrue(inputPadIntrinsics.contains("input.pad"));
assertTrue(intrinsicCalls.stream().anyMatch(instruction ->
instruction.intrinsicCall() != null && "input.pad.a".equals(instruction.intrinsicCall().canonicalName())));
assertTrue(intrinsicCalls.stream().anyMatch(instruction ->
instruction.intrinsicCall() != null && "input.button.pressed".equals(instruction.intrinsicCall().canonicalName())));
assertTrue(callableCalls.contains("Pad.pressed"));
assertTrue(intrinsicCalls.isEmpty());
final var pad = irBackend.getExecutableFunctions().stream().filter(f -> f.callableName().equals("Pad.pressed")).findFirst().orElseThrow();
assertEquals(12, pad.instructions().stream().filter(i -> i.intrinsicCall() != null).count());
assertTrue(pad.instructions().stream().filter(i -> i.intrinsicCall() != null).allMatch(i -> i.expectedArgSlots() == 0));
assertTrue(
irBackend.getExecutableFunctions().stream().anyMatch(function -> "frame".equals(function.callableName())),
"diagnostics="
@@ -1748,7 +1736,7 @@ class PBSFrontendPhaseServiceTest {
}
@Test
void shouldResolveIntrinsicChainsWithMethodNameCollisionsByOwnerIdentity() throws IOException {
void shouldResolvePadAndTouchQueriesByOwnerIdentity() throws IOException {
final var projectRoot = tempDir.resolve("project-intrinsic-owner-collision");
final var sourceRoot = projectRoot.resolve("src");
Files.createDirectories(sourceRoot);
@@ -1756,13 +1744,13 @@ class PBSFrontendPhaseServiceTest {
final var sourceFile = sourceRoot.resolve("main.pbs");
final var modBarrel = sourceRoot.resolve("mod.barrel");
Files.writeString(sourceFile, """
import { Input } from @sdk:input;
import { Pad, Button, Touch } from @sdk:input;
[Frame]
fn frame() -> void
{
Input.pad().x().pressed();
Input.touch().x();
Pad.pressed(Button.X);
Touch.x();
}
""");
Files.writeString(modBarrel, "pub fn frame() -> void;");
@@ -1811,37 +1799,16 @@ class PBSFrontendPhaseServiceTest {
&& instruction.intrinsicCall() != null)
.map(instruction -> instruction.intrinsicCall().canonicalName())
.toList();
final var inputPadExecutable = irBackend.getExecutableFunctions().stream()
.filter(function -> "Input.pad".equals(function.callableName()))
.findFirst()
.orElseThrow();
final var inputTouchExecutable = irBackend.getExecutableFunctions().stream()
.filter(function -> "Input.touch".equals(function.callableName()))
.findFirst()
.orElseThrow();
final var inputPadIntrinsics = inputPadExecutable.instructions().stream()
.filter(instruction ->
instruction.kind() == p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC
&& instruction.intrinsicCall() != null)
.map(instruction -> instruction.intrinsicCall().canonicalName())
.toList();
final var inputTouchIntrinsics = inputTouchExecutable.instructions().stream()
.filter(instruction ->
instruction.kind() == p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC
&& instruction.intrinsicCall() != null)
.map(instruction -> instruction.intrinsicCall().canonicalName())
.toList();
assertTrue(callableCalls.contains("Input.pad"));
assertTrue(callableCalls.contains("Input.touch"));
assertTrue(inputPadIntrinsics.contains("input.pad"));
assertTrue(intrinsicCalls.contains("input.pad.x"));
assertTrue(intrinsicCalls.contains("input.button.pressed"));
assertTrue(inputTouchIntrinsics.contains("input.touch"));
assertTrue(callableCalls.contains("Pad.pressed"));
assertTrue(intrinsicCalls.contains("input.touch.x"));
assertFalse(intrinsicCalls.contains("input.pad"));
final var pad = irBackend.getExecutableFunctions().stream().filter(f -> f.callableName().equals("Pad.pressed")).findFirst().orElseThrow();
assertTrue(pad.instructions().stream().anyMatch(i -> i.intrinsicCall() != null && i.intrinsicCall().canonicalName().equals("input.pad.x.pressed")));
}
@Test
void shouldResolveIntrinsicCallsOnBuiltinValuesStoredInLocals() throws IOException {
void shouldPassStoredButtonValuesToPadQueries() throws IOException {
final var projectRoot = tempDir.resolve("project-intrinsic-local-builtin-receiver");
final var sourceRoot = projectRoot.resolve("src");
Files.createDirectories(sourceRoot);
@@ -1849,14 +1816,14 @@ class PBSFrontendPhaseServiceTest {
final var sourceFile = sourceRoot.resolve("main.pbs");
final var modBarrel = sourceRoot.resolve("mod.barrel");
Files.writeString(sourceFile, """
import { Input } from @sdk:input;
import { Pad, Button, Touch } from @sdk:input;
[Frame]
fn frame() -> void
{
let touch = Input.touch();
touch.x();
touch.y();
let button = Button.A;
Pad.pressed(button);
Touch.y();
}
""");
Files.writeString(modBarrel, "pub fn frame() -> void;");
@@ -1905,20 +1872,10 @@ class PBSFrontendPhaseServiceTest {
&& instruction.intrinsicCall() != null)
.map(instruction -> instruction.intrinsicCall().canonicalName())
.toList();
final var inputTouchExecutable = irBackend.getExecutableFunctions().stream()
.filter(function -> "Input.touch".equals(function.callableName()))
.findFirst()
.orElseThrow();
final var inputTouchIntrinsics = inputTouchExecutable.instructions().stream()
.filter(instruction ->
instruction.kind() == p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC
&& instruction.intrinsicCall() != null)
.map(instruction -> instruction.intrinsicCall().canonicalName())
.toList();
assertTrue(callableCalls.contains("Input.touch"));
assertTrue(inputTouchIntrinsics.contains("input.touch"));
assertTrue(intrinsicCalls.contains("input.touch.x"));
assertTrue(callableCalls.contains("Pad.pressed"));
assertTrue(intrinsicCalls.contains("input.touch.y"));
assertFalse(intrinsicCalls.contains("input.touch"));
}
@Test
@@ -3,6 +3,7 @@ plugins {
}
dependencies {
testImplementation(project(":prometeu-compiler:frontends:prometeu-frontend-pbs"))
api(project(":prometeu-infra"))
implementation(project(":prometeu-compiler:prometeu-deps"))
implementation(project(":prometeu-compiler:prometeu-compiler-core"))
@@ -94,6 +94,28 @@ public class LowerToIRVMService {
operations.add(BytecodeEmitter.Operation.pushI32(value, sourceSpan));
functionPc += IRVMOp.PUSH_I32.immediateSize() + 2;
}
case PUSH_I64, PUSH_F64, BUILTIN_CONST -> {
final java.util.List<BytecodeModule.ConstantPoolEntry> entries;
if (instr.kind() == IRBackendExecutableFunction.InstructionKind.BUILTIN_CONST) {
var key = instr.label().split("@", 2);
int dot = key[0].lastIndexOf('.');
entries = IRVMBuiltinConstantDefinition.resolve(key[0].substring(0, dot), key[0].substring(dot + 1), Long.parseLong(key[1]))
.orElseThrow(() -> new IllegalArgumentException("Unknown builtin constant: " + instr.label())).materialize().asList();
} else {
entries = java.util.List.of(instr.kind() == IRBackendExecutableFunction.InstructionKind.PUSH_I64
? new BytecodeModule.Int64Constant(Long.parseLong(instr.label()))
: new BytecodeModule.Float64Constant(Double.parseDouble(instr.label())));
}
if (instr.kind() == IRBackendExecutableFunction.InstructionKind.BUILTIN_CONST && entries.size() != instr.expectedRetSlots())
throw new IllegalArgumentException("Builtin constant group width differs from declared type: " + instr.label());
for (var value : entries) {
int index = constPool.indexOf(value);
if (index < 0) { index = constPool.size(); constPool.add(value); }
instructions.add(new IRVMInstruction(IRVMOp.PUSH_CONST, index));
operations.add(BytecodeEmitter.Operation.pushConst(index, sourceSpan));
functionPc += IRVMOp.PUSH_CONST.immediateSize() + 2;
}
}
case PUSH_CONST -> {
final var value = instr.label() == null ? "" : instr.label();
final var constPoolIndex = constPoolIndexByString.computeIfAbsent(value, ignored -> {
@@ -0,0 +1,124 @@
package p.studio.compiler.backend.irvm;
import org.junit.jupiter.api.Test;
import p.studio.compiler.pbs.PbsFrontendCompiler;
import p.studio.compiler.models.IRBackend;
import p.studio.compiler.backend.bytecode.*;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.identifiers.FileId;
import p.studio.compiler.models.SourceKind;
import java.nio.file.*;
import static org.junit.jupiter.api.Assertions.*;
class PbsRuntimeAlignmentTest {
private static String sdk(String path) throws Exception {
try(var stream = PbsFrontendCompiler.class.getResourceAsStream("/game/stdlib/1/"+path+"/main.pbs")) {
assertNotNull(stream); return new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
}
}
private static BytecodeModule compile(String name,String source) throws Exception {
var diagnostics=DiagnosticSink.empty();
var fileId = new FileId(0);
var ast = p.studio.compiler.pbs.parser.PbsParser.parse(p.studio.compiler.pbs.lexer.PbsLexer.lex(source,fileId,diagnostics),fileId,diagnostics,p.studio.compiler.pbs.parser.PbsParser.ParseMode.INTERFACE_MODULE);
var file=new PbsFrontendCompiler().compileParsedFile(fileId,ast,diagnostics,SourceKind.SDK_INTERFACE,
new p.studio.compiler.source.identifiers.ModuleId(0),p.studio.utilities.structures.ReadOnlyList.empty(),
p.studio.compiler.messages.HostAdmissionContext.permissiveDefault(),p.studio.compiler.messages.FESurfaceContext.empty(),new p.studio.compiler.source.tables.NameTable());
assertFalse(diagnostics.hasErrors(), ()->diagnostics.stream().map(d->d.getCode()+":"+d.getMessage()).toList().toString());
var backend=IRBackend.builder().entryPointCallableName("Probe.main").entryPointModuleId(new p.studio.compiler.source.identifiers.ModuleId(0)).executableFunctions(file.executableFunctions())
.globals(file.globals()).registry(file.registry()).intrinsicPool(file.intrinsicPool()).callableSignatures(file.callableSignatures()).build();
var program=new LowerToIRVMService().lower(backend);
var module=new BytecodeEmitter().emit(program.coherentEmissionPlan());
new BytecodePreloadVerifierService().verify(module);
var directory=Path.of("build/registry-conformance");Files.createDirectories(directory);
Files.write(directory.resolve("pbs-"+name+".pbx"),module.serialize());
return module;
}
@Test void numericValuesAndExplicitConversionsReachProductionPbx() throws Exception {
compile("numeric", """
declare service Probe {
fn widen(value: int) -> long { return value as long; }
fn contextual() -> long { return 1; }
fn receive(value: long) -> long { return value; }
fn main() -> long {
let large: long = 2147483648;
let maximum: long = 9223372036854775807;
Probe.contextual();
Probe.receive(2147483648);
return large + Probe.widen(7);
}
}
""");
compile("narrow", "declare service Probe { fn main() -> int { let value: long = 2147483648; return value as int; } }");
compile("float", "declare service Probe { fn main() -> float { return 1.5 + 2.25; } }");
compile("overflow", "declare service Probe { fn main() -> int { return 2147483647 + 1; } }");
}
@Test void allInputQueriesCompileFromThePublishedFacade() throws Exception {
var input=sdk("sdk/input");
for (var button : new String[]{"Up","Down","Left","Right","A","B","X","Y","L","R","Start","Select"}) {
for(var query:new String[]{"pressed","released","down","hold"}) {
var type=query.equals("hold")?"long":"bool";
compile("pad-"+button.toLowerCase()+"-"+query,input+"\ndeclare service Probe { fn select(button: Button) -> Button { return button; } fn main() -> "+type+" { let button = Probe.select(Button."+button+"); return Pad."+query+"(button); } }");
compile("pad-"+button.toLowerCase()+"-"+query+"-constant", input+"\ndeclare service Probe { fn main() -> "+type+" { return Pad."+query+"(Button."+button+"); } }");
}
}
for(var query:new String[]{"pressed","released","down","hold","x","y"}) {
var type=java.util.Set.of("hold","x","y").contains(query)?"long":"bool";
compile("touch-"+query,input+"\ndeclare service Probe { fn main() -> "+type+" { return Touch."+query+"(); } }");
}
}
@Test void completeBuiltinAndTupleGroupsReachProductionPbx() throws Exception {
compile("vec2", """
[BuiltinType(name = "vec2", version = 1)]
declare builtin type Vector(pub x: float, pub y: float) {}
[BuiltinConst(target = "vec2", name = "zero", version = 1)]
declare const ZERO: Vector;
declare service Probe {
fn echo(value: Vector) -> Vector { return value; }
fn main() -> Vector { let vector = Probe.echo(ZERO); return vector; }
}
""");
compile("tuple", """
declare service Probe {
fn pair() -> (x: int, y: long) { return (x: 7, y: 8 as long); }
fn main() -> (x: int, y: long) { let pair = Probe.pair(); return pair; }
}
""");
compile("named", """
declare global trace: int = 0;
declare service Probe {
fn x() -> int { trace = trace * 10 + 1; return 10; }
fn y() -> int { trace = trace * 10 + 2; return 20; }
fn combine(x: int, y: int) -> int { return x * 100 + y; }
fn main() -> int {
trace = 0;
let value = Probe.combine apply (y: Probe.y(), x: Probe.x());
return trace * 10000 + value;
}
}
""");
compile("color", sdk("core/color") + "declare service Probe { fn echo(value: Color) -> Color { return value; } fn main() -> Color { return Probe.echo(RED); } }");
compile("pixel", sdk("core/color") + """
[BuiltinType(name = "pixel", version = 1)]
declare builtin type Pixel(pub x: long, pub y: long, pub color: Color) {}
declare service Probe {
fn echo(value: Pixel) -> Pixel { return value; }
fn main() -> Pixel { let value = new Pixel(12, -34, RED); return Probe.echo(value); }
}
""");
compile("string", "declare service Probe { fn echo(value: str) -> str { return value; } fn main() -> str { return Probe.echo(\"hello\"); } }");
compile("division", "declare service Probe { fn main() -> int { return 1 / 0; } }");
compile("minimum", "declare service Probe { fn main() -> long { return -9223372036854775808; } }");
}
@Test void wrongNumericAndButtonTypesAreRejected() throws Exception {
for(var expression:new String[]{"1","1 as long","true","Other.A","\"A\""}) {
var diagnostics=DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0),sdk("sdk/input")+"\ndeclare enum Other(A); declare service Probe { fn main() -> bool { return Pad.pressed("+expression+"); } }",diagnostics,SourceKind.SDK_INTERFACE);
assertTrue(diagnostics.hasErrors());
}
for(var source:new String[]{"fn main() -> long { let x: long = 1; let y: int = 1; return x + y; }", "fn main() -> int { return 2147483648; }", "fn main() -> long { return 9223372036854775808; }"}) {
var diagnostics=DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0),source,diagnostics);
assertTrue(diagnostics.hasErrors());
}
}
}
@@ -255,7 +255,12 @@ public record IRBackendExecutableFunction(
case REGISTRY -> {
if (hostCall != null || intrinsicCall != null || calleeCallableId != null || !label.isEmpty() || !targetLabel.isEmpty()) throw new IllegalArgumentException("unexpected Registry instruction metadata");
}
case PUSH_I32 -> {
case BUILTIN_CONST -> {
if (label.isBlank() || expectedRetSlots == null || expectedRetSlots <= 0 || expectedArgSlots != null
|| !targetLabel.isBlank() || !calleeCallableName.isBlank() || calleeCallableId != null || hostCall != null || intrinsicCall != null)
throw new IllegalArgumentException("BUILTIN_CONST requires canonical identity and complete result width");
}
case PUSH_I32, PUSH_I64, PUSH_F64 -> {
if (label.isBlank()) {
throw new IllegalArgumentException("PUSH_I32 requires immediate label payload");
}
@@ -426,6 +431,9 @@ public record IRBackendExecutableFunction(
public enum InstructionKind {
REGISTRY,
PUSH_I32,
PUSH_I64,
PUSH_F64,
BUILTIN_CONST,
PUSH_BOOL,
PUSH_CONST,
GET_LOCAL,