Typechecking and _ffi

Tom Murphy tom7@cs.cmu.edu
Fri, 22 Mar 2002 14:43:21 -0500 (EST)


While it's easy to use SML/NJ to type-check standard Standard ML code,
when using MLton's FFI primitives this becomes a trickier situation. I've
got an easy way to do this now, so I thought I might share it.

Suppose that I've got a bunch of standard code, and one file 'mlx.sml'
that uses _ffi and _prim. My program is built through a file called
mlxtest.cm. The following makefile allows me to type-check my code with
SML/NJ by typing 'make typecheck':

nj : *.sml *.cm
	cat mlx.sml | sed -e 's/_ffi/Unsafe.cast/' | sed -e 's/_prim/Unsafe.cast/' > mlx-nj.sml
	cat mlxtest.cm | sed -e 's/mlx.sml/mlx-nj.sml/' > sources.cm

typecheck : nj
	echo "CM.make();" | sml

The basic trick is to replace _ffi and _prim with Unsafe.cast (you could
also use anything of type string -> 'a, like (raise Match) or a looping
function, but I like to live dangerously! ;-)) to generate a new program
that SML/NJ likes. Since all _ffi and _prim declarations are annotated
with their types, the cast is constrained to the "actual" type of the
foreign function or primitive. Of course, you should never actually run
the code, but it's sufficient for type checking.

Still looking forward to a real frontend in MLton, but this is making my
life a lot easier in the meantime!

 - Tom 7