Search code examples
haskell

Is it possible to create custom Haskell "toplevels"?


I am writing a compiler in Haskell, trying to shun the lexing and parsing phases. I would like the source code to be an AST implemented as an algebraic type.

My current structure is the following :

  • I have a set of .hs files that contain the definitions of AST nodes, and the transformation functions from a program to its output, chiefly a monadic function named compile. This is the "compiler implementation".
  • I have another .hs file that defines a nullary function called program, which returns the AST to compile. This is the "program".
  • Lastly, I have a last .hs file that defines main basically as compile program. This is the "driver".

I would like to be able to deliver the compiler (compiler implementation + driver) in a neat packaged form, expecting my users to provide the definition of program themselves.

I have tried to implement the compiler with instances of Read for the AST types, but the problem is that the feedback for program error says "couldn't read", and that's it. Since I expect the program to be in the form of valid Haskell, I would like the part that reads the AST to be done with a Haskell compiler.

I imagine a solution where I would be able to provide a beefed up Haskell compiler incorporating the compiler implementation and the driver, which would compile the program.

Is it possible to create this kind of artefact, in the like of a LISP image or an OCaml custom top-level?


Solution

  • This is, roughly, what xmonad does, so you could read about how that mechanism works and take inspiration from it. The dyre package attempts to bundle up the technique into a standalone library.

    You will need to make a full Haskell compiler -- i.e. GHC -- available to the user as part of your packaging.