ensure number of args passed to constructor is correct

This commit is contained in:
2026-05-04 20:47:36 +10:00
parent 19fb905bc0
commit 0836495cd4
3 changed files with 55 additions and 14 deletions

View File

@@ -1,22 +1,32 @@
; ModuleID = 'main'
source_filename = "main"
%Test = type { i32 }
@str = private constant [11 x i8] c"test = %d\0A\00"
declare i32 @printf(ptr, ...)
define i32 @add(i32 %0, i32 %1) {
add_entry:
%a = alloca i32, align 4
store i32 %0, ptr %a, align 4
%b = alloca i32, align 4
store i32 %1, ptr %b, align 4
%a1 = load i32, ptr %a, align 4
%b2 = load i32, ptr %b, align 4
%2 = add i32 %a1, %b2
ret i32 %2
define void @Test_CONSTRUCTOR(ptr %0, i32 %1) {
Test_CONSTRUCTOR_entry:
%x = alloca i32, align 4
store i32 %1, ptr %x, align 4
%x1 = load i32, ptr %x, align 4
%xFieldPtr = getelementptr %Test, ptr %0, i32 0, i32 0
store i32 %x1, ptr %xFieldPtr, align 4
ret void
}
define i32 @main() {
main_entry:
%add = call i32 @add(i32 1, i32 2)
ret i32 %add
%test = alloca %Test, align 8
%selfTmp = alloca %Test, align 8
call void @Test_CONSTRUCTOR(ptr %selfTmp, i32 123)
%selfVal = load %Test, ptr %selfTmp, align 4
store %Test %selfVal, ptr %test, align 4
%test1 = load %Test, ptr %test, align 4
%Test_access = getelementptr %Test, ptr %test, i32 0, i32 0
%x_field = load i32, ptr %Test_access, align 4
%print = call i32 (ptr, ...) @printf(ptr @str, i32 %x_field)
ret i32 0
}

View File

@@ -1182,6 +1182,29 @@ ResultType(CometValue, charptr) visitNewStatement(CometCompiler* compiler, Comet
append(argValues, arg.as.success.value);
}
// ensure number of args passed to constructor is correct
if (newStmt.args.count < numParams-1) {
Estr errMsg = CREATE_ESTR("Not enough params passed to constructor of struct \"");
APPEND_ESTR(errMsg, structName);
APPEND_ESTR(errMsg, "\" (expects ");
char* buffer = malloc(128);
sprintf(buffer, "%d, passed %zu)", numParams-1, newStmt.args.count);
APPEND_ESTR(errMsg, buffer);
return Error(CometValue, charptr, errMsg.str);
} else if (newStmt.args.count > numParams-1) {
Estr errMsg = CREATE_ESTR("Too many params passed to constructor of struct \"");
APPEND_ESTR(errMsg, structName);
APPEND_ESTR(errMsg, "\" (expects ");
char* buffer = malloc(128);
sprintf(buffer, "%d, passed %zu)", numParams-1, newStmt.args.count);
APPEND_ESTR(errMsg, buffer);
return Error(CometValue, charptr, errMsg.str);
}
LLVMBuildCall2(compiler->builder, constructorType, constructor, argValues.pointer, argValues.count, "");
LLVMValueRef selfVal = LLVMBuildLoad2(compiler->builder, structType.as.success, self, "selfVal");

View File

@@ -1,5 +1,13 @@
func add(int a, int b) -> int => a + b
struct Test {
int x
init(int x) {
self.x = x
}
}
func main() -> int {
return add(1, 2)
Test test = new Test(123)
print("test = %d\n", test.x)
return 0
}