type checker, phase 2: return hints checked

- parse the `-> T` return hint into the function context (was consumed
  and dropped).
- `return <literal>` is checked against the declared return type: a
  concrete mismatch raises at compile time.  Opaque/unknown returns and
  non-literal expressions stay permissive.
- tests/types.cat + suite: a valid `-> int` function.  Suite 140 -> 141.
This commit is contained in:
Minus committed 2026-11-18 17:15:42 +00:00
1 parent 48b1b84ea6
commit 96e8f516cc
3 files changed
+19 -4

No files matched your search

+12 -4
View File
@@ -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 {