diff --git a/src/cat/compiler.c b/src/cat/compiler.c index 0481d33..88e4a7b 100644 --- a/src/cat/compiler.c +++ b/src/cat/compiler.c @@ -42,6 +42,7 @@ typedef struct { CAT_BYTECODE_Function *fn; char locals[MAXLOCALS][64]; CAT_TYPES_TYPE_Type *local_types[MAXLOCALS]; /* declared/inferred */ + CAT_TYPES_TYPE_Type *ret_type; /* declared `-> T` (or any) */ int nlocals; int is_generator; /* body used `yield` */ } FuncCtx; @@ -307,10 +308,10 @@ static int compile_function_literal(Compiler *c, const char *name) sub->nlocals = nc.nlocals; /* optional return type hint */ - if (accept(c, CAT_LEXER_TOK_ARROW)) { - if (check(c, CAT_LEXER_TOK_NAME)) - next(c); - } + if (accept(c, CAT_LEXER_TOK_ARROW)) + nc.ret_type = parse_type_core(c, 0); + else + nc.ret_type = cat_types_type_any(); /* push context and compile body */ c->stack[c->nstack++] = nc; @@ -1022,6 +1023,13 @@ static void stat(Compiler *c) !check(c, CAT_LEXER_TOK_SEMI) && !check(c, CAT_LEXER_TOK_ELSE) && !check(c, CAT_LEXER_TOK_ELSEIF) && !check(c, CAT_LEXER_TOK_UNTIL) && !check(c, CAT_LEXER_TOK_EXCEPT)) { + CAT_TYPES_TYPE_Type *lit = literal_type(c); + CAT_TYPES_TYPE_Type *want = ctx(c)->ret_type; + if (lit != NULL && want != NULL && + !cat_types_type_assignable(want, lit)) + err_at(c, line, "cannot return %s from function returning %s", + cat_types_type_name(lit), + cat_types_type_name(want)); expr(c); emit(c, CAT_BYTECODE_OP_RETURN, 0, 0, line); } else { diff --git a/tests/run_tests.sh b/tests/run_tests.sh index 7e2da56..5cef7be 100644 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -258,6 +258,7 @@ out=`$BIN tests/types.cat` check "types-ok" "ok: 42 3.5 hi true" "`echo "$out" | sed -n 1p`" check "types-widen" "widen: 7" "`echo "$out" | sed -n 2p`" check "types-opaque" "opaque: 42 empty" "`echo "$out" | sed -n 3p`" +check "types-ret" "ret: 5" "`echo "$out" | sed -n 4p`" # type hints are CHECKED where both sides are concrete printf 'local x : int = "bad"\n' > /tmp/catscript_badtype.cat diff --git a/tests/types.cat b/tests/types.cat index 1341e90..293ecd6 100644 --- a/tests/types.cat +++ b/tests/types.cat @@ -18,3 +18,9 @@ print("widen:", f) local n : cint = 42 local buf : cbyte[] = empty print("opaque:", n, buf) + +-- return type hints are checked where concrete +function good() -> int + return 5 +end +print("ret:", good())