MicroHs

MicroHs (mhs) is a compiler for an extended subset of Haskell. It compiles Haskell to combinators, which are then executed by a small runtime system written in C. The compiler is written in MicroHs and can compile itself. All you need to build and run MicroHs is a C compiler.

There are some slides with a general presentation of MicroHs.

Contents:


Language

The language is an extended subset of Haskell 2010.

Differences from Haskell 2010 and GHC:

Extensions

The following extensions are supported:

Deriving

Deriving is supported for Bounded, Data, Enum, Eq, Foldable, Functor, Generic, Generic1, Ix, Lift, Ord, Read, Show, and Traversable.

Typeable is automatic: every data type, newtype, and class gets a Typeable instance. This needs the class Data.Typeable.Typeable, which is known in any module that imports the Prelude. To avoid the instance for a data type or newtype, e.g., in a module that does not import the Prelude, add an empty deriving () clause. This turns off all deriving for that type, including the HasField instances for its record fields, so any other deriving clauses on the same declaration are ignored. There is no way to avoid the instance for a class.

Extra commas

A comma separated list can have an extra comma at the beginning or at the end. This makes it easier to add, remove, and reorder items, and to make items conditional with CPP. For example:

module M(
    Color(Red, Green,),
    main,
  ) where

data Color = Red | Green
  deriving (
    Eq,
    Show,
  )

colors :: [Color]
colors = [
    Red,
    Green,
  ]

A leading or trailing comma is allowed in list literals and list comprehensions, export and import lists (and the lists of constructors and methods in them), deriving and default clauses, record declarations, record construction and update, guards, and functional dependencies. Only a trailing comma is allowed in a list of names before :: and in a fixity declaration, e.g., x, y, :: Int. Tuples cannot have extra commas, since that would conflict with tuple sections.

GHC will also get this extension; see the accepted proposal.

Extra instance bindings

An instance declaration can have a second where with bindings that are not methods. These bindings can be used in the methods, and they can use the type variables and the context of the instance, but they are not visible outside the instance. This extension is MicroHs only. For example:

instance Show a => Show (Tree a) where
    showsPrec _ t = go 0 t
  where
    go :: Int -> Tree a -> ShowS
    go n (Leaf x)   = indent n . shows x . showString "\n"
    go n (Node l r) = indent n . showString "Node\n" . go (n+2) l . go (n+2) r
    indent n = showString (replicate n ' ')

The second where must be indented less than the methods, so that it ends the block of methods.

Import shadowing

A top level definition in a module shadows an imported definition with the same name. In Haskell 2010, using such a name is an error, since it is ambiguous. The imported definition can still be used with a qualified name:

import Data.List

insert :: Int -> [Int] -> [Int]     -- shadows Data.List.insert
insert x xs = x : xs

test = (insert 1 [2, 3], Data.List.insert 2 [1, 3])

Multi-class instances

An instance declaration can define instances of several classes at once, by giving a tuple of class constraints instead of a single one. The methods of all the classes go in the same where, and the instance context applies to all of them. This extension is MicroHs only. For example:

data Color = Red | Green

instance (Eq Color, Show Color) where
  Red   == Red   = True
  Green == Green = True
  _     == _     = False
  show Red   = "Red"
  show Green = "Green"

class Describe a where
  describe :: a -> String
  describe _ = "something"

class Name a where
  name :: a -> String
  name _ = "nameless"

instance Show a => (Describe [a], Name [a]) where
  describe xs = "a list of length " ++ show (length xs)
  name = show

The classes can also be given by a constraint synonym. An instance declaration without a where gives instances where all methods have their default definitions:

type Both a = (Describe a, Name a)

instance Both Bool

Qualified strings

A string literal can be qualified with a module name, M."...". This means M.fromString "...", using whatever fromString is in scope as M.fromString. It gives a lightweight way to have string literals of different types without turning on OverloadedStrings for the whole module.

String interpolation

A string literal prefixed by s can contain interpolated expressions, written ${expr}:

greet :: String -> Int -> String
greet name n = s"Hello ${name}, you are number ${n + 1}"

Interpolation also works with multi-line strings, s"""...""", and interpolated strings can be nested.

The string s"foo ${e} bar" is translated into

interpolateFinalize (interpolateRaw "foo " `interpolateAppend`
                     interpolateValue e    `interpolateAppend`
                     interpolateRaw " bar" `interpolateAppend`
                     interpolateEmpty)

The unqualified form uses the definitions in Data.String.Interpolate, where interpolateValue uses the Interpolate class (similar to Show, but strings and characters are not quoted) and the result can be any IsString type. A qualified form, M.s"...", uses M.interpolateRaw etc. instead, so you can provide your own interpretation. Data.String.Interpolate.Basic is a simple alternative where all interpolated values must already have the result type.

Type-level literals

Natural numbers and strings can be used as types, with the kinds Nat and Symbol. The classes KnownNat and KnownSymbol, with the methods natVal and symbolVal, turn them into values. They are all exported from Data.TypeLits, which in GHC is called GHC.TypeLits. For example:

import Data.TypeLits
import Data.Proxy

newtype Vec (n :: Nat) = Vec [Int]

vlen :: forall n . KnownNat n => Vec n -> Integer
vlen _ = natVal (Proxy :: Proxy n)      -- vlen (Vec [] :: Vec 3) is 3

In GHC, type-level literals are part of DataKinds (see type-level literals). MicroHs only has the literals; it cannot use data types as kinds, and there are no type-level operations on numbers or strings.

Records

MicroHs implements the overloaded record extensions. A field a of a record r can be accessed as r.a, as well as with the usual a r. The former is overloaded and works for any record type with a field a, whereas the latter uses the usual monomorphic field selector. A field update has the usual syntax, r{ a = e }, but it is also overloaded, so it can update the field a of any record type. The type classes HasField and SetField capture this: HasField "name" rec ty means that the record type rec has a field name of type ty, which can be extracted with getField, and SetField "name" rec ty means that the field can be set with setField.

Record updates can also update nested fields, e.g., r{ a.b.c = e }. This does not easily work in GHC, since GHC does not fully implement OverloadedRecordUpdate. When GHC decides how to do it, MicroHs will follow suit.

Record updates cannot change the type of polymorphic fields.

Libraries

The Prelude contains the functions from the Haskell Report and a few extensions. The base package contains most of what GHC has in base.

To avoid the Prelude completely (which is needed in parts of base to avoid circular imports), use import qualified Prelude(). The compiler then does not even open Prelude.hs, and it also skips the automatic qualified import of Mhs.Builtin. Note that the NoImplicitPrelude pragma has no effect.

MicroHs specific modules

Besides the usual modules, base has some modules that are specific to MicroHs:

Serialization

System.IO.Serialize can write any value to a handle and read it back, even functions and values with sharing or cycles. The exceptions are values that refer to C data, such as Ptr, FunPtr, and file handles (except stdin, stdout, and stderr), and MVars, ThreadIds, and weak pointers. The value is written in the combinator file format, so it can only be read by a program with the same version of the runtime.

Use hSerializeDescr and hDeserializeDescr when you can, since they are safer. They need a Data instance for the type. hSerializeDescr writes a checksum of the complete type (all constructors and the types of their fields, recursively) before the value, and hDeserializeDescr returns Nothing if it does not match the type that it is expected to read. Functions have a Data instance too, and the checksum of a function type includes its argument and result types, so this also works for functions and for data types with function fields:

import Data.Data
import System.IO
import System.IO.Serialize

data Shape = Circle Double | Rect Double Double
  deriving (Show, Data)

main :: IO ()
main = do
  withBinaryFile "shapes.ser" WriteMode $ \ h -> hSerializeDescr h [Circle 1, Rect 2 3]
  r <- withBinaryFile "shapes.ser" ReadMode hDeserializeDescr
  print (r :: Maybe [Shape])      -- Just [Circle 1.0,Rect 2.0 3.0]

hSerialize and hDeserialize do no check at all, and reading a value as the wrong type will probably crash the program. Use them only for values whose type has no Data instance. There are also writeSerialized and readSerialized, which work on files, and writeSerializedCompressed, which compresses the data (readSerialized handles both).

Report compliance

Module Report compliant Comment
Prelude yes1 missing catch (as in GHC)
Control.Monad yes1 fail not in Monad (as in GHC)
Data.Array yes  
Data.Bits yes  
Data.Char no missing lexLitChar, readLitChar
Data.Complex yes1 no datatype context
Data.Int yes  
Data.Ix yes  
Data.List yes  
Data.Maybe yes  
Data.Ratio yes  
Data.Word yes  
Foreign yes  
Foreign.C yes  
Foreign.C.Error yes  
Foreign.C.String no missing functions (in particular CWString related)
Foreign.C.Types no missing/wrong instances
Foreign.ForeignPtr no missing FinalizerEnvPtr, newForeignPtrEnv, addForeignPtrFinalizerEnv, finalizeForeignPtr, unsafeForeignPtrToPtr
Foreign.Marshal yes  
Foreign.Marshal.Alloc yes  
Foreign.Marshal.Array yes  
Foreign.Marshal.Error yes1 void :: Functor f => f a -> f ()
Foreign.Marshal.Utils yes  
Foreign.Ptr yes freeHaskellFunPtr does nothing
Foreign.StablePtr yes  
Foreign.Storable yes  
Numeric yes  
System.Environment yes  
System.Exit yes  
System.IO no some missing functions and types
System.IO.Error yes1 renamed catch, try to catchIOError, tryIOError (as in GHC)

1. not quite, but close enough, see comment

FFI

MicroHs supports foreign import ccall, foreign import capi, foreign export ccall, foreign import javascript, and foreign export javascript (the last two for the emscripten target, see JavaScript). When running a program directly (using -r), in the interactive system, or when generating a .comb file, only the C functions built into the runtime (plus those from embedded packages) can be called. When generating a .c file or an executable, any C function can be called.

As in GHC, the import string can name header files and use & to import the address of a C object. In addition, MicroHs has a non-standard form, "value EXPR", which imports the value of an arbitrary C expression. Inside EXPR, $1, $2, … (up to $9) are replaced by the function’s arguments, numbered from 1 as in a JavaScript import (and as in GHC); any other $k, in particular $0, is an error. For example:

foreign import capi "value EINTR" eINTR :: Errno
foreign import ccall "value ($1 + $2) * 2" addTwice :: CInt -> CInt -> IO CInt

The expression is pasted verbatim into the generated C code, so it must be a valid C expression for the argument and result types. A type without IO gives a pure value.

As in GHC, foreign import ccall "dynamic" turns a pointer to a C function into a Haskell function; its type must be FunPtr ft -> ft. For example:

foreign import ccall "dynamic" callIntFun :: FunPtr (CInt -> IO CInt) -> CInt -> IO CInt

Like other imports of C functions, it needs a .c file or an executable. A call through a pointer has no C prototype to convert the arguments and the result, so the types must match the C function exactly. The types from Foreign.C.Types, Int8 to Int64, Word8 to Word64, Float, Double, Ptr, and FunPtr (and newtypes of them) are passed as the corresponding C types; Int and Word are intptr_t and uintptr_t.

Some of the FFI is still missing compared to GHC. In particular, foreign import ccall "wrapper" is not implemented.

Calling Haskell from C

A function exported with foreign export ccall can be called from C. Compile the module with -c, which leaves out the C main of the runtime, so the module does not need a main either. mhs also writes the header file M_stub.h (for module M, next to the output file) with prototypes for mhs_init and the exported functions. The C code must call mhs_init() once, before it calls any exported function. For example, with

module ForExp where

foreign export ccall funcName :: Int -> IO Int
foreign export ccall "other" (*) :: Int -> Int -> Int    -- exported as other

funcName :: Int -> IO Int
funcName x = do
  putStrLn "funcName called"
  pure (x + 1)

and the C program main.c

#include <stdio.h>
#include "ForExp_stub.h"

int main(void) {
  mhs_init();
  printf("%d %d\n", (int)funcName(5), (int)other(6, 7));
  return 0;
}

the Haskell code can be made into a shared library:

mhs -c -optc --shared -optc -fPIC ForExp -olibforexp.so
cc main.c -L. -lforexp -o main

On Linux, also add -Wl,-rpath,'$ORIGIN' to the cc command (or set LD_LIBRARY_PATH), so that the library is found when the program runs.

Alternatively, mhs -c ForExp -oForExpHs.c writes the C code for the Haskell part. Compile it together with the runtime, src/runtime/eval.c, and the C program, with the directories src/runtime and src/runtime/unix (or another platform) as include directories.

JavaScript

With the emscripten target (see Targets), foreign import javascript calls JavaScript code. The import string is the body of a JavaScript function, where $1, $2, … (up to $9) are the arguments, numbered from 1 as in GHC and in a "value" import. The arguments can have the types Int, Double, Float, and Ptr, and the result can also be (). As usual, the result can be in IO:

foreign import javascript "return jsAdd($1, $2)" jsAdd :: Int -> Int -> IO Int

A function like jsAdd can be defined in a JavaScript file that is given on the command line, e.g., mhs -temscripten add.js Main -oout.js. The file is embedded in the output. A package can also provide JavaScript files, in its jsbits directory; they are embedded in every program that uses the package.

foreign export javascript makes a Haskell function callable from JavaScript, where its name gets a _ prefix, as usual with emscripten. Such a function can also have Bool arguments and results, which become 0 and 1. As for C, compile the module with -c, and call _mhs_init() before any exported function. The testforexpjs target in tests/Makefile shows how to compile such a module with emcc and call it from JavaScript.

Preprocessor

Sadly, many Haskell packages need the C preprocessor. MicroHs uses cpphs, and the distribution contains the combinator code for it, so make builds bin/cpphs. The symbol __MHS__ is defined when compiling with MicroHs. As in GHC, so are OS_HOST_OS and ARCH_HOST_ARCH (and OS_BUILD_OS and ARCH_BUILD_ARCH), where OS and ARCH are the values of System.Info.os and System.Info.arch, which are the names GHC uses, e.g., darwin_HOST_OS, linux_HOST_OS, aarch64_HOST_ARCH, and x86_64_HOST_ARCH. On Windows the system is mingw32 when the runtime is compiled with MinGW (as for GHC), and windows otherwise, e.g., with cl.


Compiler

The compiler takes the name of a module (or a file name) and compiles it. The module should contain the function main of type IO (), which is the entry point of the program. If no module is given, the compiler starts in interactive mode.

Modules

A module M.N is looked for as the file M/N.hs (or .lhs, or .hsc, which is run through hsc2hs) in each directory of the module search path, which defaults to . and can be changed with -i. If it is not found there, the installed packages are searched (see Packages). If the name given on the command line ends in .hs or .lhs it is treated as a file name.

Compiler flags

Flag Meaning
-h, -? Print short usage
--help Print all flags
--version Print the version
--numeric-version Print just the version number
-v Increase verbosity (can be repeated)
-q Be quiet
-oFILE Output to FILE. If FILE ends in .comb, produce a combinator file. If it ends in .c, produce a C file. Otherwise compile the combinators together with the runtime system to produce an executable. Default is out.comb.
-r Run the program directly instead of writing a file
-c Leave out the runtime’s C main, e.g., to build a library (see Calling Haskell from C)
-eEXPR Evaluate EXPR (in the context of the given modules)
--interactive Start interactive mode even with module arguments
-iPATH Add PATH (colon separated) to the module search path
-i Clear the module search path
-aPATH Add PATH (colon separated) to the package search path
-a Clear the package search path
-PPKG Build package PKG from the given modules
-Q PKG [DIR] Install package PKG, optionally into DIR
-L[FILE\|PKG] List all modules of a package
-pFILE Preload a package
-tTARGET Select a target from mhs.conf (see Targets)
-optc OPTION Pass an option to the C compiler
-optl OPTION Pass an option to the C compiler for linking
-XCPP Run cpphs on all source files
-Dxxx, -Ixxx Passed to cpphs
-F Run a preprocessor on the source files
-pgmF CMD Use CMD as the -F preprocessor
-optF FLAG Pass FLAG to the -F preprocessor
-C[PATH] Read and write the compilation cache, optionally at PATH (default .mhscache)
-CR[PATH] Only read the compilation cache
-CW[PATH] Only write the compilation cache
-z Compress the combinator code (LZMA)
-b64 Base64 encode the combinator code
-T Generate dynamic function usage statistics
-l Show every time a module is loaded
-s Show compilation speed in lines/s
-fno-code Type check only; do not generate code
-ECMD Set the editor for the :edit command
-interactive-print FUN Use FUN to print values in interactive mode
--stdin Use stdin in the interactive system (no line editing)
--embed-packages PKG:... Embed packages (and their FFI stubs) in an mhs binary
--embed-ffis PKG:... Embed the FFI stubs of packages in an mhs binary
-ddump-PASS Debug: print the program after PASS, one of preproc, parse, derive, expandInst, typecheck, desugar, linked, toplevel, combinator, all (see Dump flags)
-- End of compiler arguments; the rest are passed to the program (with -r)

Files ending in .c, .o, or .a on the command line are passed to the C compiler, and .js files are embedded in the output (for targets that support it).

With the -v flag the processing time for each module is reported, e.g.

importing done MicroHs.Exp, 284ms (91 + 193)

which means that processing MicroHs.Exp took 284ms, with parsing taking 91ms and type checking and desugaring taking 193ms.

Compilation cache

With the -C flag the compiler writes its internal cache of compiled modules to .mhscache at the end of compilation. At startup it reads this file if it exists, and validates the contents using an MD5 checksum of each file in the cache. This can make compilation much faster, since a cached module is not parsed and type checked again. Do not use -C when you are changing the compiler itself; if the cached data types change the compiler will probably just crash.

Environment variables

Interactive mode

If no module name is given, the compiler enters interactive mode. You can also use --interactive to enter it after loading some modules. Normally input is read from the terminal with line editing (see below). With the --stdin flag, input is read as plain lines from standard input without line editing, which is useful when input is piped from a file or another program, e.g., mhs --stdin < script.txt.

At the prompt you can enter an expression to evaluate it, a top level definition (or an import) to add it, or a command starting with :. An expression of type IO a is run, and its result is printed unless it is (). Any other expression is printed with show. If an expression uses a qualified name, e.g., Data.Map.empty, and the module is not imported, a qualified import is added automatically.

Commands

Commands can be abbreviated to any unique prefix, e.g., :t for :type.

Command Meaning
:quit Quit
:{ Start multi-line input, ended by a line with :}
:clear Clear all definitions and imports
:reload Reload all modules
:delete PRE Delete the definitions (and imports) whose lines start with PRE
:defs Show the current definitions
:type EXPR Show the type of EXPR
:kind TYPE Show the kind of TYPE
:main ARGS Run main with the given arguments
:save [FILE] Save the current definitions to a file
:edit [FILE] Edit a file, or the location of the last error, and then reload
:find NAME Edit the file containing the definition of NAME
:! CMD Run a shell command
:set [OPT] Show the options, or set an option (see below)
:help, :? Show the commands

The options for :set are:

The editor used by :edit and :find is set with the -E flag, e.g., '-Eemacs +%d %s', where %d is replaced by the line number and %s by the file name. The default is vim +%d %s.

Line editing

The input line can be edited with Emacs-like keys:

Key Action
Ctrl-A, Home Go to beginning of line
Ctrl-E, End Go to end of line
Ctrl-B, Left Move back one character
Ctrl-F, Right Move forward one character
Backspace Delete the character before the cursor
Ctrl-D, Delete Delete the character under the cursor
Ctrl-K Delete to the end of the line
Ctrl-U Erase the whole line
Ctrl-P, Up Previous line in the history
Ctrl-N, Down Next line in the history
Ctrl-R Reverse incremental search in the history
TAB Complete an identifier, module name, or keyword
Return Submit the line
Ctrl-C Interrupt a running evaluation

During an incremental search (Ctrl-R), typed characters extend the search string, Ctrl-R finds the next older match, Backspace undoes the last step, and Ctrl-G aborts the search. Any other key accepts the found line and then performs its usual action.

All input lines are saved in ~/.mhsi, which is read at startup so the history persists between sessions.

Targets

mhs compiles the combinators together with the runtime system using a C compiler. How this is done is controlled by the configuration file mhs.conf (installed in the mhs data directory), and the -t flag selects a target. A target section looks like this:

[unix]
cc = "cc"
ccflags = "-w -Wall -O3"
cclibs = "-lm"
conf = "unix"

The keys are cc (the C compiler), ccflags (flags at the start of the command), cclibs (flags at the end), conf (which src/runtime/ platform directory to use), cout (the flag for the output file, default -o), and js (the flag to embed a JavaScript file).

The distributed targets are:

You can add your own targets to mhs.conf.

For example, with emcc and node installed:

mhs -temscripten Example -oout.js
node out.js

The generated JavaScript file contains the WASM code embedded as a blob. Running via JavaScript/WASM is almost as fast as running natively.

The [mhs] section of mhs.conf has the key packageDbPath, which is the default package search path.

Profiling

Compiling with -T adds a counter to every top level function. Running the program with +RTS -T -RTS then prints, when the program exits, how many times each function was called. Functions that were never called are left out. For example, for a module Fib whose main computes fib 20:

$ mhs -T Fib -ofib
$ ./fib +RTS -T -RTS
...
Fib.fib                                                           21891

Only code compiled with -T has counters, so, e.g., functions from installed packages are not counted.

For overall numbers, use +RTS -v -RTS, which prints the number of reductions, allocated cells, garbage collections, etc. In interactive mode, :set +s shows the time, reductions, and allocated cells for each evaluation.

Debugging


Runtime flags

Programs compiled with MicroHs, including mhs itself, take runtime flags between +RTS and -RTS. All other arguments are passed to the running program.

For example, ./prog +RTS -H1M -v -RTS hello runs prog with a heap of 1M cells and prints statistics at the end, and the program gets the single argument hello.

The heap and the stack have a fixed size; they do not grow. A program that runs out of heap stops with the error heap exhausted, and one that runs out of stack stops with stack overflow. Run it again with a bigger -H or -K.


Packages

To avoid compiling everything from source every time, modules can be precompiled into packages. A package is a set of modules that are compiled together and then installed in a known place. Packages can depend on other installed packages.

mhs needs no extra flags to use installed packages; all installed packages are always visible. When compiling to an executable, only the parts of a package that are actually used are included.

Creating and installing a package with mhs

To build a package, use mhs -Ppackage-name -opackage-name.pkg modules..., where modules... are the modules to expose from the package. Other modules that are needed are included automatically.

To install a package, use mhs -Q package-name.pkg [install-dir]. If install-dir is left out, the package is installed in the default place.

To list the modules in a package, use mhs -Lpackage-name.pkg.

MicroCabal (mcabal)

Normally you don’t call mhs directly to build packages. Instead you use mcabal, a reimplementation of a subset of Cabal, which is included with MicroHs. It reads the package’s .cabal file and does the right thing.

To get a consistent set of packages, MicroCabal uses Stackage (nightly by default) to pick package versions. It assumes a Unix-like system with curl (or wget, if MICROCABAL_USE_WGET is set) and tar.

Installed package organization

Packages are installed in ~/.mcabal/ (or $CABALDIR) with the following layout:

There can only be one version of a package installed in a directory. If you need multiple versions, use different directories and the -a flag. There are no checks for consistency among packages, and packages compiled with different versions of the compiler are not compatible.

Embedding packages in mhs

Normally mhs finds packages in the package search path, but packages can also be built into the mhs binary itself, e.g., to get a compiler that does not need any installed packages. When compiling the compiler (the module MicroHs.Main), the flag --embed-packages PKG1:PKG2:... puts the given packages into the binary. They are loaded when mhs starts, as if they were installed. For example:

mhs -i -imhs -isrc MicroHs.Main --embed-packages base -omhs-base

When running a program directly (-r), in the interactive mode, or when generating a .comb file, a foreign import can only call C functions that are in the mhs binary. --embed-ffis PKG1:PKG2:... includes the C wrappers for the foreign imports of the given packages, without embedding the packages themselves. --embed-packages does this for the packages it embeds.

Porting a package

Hackage is full of great packages; unfortunately most of them contain some GHC specific code. Some compile as is, many need small changes. Here are some tips:

When you have a working port, please try to get the changes upstream, and report the status.

Available packages

Included in base (and installed with the compiler): array, bytestring, deepseq, directory, hashable, process, stm, text (with varying degrees of completeness).

Some important packages that are known to work: containers, transformers, mtl, parsec, filepath, time, random, QuickCheck, hspec, HUnit, pretty, prettyprinter, optparse-applicative, unordered-containers, async, split, fgl, cpphs.

make -f Makefile.packages installs a large set of packages that are known to compile. There is also a spreadsheet with the status for many packages. If a package is not listed it just means that nobody has reported success or failure with it. Please do so.


Implementation

Compiler

The compiler is written in MicroHs and lives in src/MicroHs/. It can also be compiled with GHC (make bin/gmhs) and with a slightly patched Hugs (see below). When compiling with GHC, the ghc/ directory provides some compatibility modules. The compiler also uses some modules of base, which are in lib/libmhs, so that GHC and Hugs can compile them too; they import MiniPrelude, which ghc/ and hugs/ provide as well.

The compiler pipeline is:

  1. Lexing and layout processing (Lex), and parsing to an abstract syntax tree (Parse, Expr).
  2. Deriving instances (Deriving).
  3. Fixity resolution (Fixity) and type checking (TypeCheck, TCMonad), which also translates type classes to dictionary passing.
  4. Desugaring to a simple lambda calculus (Desugar, Exp), where constructors and case become special combinators (EncodeData), see Data type encoding.
  5. Translation to combinators by bracket abstraction, with optimizations (Abstract), see Combinators.
  6. Serialization of the combinator graph (ExpPrint), optionally compressed and turned into a C array (MakeCArray), see Combinator file format.

Other important modules:

Dump flags

The -ddump-PASS flags print the program at different stages of compilation, which is useful when working on the compiler. Several flags can be given at once, and -ddump-all turns on all of them.

The following flags print each module as it is compiled. Modules that are loaded from the compilation cache or from an installed package are not compiled, so they are not printed.

The following flags print the whole program, including the library, so the output is large.

Bootstrapping

The repository contains the compiler itself compiled to combinators (as C code) in generated/mhs.c. This is how mhs is built from just the C compiler.

To rebuild the compiler after changing it, use make newmhs (or make newmhsz to compress). make bootstrap recompiles the compiler twice and compares the outputs to make sure the new compiler still works.

MicroHs can also be built from scratch in the sense of bootstrappable.org, using Hugs (make bin/hmhs). This needs a slightly patched version of Hugs, to work around undefined behavior with arithmetic overflow.

Combinators

Bracket abstraction (Abstract) removes all lambdas using S, K, and I. A number of rewrites then introduce the other combinators, which give smaller code and fewer reductions. Some rewrites remove combinators altogether, e.g., S K x → I, S (K x) (K y) → K (x y), S (K x) I → x, B I x → x, and Y (K x) → x.

Combinator Reduction Introduced by
S S x y z = x z (y z) bracket abstraction
K K x y = x bracket abstraction
I I x = x bracket abstraction
B B x y z = x (y z) S (K x) y → B x y
C C x y z = x z y S x (K y) → C x y
S' S' x y z w = x (y w) (z w) S (B x y) z → S' x y z
C' C' x y z w = x (y w) z C (B x y) z → C' x y z
B' B' x y z w = x y (z w) B B → B'
C'B C'B x y z w = x z (y w) C' B → C'B
A A x y = y K I → A
U U x y = y x C I → U
Z Z x y z = x y B K → Z
K2 K2 x y z = x Z K → K2, K (K x) → K2 x
K3 K3 x y z w = x Z K2 → K3, K (K2 x) → K3 x
K4 K4 x y z w v = x Z K3 → K4, K (K3 x) → K4 x
P P x y z = z x y C (C I x) y → P x y, B C (C I) → P
R R x y z = y z x C C → R
O O x y z w = w x y B (B K) P → O
Y Y x = x (Y x) recursive let

The runtime implements Y x by making the redex point to itself, so it builds a cyclic graph. A combinator that returns one of its arguments (e.g., I, K, and A) overwrites the redex with an indirection; the others overwrite it with the result, allocating cells for the new inner applications. The rewrites can increase the arity of an expression, so a few combinators also reduce when they have too few arguments, e.g., B' x y = B (x y) and Z x y = K (x y). This keeps the sharing (full laziness) of the original code.

When the program has been loaded, the garbage collector also does some reductions that make the graph smaller, e.g., I x → x and K x y → x. A program can ask for this with performGCWithReduction from System.Mem.

Besides combinators, the code contains literals, the data type combinators described below, and primitive operations such as +, ==, seq, and the IO operations. The runtime lists them all in the primops table in src/runtime/eval.c.

Data type encoding

Data types are not encoded as functions; the runtime handles constructors and case directly. The encoding is generated by EncodeData.

Constructors

Constructor number k with n fields is the combinator C_k_n, where the constructors are numbered from 0 in the order they appear in the data declaration. A value is the constructor applied to its fields. For example, with data Maybe a = Nothing | Just a, Nothing is C_0_0 and Just 42 is C_1_1 42. A constructor applied to at most n arguments is in weak head normal form. A constructor with strict fields is a function that evaluates those fields before building the value, e.g., \ x y -> seq x (C_0_2 x y) when the first field is strict. A newtype constructor is just I.

The runtime knows the encoding of a few types, since some primitives take or return them:

Type Constructors
Bool False = C_0_0, True = C_1_0
Ordering LT = C_0_0, EQ = C_1_0, GT = C_2_0 (returned by the comparison primitives, e.g., icmp and bscmp)
Maybe a Nothing = C_0_0, Just = C_1_1 (returned by, e.g., tryTakeMVar and deRefWeak)
[a] [] = C_0_0, (:) = C_1_2
tuples () = C_0_0, (,) = C_0_2, (,,) = C_0_3, …

The runtime also knows the Exception class, so that it can show an exception that has no handler. It does that with D_2 (U (K2 A)), i.e., a case on the SomeException, whose fields are the Exception dictionary and the exception itself, that selects displayException from the dictionary and applies it to the exception. This code is built by the runtime (combShowExn in src/runtime/eval.c), so a change to SomeException or to the Exception class in Control.Exception.Internal must be reflected there.

Case

A case on a type with m constructors normally becomes

D_a0_..._a{m-1} f0 ... f{m-1} e

where e is the scrutinee, ak is the number of fields of constructor k, and the arm fk is a function of those fields. Arms that are not in the case are filled in with the default alternative, which ignores the fields. For example:

case xs of { [] -> a; y:ys -> b }    becomes    D_0_2 a (\ y ys -> b) xs
if c then t else e                   becomes    D_0_0 e t c

Mutually recursive local definitions are combined into a tuple v, and the ith of n components is selected with D_n (\ x1 ... xn -> xi) v.

The runtime does not need the arities ak, since a constructor knows its number of fields. They are there so that the combinator code can be turned back into lambda expressions, e.g., by Mhs.Reflect: after bracket abstraction the number of fields cannot be read from an arm (\ x xs -> x is just K). Below, D_m stands for a dense case with m arms.

If the type has more than 4 constructors and fewer than 3/4 of them have an arm, a sparse case is used instead:

E_k1_n1_..._km_nm d f1 ... fm e

Here m is the number of arms, d is the default, and the arm fj is for constructor kj, which has nj fields. The arms are sorted by constructor number. Since the constructor numbers are part of the combinator, bracket abstraction cannot separate them from the case. Below, E_m stands for a sparse case with m arms.

The scrutinee comes last so that \ x -> case x of ... becomes just D_m f0 ... f{m-1} after bracket abstraction, without any extra combinators.

Evaluation

The constructor and case combinators take no space in the heap. Their tag, the constructor number, and the number of fields (or arms) are stored in the pointer itself (see Memory layout). There are 11 bits for the constructor number and 8 bits for the number of fields. A D_m or E_m uses those 19 bits for an index into a table of case arities, where each entry holds m, the arities, and for an E_m the constructor numbers. Equal entries are shared, and the table is never freed.

To reduce D_m f0 ... f{m-1} e, the runtime leaves the arms on the stack, pushes a marker, and evaluates e. When the evaluation of e reaches a constructor C_k_n applied to its n fields, the marker is right below it on the stack. The runtime then selects the arm fk and overwrites the case redex with fk e1 ... en, which needs n-1 new cells (or with an indirection to fk when n is 0). For E_m, the arm is found by binary search on the constructor numbers in the table, and if there is no match the result is d. A constructor that is not directly above a marker is a value.

Class dictionaries

Type classes are translated to dictionary passing, but dictionaries do not use the constructor encoding. A dictionary is a function that applies its argument to the superclass dictionaries and the methods, in the order they are declared. The dictionary constructor for a class C with n components is

C$C = \ x1 ... xn f -> f x1 ... xn

and the component number i is selected by

\ d -> d (\ x1 ... xn -> xi)

After bracket abstraction a selector is just a few combinators. For example, pure, which is the second of the six components of Applicative, is U (K K4).

Runtime

The runtime system is written in C and is mainly in src/runtime/eval.c. It is a graph reduction machine for combinators, with primitive operations for built in types and for executing IO operations. The C code is reasonably portable and has no dependencies beyond a C compiler and (optionally) a C library.

The runtime also contains:

Types

Some types are primitive and known by the runtime, e.g., Int, Word, Double, Float, Ptr, IO, and arrays. The function type, ->, is (of course) also built in. All other types are defined in Haskell, and the compiler encodes them with constructor and case combinators. The runtime knows how booleans, orderings, Maybe, lists, and tuples are encoded (see Data type encoding).

Memory layout

Memory is allocated in cells. Each cell has room for two pointers (two words, typically 16 bytes), so it can represent an application node. A few bits indicate if the cell is an application or something else. If it is something else, one word is a tag, e.g., an integer or an indirection, and the other word stores the payload, e.g., the integer value.

Cells are aligned, so the two lowest bits of a real pointer are always 0. A pointer whose lowest bits are 10 does not point anywhere; instead it holds a tag, e.g., a combinator, a primitive, or a constructor. Such values take no space in the heap.

There is a bitmap with one bit per cell. Allocating a cell consists of finding the next free cell using the bitmap and marking it as used; in practice whole runs of free cells are claimed at once. The garbage collector clears the bitmap and then marks every reachable cell. There is no explicit scan phase, since that is baked into the allocation. Allocation is fast, assuming the CPU has some kind of find-first-set instruction.

The evaluator

The evaluator, evali, reduces an expression to weak head normal form. It walks down the left spine of applications, pushing each application node on the stack, until it finds something that is not an application, e.g., a combinator. If the stack has enough arguments, the combinator is reduced by overwriting the topmost application node of the redex with the result, so the result is shared. Otherwise the expression is already in weak head normal form, and the evaluator returns. Indirection nodes are followed and short-circuited on the way. A reduction that allocates cells first makes sure that there are enough free cells, and runs a garbage collection if needed. The roots for the garbage collector are the stack, the threads, and some global tables.

There is a single stack. A recursive call of the evaluator uses the part above its caller’s part, but recursive calls are avoided where possible, since they also use C stack. A strict primitive, e.g., + on Int, pushes a marker and evaluates one argument. When the evaluator returns to the marker, it changes the marker and evaluates the other argument, and when it returns to the changed marker, it performs the operation. case works in a similar way (see Data type encoding).

An IO action is a function that takes a world token and returns a pair of the result and a new world token. The pair is Scott encoded with P (P r w k = k r w), so return is just P, and >>= is just C: C m f w = m w f, and when m w has been reduced to P r w', this is f r w'. unsafePerformIO applies the action to a world token, and selects the result with K. The primitive IO operations return their results in the same way.

catch sets up a handler with setjmp, and evaluates the protected action with a recursive call of the evaluator. Throwing an exception does a longjmp to the innermost handler, which runs the handler action. An exception that is not caught kills the thread, and the program if it is the main thread.

Each thread has a root node, its IO action applied to a world token, and the scheduler evaluates the root of the thread at the front of the run queue. When the thread’s time slice runs out, or the thread blocks, e.g., on an MVar, the thread’s stack is simply thrown away, and the next thread runs. All reductions have been done in place in the graph, so evaluating the root again later resumes the computation where it left off. Exception handlers are set up again when the evaluation passes the catch.

Configuration

The runtime is configured for each platform by a config.h in a subdirectory of src/runtime/. It contains a number of WANT_ macros that select functionality, e.g., WANT_STDIO (file I/O), WANT_FLOAT32/WANT_FLOAT64 (floating point), WANT_INT64 (64 bit integers on 32 bit platforms), WANT_IMATH and WANT_GMP (which implementation of Integer to use), WANT_DIR, WANT_TIME, WANT_SOCKET, etc. It also defines how to do platform specific things, such as finding the first set bit. Platform specific code goes in extra.c in the same directory.

Some other macros control how the runtime works. These are set in config.h:

These have defaults, and can be set with -D, e.g., mhs -optc -DMARK_PFQ=0 ...:

Implementations of Integer

There are three implementations of Integer:

imath and GMP have the same interface, so the Haskell code in lib is the same for both. The Haskell implementation replaces two modules, Data.Integer_Type and Data.Integer.Internal, which are in lib/no-gmp. The library code and the runtime must agree: code compiled for imath or GMP calls C functions that a runtime without them does not have, and it fails with an error like FFI unknown mpz_cmp. To compile a program that uses the Haskell implementation, put lib/no-gmp before lib in the module search path, and compile the runtime without imath, e.g., with $MHSDIR being the MicroHs source directory:

mhs -i -i. -i$MHSDIR/lib/no-gmp -i$MHSDIR/lib -optc -DWANT_IMATH=0 Prog -oprog

Platforms

MicroHs needs a C compiler (C99 or so) and not much else. The runtime works on 32 and 64 bit platforms, both little- and big-endian. The cell size is two words, so 8 bytes on 32 bit platforms (12 bytes if Double is enabled) and 16 bytes on 64 bit platforms.

The configurations in src/runtime/ are:

Directory Platform Notes
unix Linux, macOS, BSD, and other Unix-like systems Full functionality. Tested with gcc, clang, and tcc.
windows Windows with MSVC (cl) Build with nmake -f Makefile.windows. 32 and 64 bit.
mingw Windows with MinGW  
micro Generic micro-controller No file system; the program is read from memory.
stm32f4 STM32F4 micro-controllers Example in boards/STM32F407G-DISC1.
esp32 ESP32 micro-controllers Example in boards/ESP32-C3-DevKitM-1.
c64 Commodore 64, using cc65 Example in boards/C64. Very limited.

Also:

Requirements:


Contributing

Contributions are very welcome! Bug reports, missing library functions, ported packages, and compiler improvements are all appreciated. Open an issue or a pull request at github.com/augustss/MicroHs. See also the AI policy.

Building

Changing the combinator format

The combinator file format has a version, which must be the same in src/runtime/eval.c (VERSION) and src/MicroHs/ExpPrint.hs (combVersion). Change it whenever existing combinator files would no longer work, e.g., when the data type encoding changes, or a primitive is removed or changes meaning. Then old files are rejected, instead of misbehaving.

After such a change all the combinator code in generated/ must be regenerated, not just the compiler, i.e., also cpphs.c, mcabal.c, install.c, tester.c, and the base package, base.pkg. make preparedist does all of this. It needs GHC, a checkout of MicroCabal next to the MicroHs directory, the cpphs sources (it fetches them as a git submodule), and emscripten (for generated/mhseval.js).

Libraries

The libraries live in the lib/ directory. Adding missing functions, instances, and types from the Report or from GHC’s base is a welcome contribution. So are improvements to the bundled versions of packages that are heavily GHC specific, such as array, bytestring, and text.

Tests

The test suite is in the tests/ directory. To run it, do

To add a test, create MyTest.hs and MyTest.ref, where the latter contains the expected output, and add a line MyTest to tests/all.tests. The file explains how to give input, expected error output, and compiler flags. Tests that check compiler error messages go in tests/err.tests in the same way, with the expected message in the .ref file.

Measuring performance

Adding a primitive

To add a new primitive, change src/runtime/eval.c:

Then the primitive can be used with _primitive "myPrimitive". The interactive mode reads its code the same way as the runtime, so the primitive works there too.

Thank you

A big thanks goes to the people who have contributed to MicroHs: @amigalemming, @arossato, @benclifford, @claudeha, @dmjio, gay@disroot.org, @gergoerdi, @ikervagyok, @jmaessen, @juhp, @kolmodin, @konsumlamm, @liolin, @lortabac, @MaximilianAlgehed, @meooow25, @philderbeast, @rewbert, @sol, @Superstar64, @thielema, @thimc, @thma, @treeowl, @TristanCacqueray, @tvmaaren, @yobson.