From 45b6f073fe398e820e9e4a82900bc282ee32af9b Mon Sep 17 00:00:00 2001 From: Mel Date: Tue, 26 Jul 2022 20:13:28 +0000 Subject: Add OpRet manually for functions without return --- pkg/lang/compiler/compiler.go | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'pkg/lang') diff --git a/pkg/lang/compiler/compiler.go b/pkg/lang/compiler/compiler.go index 5e2a645..9dbfd12 100644 --- a/pkg/lang/compiler/compiler.go +++ b/pkg/lang/compiler/compiler.go @@ -112,6 +112,14 @@ func (comp *Compiler) compileFnDeclStmt(t *code.Builder, fnDeclStmt ast.StmtFnDe return err } + // If the function did not end with a return statement, we need to add an OpRet for safety. + lastStmt := fnDeclStmt.Body.Stmts[len(fnDeclStmt.Body.Stmts)-1] + // TODO: Get rid of EmptyStmt so we can use the Kind field to determine if the last statement is a return statement. + if lastStmt.Kind != ast.StmtKindReturn { + functionTarget.AppendOp(code.OpPushNull) + functionTarget.AppendOp(code.OpRet) + } + fnScope := comp.scopes.CurrentFunction() _ = comp.scopes.Exit() // Function declaration scopes do not pollute stack -- cgit 1.4.1