From fb439df085eb1f7095d987973475a7753d0a1103 Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Sun, 26 Jan 2025 10:23:13 +0000 Subject: Use correct type for this in methods for generic structs --- .../TypeCheckerStructDefinitionTests.java | 43 ++++++++++++++++++++++ 1 file changed, 43 insertions(+) (limited to 'src/test/java') diff --git a/src/test/java/org/shedlang/compiler/typechecker/TypeCheckerStructDefinitionTests.java b/src/test/java/org/shedlang/compiler/typechecker/TypeCheckerStructDefinitionTests.java index 09df039c..c1954ea5 100644 --- a/src/test/java/org/shedlang/compiler/typechecker/TypeCheckerStructDefinitionTests.java +++ b/src/test/java/org/shedlang/compiler/typechecker/TypeCheckerStructDefinitionTests.java @@ -397,4 +397,47 @@ public class TypeCheckerStructDefinitionTests { )) ); } + + @Test + public void canTypeCheckMethodOnGenericStructReturningThis() { + var untyped = UntypedStructDefinitionNode.builder() + .withName("ExampleStruct") + .withTypeLevelParams(List.of(Untyped.typeParam("T"))) + .addMethod( + UntypedFunctionDefinitionNode.builder() + .addPositionalParam("this", Optional.empty()) + .withName("a") + .withReturnType(Untyped.constructedType( + Untyped.typeLevelReference("ExampleStruct"), + List.of(Untyped.typeLevelReference("T")) + )) + .addStatement(Untyped.functionReturn(Untyped.reference("this"))) + .build() + ) + .build(); + var context = TypeCheckerContext.EMPTY; + + var typed = typeCheckNamespaceStatement(untyped, context); + + var structTypeInfo = typed.context().toTypeInfos() + .structTypeInfo(Types.struct(NAMESPACE_NAME, "ExampleStruct")) + .orElseThrow(); + assertThat( + structTypeInfo, + has("methods", x -> x.methods(), isSequence( + equalTo(new MethodInfo( + "a", + FunctionType.builder() + .withReturnType(Types.constructedType( + Types.typeConstructor( + List.of(TypeParam.forStructType(Types.struct(NAMESPACE_NAME, "ExampleStruct"), "T")), + Types.struct(NAMESPACE_NAME, "ExampleStruct") + ), + List.of(TypeParam.forStructType(Types.struct(NAMESPACE_NAME, "ExampleStruct"), "T")) + )) + .build() + )) + )) + ); + } } -- cgit v1.2.3