Skip to content

Commit

Permalink
unified type hints
Browse files Browse the repository at this point in the history
  • Loading branch information
ascandone committed Jan 19, 2024
1 parent 2b2942f commit a7af84e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
8 changes: 8 additions & 0 deletions src/typecheck/typecheck.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,14 @@ test("recursive let declarations", () => {
});
});

test("type hints are used by typechecker", () => {
const [types, errs] = tc("let x: Int = 1.1");
expect(errs).not.toEqual([]);
expect(types).toEqual({
x: "Int",
});
});

function tc(src: string, context: Context = {}) {
const parsedProgram = unsafeParse(src);
const [typed, errors] = typecheck(parsedProgram, context);
Expand Down
27 changes: 26 additions & 1 deletion src/typecheck/typecheck.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { ConstLiteral, Expr, Program, Statement, Span, SpanMeta } from "../ast";
import {
ConstLiteral,
Expr,
Program,
Statement,
SpanMeta,
TypeHint,
} from "../ast";
import { TVar, Type, unify, Context, generalize, instantiate } from "./unify";

export type UnifyErrorType = "type-mismatch" | "occurs-check";
Expand Down Expand Up @@ -28,6 +35,13 @@ export function typecheck<T extends SpanMeta>(
const typedStatements = ast.statements.map<Statement<T & TypeMeta>>(
(decl) => {
const annotated = annotateExpr(decl.value);
if (decl.typeHint !== undefined) {
const t = inferTypeHint(decl.typeHint);
// TODO collect error
// - but is it even possible to fail to unify a fresh var?
unify(t, annotated.$.asType());
}

errors.push(
...typecheckAnnotatedExpr(annotated, {
...context,
Expand Down Expand Up @@ -210,3 +224,14 @@ function inferConstant(x: ConstLiteral): Type {
throw new Error("TODO inferConst with type: " + x.type);
}
}

function inferTypeHint(hint: TypeHint): Type {
switch (hint.type) {
case "named":
return {
type: "named",
name: hint.name,
args: hint.args.map(inferTypeHint),
};
}
}

0 comments on commit a7af84e

Please sign in to comment.