feat(pbs): add concrete generic structs and free functions
This commit is contained in:
+203
@@ -0,0 +1,203 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsGenericStructsTest {
|
||||
private static final String BOX = """
|
||||
declare struct Box<T>(value: T) {
|
||||
fn get() -> T { return this.value; }
|
||||
fn set(value: T) { this.value = value; }
|
||||
}
|
||||
""";
|
||||
private DiagnosticSink compile(String source) {
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
|
||||
return diagnostics;
|
||||
}
|
||||
private void accepts(String source) {
|
||||
var diagnostics = compile(source);
|
||||
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode()+": "+d.getMessage()).toList().toString());
|
||||
}
|
||||
private void rejects(String source, String code) {
|
||||
var diagnostics = compile(source);
|
||||
assertTrue(diagnostics.stream().anyMatch(d -> d.getCode().equals(code)), () -> diagnostics.stream().map(d -> d.getCode()+": "+d.getMessage()).toList().toString());
|
||||
}
|
||||
@Test void specializesStateMethodsAndContextualConstructions() {
|
||||
accepts(BOX+"""
|
||||
fn main() -> int {
|
||||
let a = new Box<int>(40);
|
||||
let b: Box<int> = new Box<>(41);
|
||||
let c: Box<int> = new Box(42);
|
||||
a.set(c.get()); return a.get();
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void explicitFreeFunctionsBecomeFnValuesAndComposeWithGenericDispatch() {
|
||||
accepts(BOX+"""
|
||||
declare contract Reader<T> { fn read() -> T; }
|
||||
implements<T> Reader<T> for Box<T> using box { fn read() -> T { return box.get(); } }
|
||||
fn read<T>(reader: Reader<T>) -> T { return reader.read(); }
|
||||
fn main() -> int {
|
||||
let box = new Box<int>(42);
|
||||
let reader: Reader<int> = box;
|
||||
let invoke: Fn(Reader<int>) -> int = read<int>;
|
||||
return invoke(reader);
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void rejectsUnjustifiedCapabilitiesEvenWhenTemplateIsUnused() {
|
||||
rejects("fn double<T>(value: T) -> T { return value + value; }", "E_SEM_GENERIC_CAPABILITY");
|
||||
rejects(BOX+"fn main() { let x = new Box(42); }", "E_SEM_GENERIC_CONTEXT");
|
||||
rejects("fn identity<T>(value: T) -> T { return value; } fn main() { let x = identity(42); }", "E_SEM_GENERIC_FUNCTION_ARGUMENTS");
|
||||
}
|
||||
@Test void rejectsOverlappingRulesWithoutRequestingTheConflictingApplication() {
|
||||
rejects(BOX+"""
|
||||
declare contract Reader<T> { fn read() -> T; }
|
||||
implements<T> Reader<T> for Box<T> using box { fn read() -> T { return box.get(); } }
|
||||
implements Reader<int> for Box<int> using box { fn read() -> int { return box.get(); } }
|
||||
""", "E_SEM_GENERIC_OVERLAP");
|
||||
}
|
||||
|
||||
@Test void substitutesNestedBodiesAndSnapshotCaptures() {
|
||||
accepts(BOX+"""
|
||||
fn box<U>(value: U) -> Box<U> { return new Box<U>(value); }
|
||||
fn wrap<T>(value: T) -> Fn() -> T {
|
||||
let owner: Box<T> = box<T>(value);
|
||||
return fn [owner]() -> T { return owner.get(); };
|
||||
}
|
||||
fn main() -> int { let read = wrap<int>(42); return read(); }
|
||||
""");
|
||||
}
|
||||
@Test void composesOptionalTupleArrayAndFunctionFields() {
|
||||
accepts(BOX+"""
|
||||
fn add(value: int) -> int { return value + 2; }
|
||||
fn main() -> int {
|
||||
let option = new Box<optional int>(some(40));
|
||||
let pair = new Box<(left: int, right: int)>((left: 20, right: 22));
|
||||
let array = new Box<array<int>>([40]);
|
||||
let function = new Box<Fn(int) -> int>(add);
|
||||
let values = pair.get();
|
||||
let call = function.get();
|
||||
return call(array.get()[0] else 0);
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void checksUnusedMethodsAndRejectsCollapsingOverloads() {
|
||||
rejects("""
|
||||
declare struct Container<T>(value: T) {
|
||||
fn unused() { let values: array<T> = new array(1); }
|
||||
}
|
||||
fn main() { let c = new Container<optional int>(none); }
|
||||
""", "E_SEM_ARRAY_ELEMENT_TYPE");
|
||||
rejects("""
|
||||
declare struct Overload<T>(value: T) {
|
||||
fn set(value: T) { this.value = value; }
|
||||
fn set(value: int) { }
|
||||
}
|
||||
fn main() { let c = new Overload<int>(42); }
|
||||
""", "E_SEM_GENERIC_COLLISION");
|
||||
}
|
||||
@Test void supportsNominalRecursionAndBoundsExpansionThroughUnusedBodies() {
|
||||
accepts("""
|
||||
declare struct Node<T>(value: T, next: optional Node<T>) {
|
||||
fn get() -> T { return this.value; }
|
||||
}
|
||||
fn main() -> int { let node = new Node<int>(42, none); return node.get(); }
|
||||
""");
|
||||
rejects("""
|
||||
declare struct Growing<T>(value: T) {
|
||||
fn unused() { let larger = new Growing<array<T>>([this.value]); }
|
||||
}
|
||||
fn main() { let c = new Growing<int>(42); }
|
||||
""", "E_SEM_GENERIC_EXPANSION");
|
||||
}
|
||||
@Test void acceptsNamedConstructorsAppliedSelfAndDifferentContractTargets() {
|
||||
accepts("""
|
||||
declare struct Box<T>(value: T) {
|
||||
ctor make(value: T) { this.value = value; }
|
||||
fn same() -> Self { return this; }
|
||||
fn get() -> T { return this.value; }
|
||||
}
|
||||
fn main() -> int { let b = new Box<int>.make(42); return b.same().get(); }
|
||||
""");
|
||||
}
|
||||
@Test void preservesNominalArgumentsAndResolvesEveryExpectedConstructionPosition() {
|
||||
accepts(BOX+"""
|
||||
declare struct Enemy(pub hp: int);
|
||||
fn take(value: Box<Enemy>) -> Box<Enemy> { return value; }
|
||||
fn make() -> Box<Enemy> { return new Box(new Enemy(42)); }
|
||||
fn main() -> int {
|
||||
let box = make();
|
||||
box = new Box<>(new Enemy(42));
|
||||
let selected = take(new Box(new Enemy(42)));
|
||||
return selected.get().hp;
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void unusedTemplatesStillObeyOrdinaryFlowAndConstructorRules() {
|
||||
rejects("fn unfinished<T>(value: T) -> T {}", "E_SEM_POSSIBLE_FALLTHROUGH_NON_UNIT");
|
||||
rejects("fn wrong<T>(value: T) -> int { return true; }", "E_SEM_RETURN_TYPE_MISMATCH");
|
||||
var diagnostics = compile("declare struct Uninitialized<T>(value: T) { ctor make() {} }");
|
||||
assertTrue(diagnostics.hasErrors(), "An unused generic constructor must initialize its fields");
|
||||
}
|
||||
@Test void constructorsRequireInitializationAcrossBranchesAndLoopExits() {
|
||||
accepts("""
|
||||
declare struct Box<T>(value: T) {
|
||||
ctor choose(flag: bool, a: T, b: T) {
|
||||
if flag { this.value = a; } else { this.value = b; }
|
||||
}
|
||||
ctor once(value: T) { while true { this.value = value; break; } }
|
||||
}
|
||||
fn main() { let value = new Box<int>.choose(true, 40, 42); }
|
||||
""");
|
||||
rejects("declare struct Box(value: int) { ctor choose(flag: bool) { if flag { this.value = 42; } } }",
|
||||
"E_SEM_CTOR_FIELD_UNINITIALIZED");
|
||||
rejects("declare struct Box<T>(value: T) { ctor loop(value: T) { for i: int from 0 until 1 { this.value = value; } } }",
|
||||
"E_SEM_CTOR_FIELD_UNINITIALIZED");
|
||||
rejects("declare struct Box(value: int) { ctor loop(flag: bool) { while true { if flag { break; } this.value = 42; break; } } }",
|
||||
"E_SEM_CTOR_FIELD_UNINITIALIZED");
|
||||
rejects("declare struct Box(value: int) { ctor choose(flag: bool) { let ignored = flag and { this.value = 42; true }; } }",
|
||||
"E_SEM_CTOR_FIELD_UNINITIALIZED");
|
||||
}
|
||||
@Test void preservesCallableFieldsAndLexicalApplicationScope() {
|
||||
accepts("""
|
||||
declare struct Callback<T>(transform: Fn(T) -> T) {
|
||||
fn invoke(value: T) -> T { return this.transform(value); }
|
||||
}
|
||||
fn identity<T>(value: T) -> T { return value; }
|
||||
fn main() -> int { let transform = new Callback<int>(identity<int>); return transform.invoke(42); }
|
||||
""");
|
||||
rejects("fn id<T>(value: T) -> T { return value; } fn main() { let id = id<int>; id<int>(42); }",
|
||||
"E_SEM_GENERIC_FUNCTION_ARGUMENTS");
|
||||
rejects("declare struct Marker<T>(); fn main() { let marker = new Marker<Self>(); }", "E_SEM_INVALID_SELF_CONTEXT");
|
||||
}
|
||||
@Test void filtersExplicitOverloadsAndPreservesComparisonsAndNestedClosers() {
|
||||
accepts("""
|
||||
declare struct Box<T>(value: T);
|
||||
fn identity(value: bool) -> bool { return value; }
|
||||
fn identity<T>(value: T) -> T { return value; }
|
||||
fn main() -> int {
|
||||
let nested = identity<Box<array<int>>>(new Box<array<int>>([42]));
|
||||
let a = 1; let b = 2; let c = 3;
|
||||
if a < b && c >= b && identity(true) { return 42; }
|
||||
return identity<int>(0);
|
||||
}
|
||||
""");
|
||||
rejects("fn duplicate<T>(value: T) -> T { return value; } fn duplicate<U>(value: U) -> U { return value; }",
|
||||
"E_SEM_GENERIC_DUPLICATE");
|
||||
accepts("fn recurse<T>(value: T, stop: bool) -> T { if stop { return value; } return recurse<T>(value, true); } fn main() -> int { return recurse<int>(42, false); }");
|
||||
rejects("fn grow<T>(value: T) { grow<array<T>>([value]); } fn main() { grow<int>(42); }", "E_SEM_GENERIC_EXPANSION");
|
||||
}
|
||||
@Test void concreteErrorsRetainDefinitionAndRequestingUse() {
|
||||
String source = "declare struct Storage<T>(values: array<T>); fn main() { let value = new Storage<optional int>([]); }";
|
||||
var diagnostics = compile(source);
|
||||
var error = diagnostics.stream().filter(d -> d.getCode().equals("E_SEM_ARRAY_ELEMENT_TYPE")).findFirst().orElseThrow();
|
||||
assertTrue(error.getMessage().contains("Storage<optional int>"), error.getMessage());
|
||||
assertFalse(error.getMessage().contains("$generic$"), error.getMessage());
|
||||
assertTrue(error.getRelated().stream().anyMatch(r -> r.getSpan().getStart() == 0));
|
||||
assertTrue(error.getRelated().stream().anyMatch(r -> r.getSpan().getStart() >= source.indexOf("new Storage")));
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
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 PbsGenericStructsEditorialTest {
|
||||
private PbsAst.File parse(String source, int id) {
|
||||
var diagnostics = DiagnosticSink.empty(); var file = new FileId(id);
|
||||
var ast = PbsParser.parse(PbsLexer.lex(source, file, diagnostics), file, diagnostics, PbsParser.ParseMode.ORDINARY);
|
||||
assertFalse(diagnostics.hasErrors(), diagnostics.toString()); return ast;
|
||||
}
|
||||
@Test void symbolicNavigationAndConcreteSignaturesShareSourceOrigins() {
|
||||
var source = """
|
||||
declare struct Box<T>(value: T) { fn get() -> T { return this.value; } }
|
||||
fn identity<U>(value: U) -> U { return value; }
|
||||
fn demo() -> int {
|
||||
let box: Box<int> = new Box<int>(42);
|
||||
let copy = identity<int>(42);
|
||||
return box.get();
|
||||
}
|
||||
""";
|
||||
var ast = parse(source, 0); var service = new PbsEditorialSupportService();
|
||||
var empty = ReadOnlyList.<PbsAst.TopDecl>empty();
|
||||
var parameter = service.definition(source, ast, empty, source.indexOf("value: T")+7);
|
||||
assertEquals(source.indexOf("<T>")+1, parameter.getFirst().span().getStart());
|
||||
assertTrue(service.hover(source, ast, empty, source.indexOf("value: T")+7).orElseThrow().detail().contains("type parameter"));
|
||||
var hover = service.hover(source, ast, empty, source.indexOf("Box<int>"));
|
||||
assertEquals("Box<int>", hover.orElseThrow().displayName());
|
||||
assertEquals("get() -> int", hover.orElseThrow().signatures().getFirst().label());
|
||||
int member = source.indexOf("box.get")+4;
|
||||
assertTrue(service.completion(source, ast, empty, member).stream().anyMatch(c -> c.label().equals("get") && c.detail().contains("int")));
|
||||
assertFalse(service.definition(source, ast, empty, member).isEmpty());
|
||||
assertEquals("identity<int>(value: int) -> int", service.signatureHelp(source, ast, empty,
|
||||
source.indexOf("identity<int>(42")+14).orElseThrow().signatures().getFirst().label());
|
||||
var usages = service.references(source, ast, empty, source.indexOf("<T>")+1);
|
||||
assertTrue(usages.size() >= 3);
|
||||
int symbolicMember = source.indexOf("this.value") + 5;
|
||||
assertTrue(service.completion(source, ast, empty, symbolicMember).stream()
|
||||
.anyMatch(c -> c.label().equals("value") && c.detail().equals("T")));
|
||||
assertEquals("T", service.hover(source, ast, empty, symbolicMember).orElseThrow().detail());
|
||||
var formatted = p.studio.compiler.pbs.PbsDocumentFormatter.format(source);
|
||||
parse(formatted, 0);
|
||||
assertEquals(formatted, p.studio.compiler.pbs.PbsDocumentFormatter.format(formatted));
|
||||
}
|
||||
@Test void importedGenericAliasesKeepCanonicalPresentationAndDefinitionSpans() {
|
||||
var remote = parse("declare struct Box<T>(value: T) { fn get() -> T { return this.value; } }", 1);
|
||||
var source = "import { Box as Package } from @sdk:boxes; fn demo(box: Package<int>) -> int { return box.get(); }";
|
||||
var ast = parse(source, 2);
|
||||
var supplemental = ReadOnlyList.wrap(java.util.List.<PbsAst.TopDecl>of(new PbsAst.TypeBindingDecl("Package", remote.topDecls().getFirst(), ast.span())));
|
||||
var service = new PbsEditorialSupportService();
|
||||
assertEquals(remote.topDecls().getFirst().span(), service.definition(source, ast, supplemental, source.indexOf("Package<int>")).getFirst().span());
|
||||
assertEquals("Box<int>", service.hover(source, ast, supplemental, source.indexOf("Package<int>")).orElseThrow().displayName());
|
||||
assertEquals("get() -> int", service.hover(source, ast, supplemental, source.indexOf("box.get")+4).orElseThrow().signatures().getFirst().label());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user