feat(pbs): add parametric arrays and concrete generic contracts

Support explicit contract type parameters, canonical nominal applications,
recursive substitution, concrete implementations and instantiated editor views.
Complete parametric Array syntax and contextual construction integration.

Preserve type origins across imports and reexports, fix trait argument stack
order, and relocate global slots before lifecycle assembly. Publish specs,
installed examples and consolidated discussion lessons.

Validate frontend, common pipeline, architecture, LSP and installed knowledge
gates, plus the full production VM conformance corpus with 14 generic fixtures.
This commit is contained in:
2026-10-20 11:30:00 +01:00
parent b62db87245
commit 240216170c
70 changed files with 2369 additions and 273 deletions
@@ -0,0 +1,175 @@
package p.studio.compiler.pbs;
import org.junit.jupiter.api.Test;
import p.studio.compiler.models.IRBackendFile;
import p.studio.compiler.models.registry.IRRegistry;
import p.studio.compiler.pbs.lexer.PbsLexer;
import p.studio.compiler.pbs.parser.PbsBarrelParser;
import p.studio.compiler.pbs.ast.PbsAst;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.identifiers.FileId;
import static org.junit.jupiter.api.Assertions.*;
class PbsGenericContractsTest {
private static final String IDENTITY = """
declare contract Identity<T> { fn hash(e: T) -> int; fn equals(a: T, b: T) -> bool; }
declare service IntIdentity {}
implements Identity<int> for IntIdentity using strategy {
fn hash(e: int) -> int { return e; }
fn equals(a: int, b: int) -> bool { return a == b; }
}
""";
private IRBackendFile compile(String source) {
var diagnostics = DiagnosticSink.empty();
var file = new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode() + ": " + d.getMessage()).toList().toString());
return file;
}
private void rejects(String source, String code) {
var diagnostics = DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
assertTrue(diagnostics.stream().anyMatch(d -> d.getCode().equals(code)), () -> diagnostics.stream().map(d -> d.getCode() + ": " + d.getMessage()).toList().toString());
}
@Test void explicitAndContextualApplicationsProduceConcreteTraits() {
var file = compile(IDENTITY + """
fn select(value: Identity<int>) -> Identity<int> { return value; }
fn demo() -> bool {
let identity: Identity<int> = IntIdentity;
let explicit = IntIdentity as Identity<int>;
return select(identity).equals(7, explicit.hash(7));
}
""");
var traits = file.registry().types().stream().filter(t -> t.body() instanceof IRRegistry.Trait).toList();
assertEquals(1, traits.size());
assertEquals("Identity<int>", traits.getFirst().name());
assertEquals(1, file.registry().implementations().size());
}
@Test void sameOwnerHasTwoIndependentApplications() {
var file = compile("""
declare contract Echo<T> { fn echo(value: T) -> T; }
declare service Strategy {}
implements Echo<int> for Strategy using s { fn echo(value: int) -> int { return value; } }
implements Echo<bool> for Strategy using s { fn echo(value: bool) -> bool { return value; } }
fn demo() -> int {
let ints: Echo<int> = Strategy;
let flags: Echo<bool> = Strategy;
if flags.echo(true) { return ints.echo(42); }
return 0;
}
""");
assertEquals(2, file.registry().implementations().size());
assertNotEquals(file.registry().implementations().get(0).trait(), file.registry().implementations().get(1).trait());
assertEquals(2, file.executableFunctions().stream().filter(f -> f.callableName().contains(".$impl.")).count());
}
@Test void multipleParametersAndComposedSignaturesAreSubstituted() {
compile("""
declare contract Convert<A, B> { fn convert(value: A) -> B; }
declare service Strategy {}
implements Convert<array<int>, (left: int, right: int)> for Strategy using s {
fn convert(value: array<int>) -> (left: int, right: int) { return (left: value[0] else 0, right: 2); }
}
fn demo() -> int {
let converter: Convert<array<int>, (left: int, right: int)> = Strategy;
let pair = converter.convert([40]);
return pair.left + pair.right;
}
""");
}
@Test void phantomArgumentsAndSharedArrayStorageRemainNominallyDistinct() {
var file = compile("""
declare contract Marker<T> {}
declare service Strategy {}
implements Marker<array<int>> for Strategy using s {}
implements Marker<array<bool>> for Strategy using s {}
fn demo() -> int {
let a: Marker<array<int>> = Strategy;
let b: Marker<array<bool>> = Strategy;
return 42;
}
""");
assertEquals(2, file.registry().types().stream().filter(t -> t.body() instanceof IRRegistry.Trait).count());
assertEquals(2, file.registry().implementations().size());
}
@Test void finiteRecursiveSignatureHasANominalAnchor() {
var file = compile("""
declare contract Node<T> { fn next() -> Node<T>; }
fn identity(value: Node<int>) -> Node<int> { return value; }
""");
assertEquals(1, file.registry().types().stream().filter(t -> t.body() instanceof IRRegistry.Trait).count());
}
@Test void expandingRecursiveSignatureIsDiagnosed() {
rejects("""
declare contract Growing<T> { fn next() -> Growing<array<T>>; }
fn use(value: Growing<int>) {}
""", "E_SEM_CONTRACT_EXPANSION");
}
@Test void finiteMutualApplicationsReuseTheirAnchors() {
var file = compile("""
declare contract Left<T> { fn next() -> Right<T>; }
declare contract Right<T> { fn next() -> Left<T>; }
fn identity(value: Left<int>) -> Left<int> { return value; }
""");
assertEquals(2, file.registry().types().stream().filter(t -> t.body() instanceof IRRegistry.Trait).count());
}
@Test void applicationsRequireExplicitExactArity() {
rejects("declare contract Identity<T> {} fn use(value: Identity) {}", "E_SEM_CONTRACT_ARITY");
rejects("declare contract Identity<T> {} fn use(value: Identity<int, bool>) {}", "E_SEM_CONTRACT_ARITY");
}
@Test void undeclaredAndDuplicateParametersAreRejected() {
rejects("declare contract Bad<T> { fn get(value: U); }", "E_SEM_CONTRACT_PARAMETER");
rejects("declare contract Bad<T, T> {}", "E_SEM_CONTRACT_PARAMETER");
}
@Test void invalidApplicationsAndImplementationsAreRejected() {
rejects("declare contract Echo<T> { fn echo(value: T) -> T; } declare service S {} implements Echo<int> for S using s {}", "E_SEM_CONTRACT_SIGNATURE");
rejects(IDENTITY + "implements Identity<int> for IntIdentity using s { fn hash(e: int) -> int { return e; } fn equals(a: int, b: int) -> bool { return true; } }", "E_SEM_CONTRACT_DUPLICATE_IMPLEMENTATION");
rejects("declare contract C<T> {} fn use(value: int<bool>) {}", "E_SEM_CONTRACT_ARGUMENT");
}
@Test void instantiatedContractsAreInvariant() {
rejects(IDENTITY + """
fn bad(value: Identity<bool>) { let wrong: Identity<int> = value; }
""", "E_SEM_CONTRACT_COERCION");
rejects(IDENTITY + "fn bad() { let wrong = IntIdentity as Identity<bool>; }", "E_SEM_CONTRACT_COERCION");
}
@Test void invalidPostSubstitutionArrayElementIsRejected() {
rejects("declare contract C<T> { fn accept(values: array<T>); } fn bad(value: C<optional int>) {}", "E_SEM_ARRAY_ELEMENT_TYPE");
}
@Test void composedPositionsKeepTheirExistingRestrictions() {
rejects("declare contract C<T> { fn accept(value: Fn(T) -> int); } fn bad(value: C<void>) {}", "E_SEM_FN_PARAMETER");
rejects("declare contract C<T> { fn get() -> optional T; } fn bad(value: C<void>) {}", "E_SEM_INVALID_OPTIONAL_VOID_TYPE_SURFACE");
rejects("declare contract C<T> {} fn bad(value: C<Self>) {}", "E_SEM_INVALID_SELF_CONTEXT");
}
@Test void functionReturnNormalizationDoesNotCreateAnotherApplication() {
compile("""
declare contract Marker<T> {}
declare service Strategy {}
implements Marker<Fn() -> int> for Strategy using s {}
fn demo() { let value: Marker<Fn() -> (value: int)> = Strategy; }
""");
}
@Test void barrelPreservesOrderedParameters() {
var diagnostics = DiagnosticSink.empty();
var fileId = new FileId(0);
var barrel = PbsBarrelParser.parse(PbsLexer.lex("pub contract Convert<A, B>;", fileId, diagnostics), fileId, diagnostics);
assertFalse(diagnostics.hasErrors());
var item = assertInstanceOf(PbsAst.BarrelContractItem.class, barrel.items().getFirst());
assertEquals(java.util.List.of("A", "B"), item.typeParameters().stream().map(PbsAst.TypeParameter::name).toList());
}
}
@@ -18,6 +18,27 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class PbsModuleVisibilityTest {
@Test void parameterizedExportsAndReexportsPreserveTheOriginalDeclaration() {
var diagnostics = DiagnosticSink.empty();
var next = new AtomicInteger(0);
var provider = module("app", "provider", List.of("declare contract Identity<T> {}"), "pub contract Identity<T>;", next, diagnostics);
var facade = module("app", "facade", List.of("import { Identity } from @app:provider;"), "pub contract Identity<T>;", next, diagnostics);
new PbsModuleVisibilityValidator().validate(ReadOnlyList.from(provider, facade), diagnostics);
assertTrue(!diagnostics.hasErrors(), diagnostics.stream().map(d -> d.getMessage()).toList().toString());
}
@Test void parameterizedBarrelArityAndOwnerModuleAreChecked() {
var diagnostics = DiagnosticSink.empty();
var next = new AtomicInteger(0);
var provider = module("app", "provider", List.of("declare contract Identity<T> {} declare service Strategy {}"),
"pub contract Identity; pub service Strategy;", next, diagnostics);
var consumer = module("app", "consumer", List.of("import { Identity, Strategy } from @app:provider; implements Identity<int> for Strategy using s {}"),
"", next, diagnostics);
new PbsModuleVisibilityValidator().validate(ReadOnlyList.from(provider, consumer), diagnostics);
assertTrue(diagnostics.stream().anyMatch(d -> d.getCode().equals("E_LINK_CONTRACT_PARAMETERS")));
assertTrue(diagnostics.stream().anyMatch(d -> d.getCode().equals("E_SEM_CONTRACT_OWNER_MODULE")));
}
@Test
void shouldReportMissingBarrelPerModule() {
final var diagnostics = DiagnosticSink.empty();
@@ -10,6 +10,18 @@ import static org.junit.jupiter.api.Assertions.*;
class PbsBarrelParserTest {
@Test
void parametricArraysAndFunctionsUseTheSharedTypeParser() {
var source = "pub fn make(a: array<array<int>>) -> array<Fn(int) -> int>;";
var diagnostics = DiagnosticSink.empty();
var id = new FileId(0);
var ast = PbsBarrelParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics);
assertFalse(diagnostics.hasErrors());
var function = (PbsAst.BarrelFunctionItem) ast.items().getFirst();
assertEquals(PbsAst.TypeRefKind.ARRAY, function.returnType().kind());
assertEquals(PbsAst.TypeRefKind.FN, function.returnType().inner().kind());
}
@Test
void shouldParseBarrelShapeWithFunctionReturnSurfaces() {
final var source = """
@@ -10,6 +10,55 @@ import static org.junit.jupiter.api.Assertions.*;
class PbsExprParserTest {
@Test
void typeCursorPeelsCompoundClosersAndPreservesRemainderSpans() {
var cursor = new PbsTokenCursor(p.studio.utilities.structures.ReadOnlyList.from(
new p.studio.compiler.pbs.lexer.PbsToken(p.studio.compiler.pbs.lexer.PbsTokenKind.GREATER_EQUAL, ">>=", 10, 13),
new p.studio.compiler.pbs.lexer.PbsToken(p.studio.compiler.pbs.lexer.PbsTokenKind.EOF, "", 13, 13)));
assertEquals(10, cursor.consumeTypeClose().start());
assertEquals(">=", cursor.peek().lexeme());
assertEquals(11, cursor.consumeTypeClose().start());
assertEquals(p.studio.compiler.pbs.lexer.PbsTokenKind.EQUAL, cursor.peek().kind());
assertEquals(12, cursor.peek().start());
assertEquals(13, cursor.peek().end());
assertNull(cursor.consumeTypeClose());
}
@Test
void parametricArraysPreserveArgumentsSpansAndContextualForms() {
var source = "fn main() { let a: array<array<int>>=new array<array<int>>(2); "
+ "let b: array<int>=new array<>(2); let c: array<int>=new array(2); let cmp = 2 >= 1; }";
var diagnostics = DiagnosticSink.empty();
var id = new FileId(0);
var ast = PbsParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics);
assertFalse(diagnostics.hasErrors(), diagnostics.toString());
var statements = ast.functions().getFirst().body().statements();
var a = (PbsAst.LetStatement) statements.get(0);
var explicit = (PbsAst.NewExpr) a.initializer();
assertEquals("array<array<int>>", source.substring((int) a.explicitType().span().getStart(), (int) a.explicitType().span().getEnd()));
assertEquals("array<int>", source.substring((int) explicit.explicitType().inner().span().getStart(), (int) explicit.explicitType().inner().span().getEnd()));
assertEquals("int", explicit.explicitType().inner().inner().name());
assertFalse(explicit.diamond());
var diamond = (PbsAst.NewExpr) ((PbsAst.LetStatement) statements.get(1)).initializer();
assertTrue(diamond.diamond());
assertNull(diamond.explicitType());
var omitted = (PbsAst.NewExpr) ((PbsAst.LetStatement) statements.get(2)).initializer();
assertFalse(omitted.diamond());
assertNull(omitted.explicitType());
assertEquals(">=", ((PbsAst.BinaryExpr) ((PbsAst.LetStatement) statements.get(3)).initializer()).operator());
}
@Test
void excessiveNestingAndMissingClosersAreDiagnosed() {
for (var type : java.util.List.of("array<int", "array<".repeat(257) + "int" + ">".repeat(257))) {
var diagnostics = DiagnosticSink.empty();
var id = new FileId(0);
var source = "fn main() { let a: " + type + " = new array(1); }";
PbsParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics);
assertTrue(diagnostics.hasErrors(), type);
}
}
@Test
void shouldParseApplyElseAndPostfixChains() {
final var source = """
@@ -56,12 +56,21 @@ final class PbsEditorialSupportServiceTest {
String source = """
declare struct Enemy(pub hp: int) { fn health() -> int { return this.hp; } }
fn main() {
let enemies: array Enemy = new array(2);
let enemies = new array<Enemy>(2);
if let enemy = enemies[0] { let hp = enemy.health(); }
enemies.clear(0);
}
""";
var ast = parseOrdinary(source);
int argumentType = source.indexOf("<Enemy>") + 1;
assertFalse(service.definition(source, ast, ReadOnlyList.empty(), argumentType).isEmpty());
assertTrue(service.hover(source, ast, ReadOnlyList.empty(), argumentType).isPresent());
var typeRename = service.rename(source, ast, ReadOnlyList.empty(), argumentType, "Opponent");
assertTrue(typeRename.allowed(), typeRename.refusal());
assertEquals(2, typeRename.sites().size());
var formatted = p.studio.compiler.pbs.PbsDocumentFormatter.format(source);
assertEquals(formatted, p.studio.compiler.pbs.PbsDocumentFormatter.format(formatted));
parseOrdinary(formatted);
int use = source.indexOf("enemy.health");
assertFalse(service.definition(source, ast, ReadOnlyList.empty(), use).isEmpty());
assertTrue(service.hover(source, ast, ReadOnlyList.empty(), use).isPresent());
@@ -0,0 +1,67 @@
package p.studio.compiler.pbs.semantics;
import org.junit.jupiter.api.Test;
import p.studio.compiler.pbs.ast.PbsAst;
import p.studio.compiler.pbs.lexer.PbsLexer;
import p.studio.compiler.pbs.parser.PbsParser;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.identifiers.FileId;
import p.studio.utilities.structures.ReadOnlyList;
import static org.junit.jupiter.api.Assertions.*;
class PbsGenericContractsEditorialTest {
@Test void importedAliasesNavigateToOriginsAndShowCanonicalArguments() {
String provider = "declare struct Enemy() {} declare contract Echo<T> { fn echo(value: T) -> T; }";
String source = """
import { Echo as Policy, Enemy as Opponent } from @sdk:policy;
fn use(reader: Policy<Opponent>) {}
""";
var diagnostics = DiagnosticSink.empty();
var providerId = new FileId(1);
var localId = new FileId(2);
var remote = PbsParser.parse(PbsLexer.lex(provider, providerId, diagnostics), providerId, diagnostics, PbsParser.ParseMode.ORDINARY);
var local = PbsParser.parse(PbsLexer.lex(source, localId, diagnostics), localId, diagnostics, PbsParser.ParseMode.ORDINARY);
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getMessage()).toList().toString());
var enemy = remote.topDecls().get(0);
var contract = remote.topDecls().get(1);
var supplemental = ReadOnlyList.wrap(java.util.List.<PbsAst.TopDecl>of(
new PbsAst.TypeBindingDecl("Opponent", enemy, local.span()),
new PbsAst.TypeBindingDecl("Policy", contract, local.span())));
var service = new PbsEditorialSupportService();
int application = source.indexOf("Policy<");
assertEquals(contract.span(), service.definition(source, local, supplemental, application).getFirst().span());
assertEquals(enemy.span(), service.definition(source, local, supplemental, application + 7).getFirst().span());
var hover = service.hover(source, local, supplemental, application).orElseThrow();
assertEquals("Echo<Enemy>", hover.displayName());
assertEquals("echo(value: Enemy) -> Enemy", hover.signatures().getFirst().label());
}
@Test void parameterNavigationAndInstantiatedPresentationShareTheCompilerModel() {
String source = """
declare contract Echo<T> { fn echo(value: T) -> T; }
fn demo(reader: Echo<int>) -> int { return reader.echo(42); }
""";
var diagnostics = DiagnosticSink.empty();
var id = new FileId(0);
var ast = PbsParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics, PbsParser.ParseMode.ORDINARY);
assertFalse(diagnostics.hasErrors());
var service = new PbsEditorialSupportService();
int parameterUse = source.indexOf("value: T") + 7;
var definition = service.definition(source, ast, ReadOnlyList.empty(), parameterUse);
assertEquals(source.indexOf("<T>") + 1, definition.getFirst().span().getStart());
assertTrue(service.hover(source, ast, ReadOnlyList.empty(), parameterUse).orElseThrow().detail().contains("type parameter"));
var application = service.hover(source, ast, ReadOnlyList.empty(), source.indexOf("Echo<int>"));
assertEquals("Echo<int>", application.orElseThrow().displayName());
assertEquals("echo(value: int) -> int", application.orElseThrow().signatures().getFirst().label());
int call = source.indexOf("reader.echo");
assertTrue(service.completion(source, ast, ReadOnlyList.empty(), call + 7).stream().anyMatch(c -> c.label().equals("echo") && c.detail().contains("int")));
assertEquals("echo(value: int) -> int", service.signatureHelp(source, ast, ReadOnlyList.empty(), source.indexOf("42)")).orElseThrow().signatures().getFirst().label());
assertFalse(service.definition(source, ast, ReadOnlyList.empty(), call + 7).isEmpty());
var formatted = p.studio.compiler.pbs.PbsDocumentFormatter.format(source);
assertEquals(formatted, p.studio.compiler.pbs.PbsDocumentFormatter.format(formatted));
var formattedDiagnostics = DiagnosticSink.empty();
PbsParser.parse(PbsLexer.lex(formatted, id, formattedDiagnostics), id, formattedDiagnostics, PbsParser.ParseMode.ORDINARY);
assertFalse(formattedDiagnostics.hasErrors());
}
}
@@ -9,6 +9,38 @@ import static org.junit.jupiter.api.Assertions.*;
class PbsSemanticsDeclarationsTest {
@Test
void arrayConstructorFormsShareExpectedTypePositions() {
for (var construction : java.util.List.of("new array<int>(2)", "new array<>(2)", "new array(2)")) {
var source = """
declare global values: array<int> = %s;
fn make() -> array<int> { return %s; }
fn use(items: array<int>) -> int { return items.length as int; }
fn main() -> int {
let local: array<int> = %s;
local = %s;
return use(%s);
}
""".formatted(construction, construction, construction, construction, construction);
var diagnostics = DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode()+":"+d.getMessage()).toList().toString());
}
}
@Test
void explicitArraysMustMatchReturnAndArgumentTypes() {
for (var source : java.util.List.of(
"fn make() -> array<int> { return new array<bool>(1); }",
"fn use(items: array<int>) {} fn main() { use(new array<bool>(1)); }",
"declare global items: array<int> = new array<bool>(1);",
"fn main() { let items: array<int> = new array(1); items = new array<bool>(1); }")) {
var diagnostics = DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
assertTrue(diagnostics.hasErrors(), source);
}
}
@Test
void shouldAcceptDocOnNamedApiDeclarations() {
final var source = """