diff --git a/README.md b/README.md
new file mode 100644
--- /dev/null
+++ b/README.md
@@ -0,0 +1,45 @@
+# Haskell package: happy-arbitrary
+
+Random programs for testing parsers made with Happy and Alex. It reads the
+parser's own grammar (`.y`) and lexer (`.x`), so the programs follow the
+grammar, and it asks the language's lexer whether their text lexes back to the
+tokens it generated.
+
+## Example
+
+A property that printing a parsed program and parsing it again gives the same
+output:
+
+```haskell
+import Language.Alex.Parser (parseAlex)
+import Language.Happy (parseGrammar, runAlex)
+import Language.Happy.Linker (Lexer, defaultLinkConfig, generateChecked)
+
+-- | The token classes our lexer finds, named like in the %token patterns.
+classes :: Lexer
+classes = either (const Nothing) (Just . map (Text.pack . show . MyLexer.lexemeClass)) . MyLexer.scan
+
+spec :: Spec
+spec = do
+    alex <- runIO $ either error id . parseAlex <$> Text.readFile "src/Lexer.x"
+    happy <- runIO $ either error id . flip runAlex parseGrammar <$> LBS.readFile "src/Parser.y"
+    let programs = generateChecked defaultLinkConfig alex classes "Program" happy
+
+    it "prints the same after parsing what it printed" $
+        forAll (programs `suchThatMap` (either (const Nothing) Just . MyParser.parse)) $ \ast ->
+            let printed = MyPrinter.print ast
+            in MyPrinter.print <$> MyParser.parse printed `shouldBe` Right printed
+```
+
+Programs have QuickCheck's size in tokens. The grammar doesn't know the checks
+in the parser's actions or in later passes, so the test drops the programs that
+the real parser rejects.
+
+By default, a `%token` pattern like `{ L _ IdVar _ }` names the token class
+`IdVar`, and so does a lexer action like `{ mkL IdVar }`. A `LinkConfig` can
+find the class in other code.
+
+## Documentation
+
+See [doc/design.md](doc/design.md) for how it works, and
+[doc/development.md](doc/development.md) for building and testing it.
diff --git a/doc/design.md b/doc/design.md
new file mode 100644
--- /dev/null
+++ b/doc/design.md
@@ -0,0 +1,76 @@
+# Design
+
+happy-arbitrary makes random programs for a language whose parser is written
+with Happy and Alex. It works from the parser's own files, so the programs
+follow the real grammar, and it uses the language's lexer to check their text.
+
+## Reading the grammar and the lexer
+
+`Language.Happy.Parser` reads a Happy `.y` file. `Language.Happy.Grammar`
+turns its rules into `Rules`: the productions of every nonterminal that the
+start symbol reaches, with parameterised rules like `List(p)` instantiated for
+every argument they're used with, so `List(Identifier)` is a nonterminal of its
+own.
+
+`Language.Alex.Parser` reads an Alex `.x` file: macros, character sets (with
+`#` and `~`), regexes, start codes, blocks of rules for a start code, and the
+code around them. Macros are expanded while parsing, so every regex stands on
+its own. Left and right contexts are read but not kept.
+
+## Linking tokens to lexer rules
+
+Happy and Alex only meet in Haskell code: a `%token` pattern like
+`{ L _ IdVar _ }` matches what a lexer action like `{ mkL IdVar }` makes. A
+`LinkConfig` finds the token class in both (by default, the word after `L _`
+and after `mkL`).
+
+A lexer rule only applies in its start codes. To make a token in the current
+start code, the linker looks for a rule that makes it there, or for a chain of
+rules that only switch start code (like `begin comment`) to get to one. It
+follows `andBegin` and `begin` to know the start code after each token.
+
+## Trees of a given size
+
+`Language.Happy.Sized` draws a tree with QuickCheck's size in tokens:
+
+- Every nonterminal knows the fewest and the most tokens it can make. Recursive
+  rules have no most.
+- A node picks one of the productions that can make its budget. The more
+  symbols a production reaches, the more likely it is, by the square root, so
+  that small productions still come up.
+- The budget is shared among the children in random order, so that each child
+  can still make its share. Children that reach more symbols get more of the
+  spare tokens, so a list of one token doesn't take up most of the tree.
+
+Trees come out at the size asked for, or as close as the grammar allows.
+
+We tried Boltzmann sampling first. It draws trees uniformly at a given size, so
+for a real grammar most of the size goes into whichever construct has the most
+trees. For Cimple's grammar, the expected size also stayed below 10 tokens
+however close we got to the singularity.
+
+## Text for the tokens
+
+`Language.Alex.Arbitrary` makes text that a regex matches, with at most 5
+repetitions. A regex like `[a-z]+` can make another class's keyword, which
+would lex as that class, so the linker draws again when it does.
+
+The text of one token can still lex differently next to its neighbours: `=`
+and `=` without a space become `==`, and where the lexer treats spaces and
+newlines as tokens (comments, preprocessor lines), a space between tokens is an
+extra token. `generateChecked` takes the language's lexer and draws a token's
+text, and the space before it (nothing, a space or a newline), again until the
+lexer finds exactly the tokens generated so far.
+
+A grammar can allow a token where its lexer can't make it, like a comment in a
+preprocessor line that the lexer only reads at the start of a line. If a token
+keeps failing, `generateChecked` draws a new tree, up to 100 times.
+`renderChecked` says which token and start code failed.
+
+Without a lexer, `generateSource` joins the tokens' text with spaces.
+
+## What the test has to do
+
+The grammar doesn't have the checks in the parser's actions, or in later passes
+over the tree, so some generated programs are rejected by the real parser. The
+test drops those, for example with `suchThatMap`.
diff --git a/doc/development.md b/doc/development.md
new file mode 100644
--- /dev/null
+++ b/doc/development.md
@@ -0,0 +1,44 @@
+# Development
+
+## Building and testing
+
+With cabal (as CI does):
+
+```sh
+cabal build
+cabal test
+```
+
+In the TokTok monorepo, with Bazel:
+
+```sh
+bazel build //hs-happy-arbitrary/...
+bazel test //hs-happy-arbitrary/...
+```
+
+To run some of the tests, pass hspec's `--match`, for example
+`--test_arg=--match=Mini` with Bazel or `--test-options=--match=Mini` with
+cabal.
+
+## Tests
+
+- `test/Language/`: tests for each module.
+- `test/Examples/Mini/`: a small language with its own Happy parser and Alex
+  lexer. `Examples.MiniSpec` checks that every generated program is one its
+  parser accepts.
+- `test/examples/Cimple/`: a copy of Cimple's lexer and grammar, a real
+  language with many start codes. Keep it in sync with hs-cimple.
+
+## Trying a grammar
+
+`tools/generate.hs` (Bazel only) prints random programs and which rules they
+used:
+
+```sh
+bazel run //hs-happy-arbitrary/tools:generate -- \
+    --alex Lexer.x --happy Parser.y --start TranslationUnit --size 50 --iterations 10
+```
+
+Without `--happy`, it prints sample text for each token class of the lexer.
+It joins tokens with spaces without asking a lexer, so a program can lex
+differently from the tokens it was made of.
diff --git a/happy-arbitrary.cabal b/happy-arbitrary.cabal
--- a/happy-arbitrary.cabal
+++ b/happy-arbitrary.cabal
@@ -1,18 +1,28 @@
 name:          happy-arbitrary
-version:       0.0.1
-synopsis:      Token list generator for arbitrary Happy grammars.
+version:       0.0.2
+synopsis:      Random programs for testing parsers made with Happy and Alex
 homepage:      https://toktok.ltd/
 license:       GPL-3
 license-file:  LICENSE
 author:        Iphigenia Df <iphydf@gmail.com>
 maintainer:    Iphigenia Df <iphydf@gmail.com>
-copyright:     Copyright (c) 2024, Iphigenia Df
-category:      Data
+copyright:     Copyright (c) 2024-2026, Iphigenia Df
+category:      Testing
 stability:     Experimental
 cabal-version: >=1.10
 build-type:    Simple
-description:   Generates token lists for a Happy grammar for testing parsers.
+description:
+  Makes random programs from a parser's own Happy grammar and Alex lexer, of a
+  given size in tokens, and checks their text with the language's lexer. For
+  QuickCheck properties of parsers and pretty-printers.
 
+extra-source-files:
+    README.md
+    doc/design.md
+    doc/development.md
+    test/examples/Cimple/Lexer.x
+    test/examples/Cimple/Parser.y
+
 source-repository head
   type:     git
   location: https://github.com/TokTok/hs-happy-arbitrary
@@ -23,23 +33,31 @@
   ghc-options:      -Wall
   build-tools:      alex >=0, happy >=0
   exposed-modules:
+    Language.Alex.Arbitrary
+    Language.Alex.Ast
+    Language.Alex.Parser
     Language.Happy.Arbitrary
     Language.Happy.Ast
+    Language.Happy.GenTree
+    Language.Happy.Grammar
     Language.Happy.Lexer
+    Language.Happy.Linker
     Language.Happy.Parser
+    Language.Happy.Sized
     Language.Happy.Tokens
+    Language.Happy
 
   build-depends:
       QuickCheck
     , aeson
     , array
+    , attoparsec
     , base                 <5
     , containers
     , bytestring
     , data-fix
-    , extra
     , file-embed
-    , recursion-schemes
+    , mtl
     , text
     , transformers-compat
 
@@ -48,13 +66,27 @@
   default-language:   Haskell2010
   hs-source-dirs:     test
   main-is:            testsuite.hs
-  other-modules:      Language.Happy.ArbitrarySpec
+  other-modules:
+      Examples.CimpleSpec
+      Examples.Files
+      Examples.Mini.Lexer
+      Examples.Mini.Parser
+      Examples.MiniSpec
+      Language.Alex.ParserSpec
+      Language.Happy.ArbitrarySpec
+      Language.Happy.LinkerSpec
+      Language.Happy.SizedSpec
   ghc-options:        -Wall
-  build-tool-depends: hspec-discover:hspec-discover
+  build-tool-depends:
+      alex:alex
+    , happy:happy
+    , hspec-discover:hspec-discover
   build-depends:
-      base        <5
+      array
+    , base        <5
     , bytestring
-    , groom
+    , containers
+    , directory
     , hspec
     , QuickCheck
     , happy-arbitrary
diff --git a/src/Language/Alex/Arbitrary.hs b/src/Language/Alex/Arbitrary.hs
new file mode 100644
--- /dev/null
+++ b/src/Language/Alex/Arbitrary.hs
@@ -0,0 +1,46 @@
+-- | Random text that a regex matches.
+module Language.Alex.Arbitrary
+    ( fixedString
+    , genRegex
+    ) where
+
+import qualified Data.Set          as Set
+import qualified Data.Text         as Text
+import           Language.Alex.Ast (CharSet (..), Regex (..))
+import           Test.QuickCheck   (Gen, elements, listOf, listOf1, oneof,
+                                    resize)
+
+-- | The characters we pick from for a set given by what it leaves out.
+universe :: [Char]
+universe = [' ' .. '~'] ++ "\t\n"
+
+-- | Returns the only string a regex matches, if it matches just one.
+fixedString :: Regex -> Maybe String
+fixedString r = case r of
+    RString t -> Just (Text.unpack t)
+    RSet (Only s) | Set.size s == 1 -> Just [Set.findMin s]
+    RSet _ -> Nothing
+    RStar _ -> Nothing
+    RPlus _ -> Nothing
+    ROpt _ -> Nothing
+    RSeq rs -> concat <$> mapM fixedString rs
+    RAlt [] -> Nothing
+    RAlt (a : as) -> do
+        s <- fixedString a
+        if all ((== Just s) . fixedString) as then Just s else Nothing
+
+-- | Makes text that the regex matches. Repetitions are short: at most 5 times.
+genRegex :: Regex -> Gen String
+genRegex r = resize 5 $ case r of
+    RString t -> return $ Text.unpack t
+    RSet s -> case members s of
+        [] -> error $ "genRegex: " ++ show s ++ " has no characters we can pick"
+        cs -> pure <$> elements cs
+    RStar r' -> concat <$> listOf (genRegex r')
+    RPlus r' -> concat <$> listOf1 (genRegex r')
+    ROpt r' -> oneof [return "", genRegex r']
+    RSeq rs -> concat <$> mapM genRegex rs
+    RAlt rs -> oneof (map genRegex rs)
+  where
+    members (Only s)   = Set.toList s
+    members (AllBut s) = filter (`Set.notMember` s) universe
diff --git a/src/Language/Alex/Ast.hs b/src/Language/Alex/Ast.hs
new file mode 100644
--- /dev/null
+++ b/src/Language/Alex/Ast.hs
@@ -0,0 +1,47 @@
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE StrictData    #-}
+-- | An Alex lexer, as far as generating text for its tokens needs it. Macros
+-- are expanded while parsing, so a regex stands on its own.
+module Language.Alex.Ast
+    ( AlexFile (..)
+    , CharSet (..)
+    , Regex (..)
+    , Rule (..)
+    ) where
+
+import           Data.Set     (Set)
+import           Data.Text    (Text)
+import           GHC.Generics (Generic)
+
+-- | A set of characters: these characters, or all characters but these.
+data CharSet
+    = Only (Set Char)
+    | AllBut (Set Char)
+    deriving (Show, Eq, Ord, Generic)
+
+-- | A regex with its macros expanded.
+data Regex
+    = RString Text
+    | RSet CharSet
+    | RStar Regex
+    | RPlus Regex
+    | ROpt Regex
+    | RSeq [Regex]
+    | RAlt [Regex]
+    deriving (Show, Eq, Ord, Generic)
+
+-- | A lexer rule: where it applies, what it matches, and its action.
+data Rule = Rule
+    { ruleStartCodes :: [Text]
+      -- ^ Empty means every start code.
+    , ruleRegex      :: Regex
+    , ruleCode       :: Text
+      -- ^ The action, without braces, or @;@ for a rule that makes no token.
+    }
+    deriving (Show, Eq, Ord, Generic)
+
+-- | The rules of a lexer, in order.
+newtype AlexFile = AlexFile
+    { alexRules :: [Rule]
+    }
+    deriving (Show, Eq, Ord, Generic)
diff --git a/src/Language/Alex/Parser.hs b/src/Language/Alex/Parser.hs
new file mode 100644
--- /dev/null
+++ b/src/Language/Alex/Parser.hs
@@ -0,0 +1,241 @@
+{-# LANGUAGE OverloadedStrings #-}
+-- | Parses Alex @.x@ files. Macros are expanded as they're used. Left and
+-- right contexts are parsed but not kept: they only restrict where a token
+-- matches, and 'Language.Happy.Linker.renderChecked' asks the real lexer.
+module Language.Alex.Parser
+    ( parseAlex
+    ) where
+
+import           Control.Applicative  (many, optional, (<|>))
+import           Data.Attoparsec.Text
+import           Data.Char            (chr, isAlphaNum, isSpace)
+import           Data.Functor         (($>))
+import           Data.Map             (Map)
+import qualified Data.Map             as Map
+import qualified Data.Set             as Set
+import           Data.Text            (Text)
+import qualified Data.Text            as Text
+import           Language.Alex.Ast
+import           Numeric              (readOct)
+
+-- | Parses an Alex file, or says why it can't.
+parseAlex :: Text -> Either String AlexFile
+parseAlex = parseOnly (alexFile <* endOfInput)
+
+-- | The macros defined so far, by name without the sigil.
+data Env = Env
+    { envSets    :: Map Text CharSet
+    , envRegexes :: Map Text Regex
+    }
+
+-- | Alex's own macros.
+builtins :: Env
+builtins = Env
+    (Map.fromList
+        [ ("white", Only (Set.fromList " \t\n\f\v\r"))
+        , ("printable", AllBut (Set.fromList (['\0' .. '\31'] ++ ['\127'])))
+        ])
+    Map.empty
+
+alexFile :: Parser AlexFile
+alexFile = do
+    spaces
+    skipMany (codeBlock *> spaces)
+    env <- definitions builtins
+    _ <- identifier *> spaces *> string ":-" <?> "the start of the rules, like `tokens :-`"
+    spaces
+    rules <- concat <$> many (rule env <* spaces)
+    skipMany (codeBlock *> spaces)
+    return $ AlexFile rules
+
+-- | Parses macros and directives like @%wrapper@, in any order.
+definitions :: Env -> Parser Env
+definitions env =
+        (directive *> spaces *> definitions env)
+    <|> (macro env >>= \env' -> spaces *> definitions env')
+    <|> pure env
+
+directive :: Parser ()
+directive = char '%' *> identifier *> hspaces *> stringLiteral $> ()
+
+macro :: Env -> Parser Env
+macro env = setMacro <|> regexMacro
+  where
+    setMacro = do
+        name <- char '$' *> identifier
+        s <- spaces *> char '=' *> spaces *> charSet env
+        return env{envSets = Map.insert name s (envSets env)}
+    regexMacro = do
+        name <- char '@' *> identifier
+        r <- spaces *> char '=' *> spaces *> regex env
+        return env{envRegexes = Map.insert name r (envRegexes env)}
+
+-- | Parses a rule, or a block of rules for some start codes: @\<sc> { ... }@.
+rule :: Env -> Parser [Rule]
+rule env = do
+    codes <- option [] (startCodes <* spaces)
+    block codes <|> (pure <$> ruleBody codes)
+  where
+    block codes = char '{' *> spaces *> many (ruleBody codes <* spaces) <* char '}'
+
+    ruleBody codes = do
+        _ <- optional (char '^' <* hspaces)
+        r <- regex env <?> "a regex"
+        hspaces
+        _ <- optional rightContext
+        code <- spaces *> action <?> "an action"
+        return $ Rule codes r code
+
+    rightContext = (char '/' *> hspaces *> ((codeBlock $> ()) <|> (regex env $> ())) <* hspaces)
+        <|> (char '$' *> hspaces)
+
+    action = codeBlock <|> (char ';' $> ";")
+
+startCodes :: Parser [Text]
+startCodes = char '<' *> (identifier `sepBy1` char ',') <* char '>'
+
+-- Regexes
+
+regex :: Env -> Parser Regex
+regex env = do
+    alts <- sequence' `sepBy1` (spaces *> char '|' <* spaces)
+    return $ case alts of
+        [r] -> r
+        rs  -> RAlt rs
+  where
+    sequence' = do
+        terms <- many1 (term <* hspaces)
+        return $ case terms of
+            [r] -> r
+            rs  -> RSeq rs
+
+    term = do
+        a <- atom
+        postfixes a
+
+    postfixes a = option a $ do
+        a' <- (char '*' $> RStar a)
+            <|> (char '+' $> RPlus a)
+            <|> (char '?' $> ROpt a)
+            <|> (repeatRange a <$> (char '{' *> decimal) <*> optional (char ',' *> optional decimal) <* char '}')
+        postfixes a'
+
+    atom = (char '(' *> spaces *> option (RSeq []) (regex env) <* spaces <* char ')')
+        <|> regexMacro
+        <|> (RString . Text.pack <$> stringLiteral)
+        <|> (RSet <$> charSet env)
+
+    regexMacro = do
+        name <- char '@' *> identifier
+        maybe (fail $ "undefined macro @" ++ Text.unpack name) return (Map.lookup name (envRegexes env))
+
+-- | @r{n}@, @r{n,}@ and @r{n,m}@.
+repeatRange :: Regex -> Int -> Maybe (Maybe Int) -> Regex
+repeatRange r n bound = RSeq $ replicate n r ++ case bound of
+    Nothing       -> []
+    Just Nothing  -> [RStar r]
+    Just (Just m) -> replicate (m - n) (ROpt r)
+
+-- Character sets
+
+-- | Parses a set, with @#@ for the difference of sets.
+charSet :: Env -> Parser CharSet
+charSet env = foldl difference <$> simpleSet env <*> many (hspaces *> char '#' *> hspaces *> simpleSet env)
+
+simpleSet :: Env -> Parser CharSet
+simpleSet env =
+        (complement <$> (char '~' *> simpleSet env))
+    <|> bracketed
+    <|> (char '.' $> AllBut (Set.singleton '\n'))
+    <|> setMacro
+    <|> range
+  where
+    bracketed = do
+        _ <- char '['
+        inverted <- option False (char '^' $> True)
+        items <- many (spaces *> (charSet env <|> setOnlyItem)) <* spaces
+        _ <- char ']'
+        let s = foldr union (Only Set.empty) items
+        return $ if inverted then complement s else s
+
+    -- Inside brackets, characters that are special in regexes are plain.
+    setOnlyItem = Only . Set.singleton <$> satisfy (`elem` ("()*+?|/^@\"{};<>" :: String))
+
+    setMacro = do
+        name <- char '$' *> identifier
+        maybe (fail $ "undefined macro $" ++ Text.unpack name) return (Map.lookup name (envSets env))
+
+    range = do
+        from <- setChar
+        to <- optional (char '-' *> setChar)
+        return $ Only $ maybe (Set.singleton from) (Set.fromList . enumFromTo from) to
+
+-- | Parses a character that stands for itself, or an escape.
+setChar :: Parser Char
+setChar = escapedChar <|> satisfy (\c -> not (isSpace c) && c `notElem` ("$@[]{}()*+?|/^.~#\"\\;<>-" :: String))
+
+escapedChar :: Parser Char
+escapedChar = char '\\' *> choice
+    [ char 'x' *> (chr <$> hexadecimal)
+    , char 'o' *> (octal =<< takeWhile1 (`elem` ['0' .. '7']))
+    , chr <$> decimal
+    , char 'n' $> '\n'
+    , char 't' $> '\t'
+    , char 'r' $> '\r'
+    , char 'f' $> '\f'
+    , char 'v' $> '\v'
+    , char 'b' $> '\b'
+    , char 'a' $> '\a'
+    , anyChar
+    ]
+  where
+    octal digits = case readOct (Text.unpack digits) of
+        [(n, "")] -> return (chr n)
+        _         -> fail "bad octal escape"
+
+union :: CharSet -> CharSet -> CharSet
+union (Only a) (Only b)     = Only (Set.union a b)
+union (Only a) (AllBut b)   = AllBut (Set.difference b a)
+union (AllBut a) (Only b)   = AllBut (Set.difference a b)
+union (AllBut a) (AllBut b) = AllBut (Set.intersection a b)
+
+difference :: CharSet -> CharSet -> CharSet
+difference a b = complement (union (complement a) b)
+
+complement :: CharSet -> CharSet
+complement (Only s)   = AllBut s
+complement (AllBut s) = Only s
+
+-- Lexical bits
+
+identifier :: Parser Text
+identifier = takeWhile1 (\c -> isAlphaNum c || c == '_' || c == '\'')
+
+stringLiteral :: Parser String
+stringLiteral = char '"' *> many (escapedChar <|> satisfy (/= '"')) <* char '"'
+
+-- | Parses Haskell code in braces, and returns it without the outer braces.
+-- Braces in nested blocks and in string and character literals are kept.
+codeBlock :: Parser Text
+codeBlock = char '{' *> (Text.concat <$> many piece) <* char '}'
+  where
+    piece = nested <|> haskellString <|> haskellChar <|> takeWhile1 (`notElem` ("{}\"'" :: String)) <|> string "'"
+    nested = (\t -> "{" <> t <> "}") <$> codeBlock
+    haskellString = do
+        body <- char '"' *> many (escaped <|> (Text.singleton <$> satisfy (/= '"'))) <* char '"'
+        return $ "\"" <> Text.concat body <> "\""
+    haskellChar = do
+        c <- char '\'' *> (escaped <|> (Text.singleton <$> satisfy (/= '\''))) <* char '\''
+        return $ "'" <> c <> "'"
+    escaped = (\c -> Text.pack ['\\', c]) <$> (char '\\' *> anyChar)
+
+-- | Skips spaces and comments, including newlines.
+spaces :: Parser ()
+spaces = skipMany (skip isSpace <|> lineComment <|> blockComment)
+  where
+    lineComment = string "--" *> skipWhile (/= '\n')
+    blockComment = string "{-" *> skipMany (blockComment <|> (notChar '-' $> ()) <|> (char '-' *> notChar '}' $> ())) <* string "-}"
+
+-- | Skips spaces and tabs, but not newlines: a regex ends at the end of its line.
+hspaces :: Parser ()
+hspaces = skipWhile isHorizontalSpace
diff --git a/src/Language/Happy.hs b/src/Language/Happy.hs
new file mode 100644
--- /dev/null
+++ b/src/Language/Happy.hs
@@ -0,0 +1,10 @@
+-- | Parses Happy @.y@ files: @runAlex text parseGrammar@.
+module Language.Happy (module X, Grammar) where
+
+import           Data.Text             (Text)
+import           Language.Happy.Ast    as X
+import           Language.Happy.Lexer  as X
+import           Language.Happy.Parser as X
+
+-- | A parsed Happy file.
+type Grammar = Node (Lexeme Text)
diff --git a/src/Language/Happy/Arbitrary.hs b/src/Language/Happy/Arbitrary.hs
--- a/src/Language/Happy/Arbitrary.hs
+++ b/src/Language/Happy/Arbitrary.hs
@@ -1,53 +1,39 @@
-{-# OPTIONS_GHC -Wwarn #-}
+{-# LANGUAGE NamedFieldPuns    #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-# LANGUAGE Strict            #-}
-module Language.Happy.Arbitrary where
-
-import           Control.Applicative  ((<|>))
-import           Control.Monad.Extra  (concatMapM)
-import           Data.Fix             (foldFix)
-import           Data.Map             (Map)
-import qualified Data.Map             as Map
-import           Data.Maybe           (fromJust)
-import           Data.Text            (Text)
-import qualified Data.Text            as Text
-import           Language.Happy.Ast   (Node, NodeF (..))
-import           Language.Happy.Lexer (Lexeme, lexemeText)
-import qualified Test.QuickCheck.Gen  as Gen
-import           Test.QuickCheck.Gen  (Gen)
-
-genTokens :: Text -> Node (Lexeme Text) -> Gen [Text]
-genTokens start g = do
-    case Map.lookup start rules of
-        Nothing -> error $ "no such rule: " <> Text.unpack start
-        Just r  -> expand tokens rules r
-  where
-    tokens = foldFix terminals g
-    rules = foldFix nonterminals g
+{-# LANGUAGE StrictData        #-}
+-- | Random trees and token lists for a Happy grammar.
+module Language.Happy.Arbitrary
+    ( Config (..)
+    , defConfig
+    , genTokens
+    , genTree
+    ) where
 
-expand :: Map Text Text -> Map Text [[Text]] -> [[Text]] -> Gen [Text]
-expand tokens rules r = do
-    rule <- Gen.elements r
-    let expanded = map (resolve tokens rules) rule
-    concatMapM (continue tokens rules) expanded
+import           Data.Text              (Text)
+import           Language.Happy.Ast     (Node, Sym (..))
+import           Language.Happy.GenTree (GenTree, flatten)
+import           Language.Happy.Grammar (extractTokens, fromAst)
+import           Language.Happy.Lexer   (Lexeme)
+import           Language.Happy.Sized   (genSized)
+import qualified Test.QuickCheck.Gen    as Gen
+import           Test.QuickCheck.Gen    (Gen)
 
-continue :: Map Text Text -> Map Text [[Text]] -> Either Text [[Text]] -> Gen [Text]
-continue _ _ (Left token)          = return [token]
-continue tokens rules (Right rule) = expand tokens rules rule
+-- | How to make a token from the code of its @%token@ pattern.
+newtype Config token = Config
+    { parseToken :: Text -> token
+    }
 
-resolve :: Map Text Text -> Map Text [[Text]] -> Text -> Either Text [[Text]]
-resolve tokens rules sym =
-    fromJust $ (Left <$> Map.lookup sym tokens) <|> (Right <$> Map.lookup sym rules)
+defConfig :: (Text -> token) -> Config token
+defConfig parseToken = Config{parseToken}
 
-terminals :: NodeF (Lexeme Text) (Map Text Text) -> Map Text Text
-terminals node = case node of
-    Token k v -> Map.singleton (lexemeText k) (lexemeText v)
-    n         -> Map.unions n
+-- | Returns the tokens of a tree from 'genTree'.
+genTokens :: Config token -> Text -> Node (Lexeme Text) -> Gen [token]
+genTokens cfg start g = flatten <$> genTree cfg start g
 
-nonterminals :: NodeF (Lexeme Text) (Map Text [[Text]]) -> Map Text [[Text]]
-nonterminals node = case node of
-    RuleLine syms _     -> Map.singleton "" [map lexemeText syms]
-    RuleDefn name rules -> Map.singleton (lexemeText name) (merge rules)
-    n                   -> Map.unionsWith (++) n
+-- | Draws trees with QuickCheck's size in tokens, or as close as the grammar
+-- allows.
+genTree :: Config token -> Text -> Node (Lexeme Text) -> Gen (GenTree token)
+genTree cfg start g = Gen.sized gen
   where
-    merge = concat . concatMap Map.elems
+    -- Shared between draws, so the size ranges are worked out once.
+    gen = genSized (fromAst start g) (extractTokens (parseToken cfg) g) (Sym start [])
diff --git a/src/Language/Happy/Ast.hs b/src/Language/Happy/Ast.hs
--- a/src/Language/Happy/Ast.hs
+++ b/src/Language/Happy/Ast.hs
@@ -3,8 +3,10 @@
 {-# LANGUAGE DerivingVia       #-}
 {-# LANGUAGE FlexibleInstances #-}
 {-# LANGUAGE Strict            #-}
+-- | The syntax of a Happy @.y@ file.
 module Language.Happy.Ast
     ( Node, NodeF (..)
+    , Sym (..), RuleDef (..)
     ) where
 
 import           Data.Aeson                   (FromJSON, FromJSON1, ToJSON,
@@ -12,29 +14,46 @@
 import           Data.Fix                     (Fix)
 import           Data.Functor.Classes         (Eq1, Ord1, Read1, Show1)
 import           Data.Functor.Classes.Generic (FunctorClassesDefault (..))
+import           Data.Text                    (Text)
 import           GHC.Generics                 (Generic, Generic1)
 
+-- | A part of a Happy file, with its parts of type @a@.
 data NodeF lexeme a
     = Grammar [lexeme] [a] [a] [lexeme]
     | PragmaExpect lexeme
-    | PragmaName lexeme lexeme
+    | PragmaName lexeme (Maybe lexeme)
+    | PragmaPartial lexeme (Maybe lexeme)
     | PragmaErrorHandlerType lexeme
     | PragmaError lexeme
     | PragmaLexer lexeme lexeme
-    | PragmaMonad lexeme
+    | PragmaMonad [lexeme]
     | PragmaTokenType lexeme
     | PragmaToken [a]
     | PragmaLeft [lexeme]
     | PragmaRight [lexeme]
+    | PragmaNonassoc [lexeme]
     | Token lexeme lexeme
-    | Rule a a
     | RuleType lexeme lexeme
-    | RuleDefn lexeme [a]
-    | RuleLine [lexeme] lexeme
+    | RuleDefn lexeme [lexeme] [a]
+      -- ^ Name, parameters and productions.
+    | RuleLine [a] lexeme
+      -- ^ Symbols and code.
+    | Symbol lexeme [a]
+      -- ^ Name and arguments.
     deriving (Show, Read, Eq, Ord, Generic, Generic1, Functor, Foldable, Traversable)
     deriving (Show1, Read1, Eq1, Ord1) via FunctorClassesDefault (NodeF lexeme)
 
+-- | A Happy file, or a part of one.
 type Node lexeme = Fix (NodeF lexeme)
 
 instance FromJSON lexeme => FromJSON1 (NodeF lexeme)
 instance ToJSON lexeme => ToJSON1 (NodeF lexeme)
+
+-- | A use of a rule or token, with its arguments: @List(Identifier)@.
+data Sym = Sym Text [Sym] deriving (Show, Eq, Ord)
+
+-- | A rule's parameters and productions.
+data RuleDef = RuleDef
+    { ruleParams :: [Text]
+    , ruleProds  :: [[Sym]]
+    } deriving (Show, Eq)
diff --git a/src/Language/Happy/GenTree.hs b/src/Language/Happy/GenTree.hs
new file mode 100644
--- /dev/null
+++ b/src/Language/Happy/GenTree.hs
@@ -0,0 +1,37 @@
+{-# LANGUAGE DeriveFunctor #-}
+{-# LANGUAGE DeriveGeneric #-}
+-- | Trees made from a grammar: rules with their symbols, down to tokens.
+module Language.Happy.GenTree
+    ( GenTree (..)
+    , flatten
+    , renderTree
+    , getRules
+    ) where
+
+import           Data.Text          (Text)
+import           GHC.Generics       (Generic)
+import           Language.Happy.Ast (Sym (..))
+
+-- | A rule with the trees of its symbols, or a token.
+data GenTree token
+    = Node Sym [GenTree token]
+    | Leaf token
+    deriving (Show, Eq, Functor, Generic)
+
+-- | Returns the tokens of the tree, in order.
+flatten :: GenTree token -> [token]
+flatten (Leaf t)    = [t]
+flatten (Node _ cs) = concatMap flatten cs
+
+-- | Returns the names of the rules in the tree, once for every use.
+getRules :: GenTree token -> [Text]
+getRules (Leaf _)               = []
+getRules (Node (Sym name _) cs) = name : concatMap getRules cs
+
+-- | Shows the tree as indented lines, for debugging.
+renderTree :: Show token => GenTree token -> String
+renderTree = go 0
+  where
+    go indent (Leaf t) = replicate indent ' ' ++ show t ++ "\n"
+    go indent (Node sym children) =
+        replicate indent ' ' ++ show sym ++ "\n" ++ concatMap (go (indent + 2)) children
diff --git a/src/Language/Happy/Grammar.hs b/src/Language/Happy/Grammar.hs
new file mode 100644
--- /dev/null
+++ b/src/Language/Happy/Grammar.hs
@@ -0,0 +1,107 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE Strict            #-}
+
+-- | The rules of a Happy grammar, with parameterised rules like @List(p)@
+-- instantiated for every argument they're used with.
+module Language.Happy.Grammar
+    ( Production
+    , Rules
+    , Sym (..)
+    , extractTokens
+    , fromAst
+    ) where
+
+import           Control.Monad.State  (State, execState, gets, modify)
+import           Data.Fix             (Fix (..))
+import           Data.Map             (Map)
+import qualified Data.Map             as Map
+import           Data.Set             (Set)
+import qualified Data.Set             as Set
+import           Data.Text            (Text)
+import           Language.Happy.Ast   (Node, NodeF (..), RuleDef (..), Sym (..))
+import           Language.Happy.Lexer (Lexeme, lexemeText)
+
+-- | The symbols on the right of a rule, in order.
+type Production = [Sym]
+
+-- | The productions of every nonterminal that the start symbol reaches.
+type Rules = Map Sym [Production]
+
+-- | Returns the rules of a parsed Happy file that the start rule reaches.
+fromAst :: Text -> Node (Lexeme Text) -> Rules
+fromAst start node = expandGrammar (extractRules node) (extractTokenNames node) (Sym start [])
+
+-- Extraction Logic
+
+extractRules :: Node (Lexeme Text) -> Map Text [RuleDef]
+extractRules (Fix (Grammar _ _ rules _)) = Map.unionsWith (++) (map extractRule rules)
+extractRules _ = mempty
+
+extractRule :: Node (Lexeme Text) -> Map Text [RuleDef]
+extractRule (Fix (RuleDefn name params ruleLines)) =
+    let paramNames = map lexemeText params
+        prods = extractRuleLines ruleLines
+    in Map.singleton (lexemeText name) [RuleDef paramNames prods]
+extractRule (Fix (RuleType _ _)) = mempty
+extractRule node = error $ "Unexpected node in Rules list: " ++ show node
+
+extractRuleLines :: [Node (Lexeme Text)] -> [[Sym]]
+extractRuleLines = map extractRuleLine
+
+extractRuleLine :: Node (Lexeme Text) -> [Sym]
+extractRuleLine (Fix (RuleLine syms _)) = map extractSymbol syms
+extractRuleLine _                       = []
+
+extractSymbol :: Node (Lexeme Text) -> Sym
+extractSymbol (Fix (Symbol name args)) = Sym (lexemeText name) (map extractSymbol args)
+extractSymbol _ = error "Invalid AST: Expected Symbol"
+
+extractTokenNames :: Node (Lexeme Text) -> Set Text
+extractTokenNames (Fix (Grammar _ pragmas _ _)) =
+    Set.unions (map extractPragmaTokenNames pragmas)
+extractTokenNames _ = mempty
+
+extractPragmaTokenNames :: Node (Lexeme Text) -> Set Text
+extractPragmaTokenNames (Fix (PragmaToken tokens)) =
+    Set.fromList [ lexemeText name | Fix (Token name _) <- tokens ]
+extractPragmaTokenNames _ = mempty
+
+-- | Makes every token from the code of its @%token@ pattern.
+extractTokens :: (Text -> token) -> Node (Lexeme Text) -> Map Text token
+extractTokens parseFunc (Fix (Grammar _ pragmas _ _)) =
+    Map.unions (map (extractPragmaToken parseFunc) pragmas)
+extractTokens _ _ = mempty
+
+extractPragmaToken :: (Text -> token) -> Node (Lexeme Text) -> Map Text token
+extractPragmaToken parseFunc (Fix (PragmaToken tokens)) =
+    Map.fromList [ (lexemeText name, parseFunc (lexemeText code))
+                 | Fix (Token name code) <- tokens ]
+extractPragmaToken _ _ = mempty
+
+-- Expansion Logic
+
+-- | Symbols that are neither tokens nor rules, like Happy's @error@, are left
+-- in the productions. They make no trees, so the generator leaves out the
+-- productions that have them.
+expandGrammar :: Map Text [RuleDef] -> Set Text -> Sym -> Rules
+expandGrammar rules tokens start = execState (process [start]) Map.empty
+  where
+    process :: [Sym] -> State Rules ()
+    process [] = return ()
+    process (sym@(Sym name args) : rest) = do
+        visited <- gets (Map.member sym)
+        case Map.lookup name rules of
+            Just defs | not visited && not (Set.member name tokens) -> do
+                let prods = [ map (substitute (bind params)) prod | RuleDef params alts <- defs, prod <- alts ]
+                    bind params
+                        | length params == length args = Map.fromList (zip params args)
+                        | otherwise = error $ "fromAst: " ++ show sym ++ " has the wrong number of arguments"
+                modify (Map.insert sym prods)
+                process (concat prods ++ rest)
+            _ -> process rest
+
+    substitute :: Map Text Sym -> Sym -> Sym
+    substitute env (Sym n a) = case Map.lookup n env of
+        Just arg | null a -> arg
+                 | otherwise -> error $ "fromAst: rule parameter " ++ show n ++ " can't take arguments"
+        Nothing -> Sym n (map (substitute env) a)
diff --git a/src/Language/Happy/Lexer.x b/src/Language/Happy/Lexer.x
--- a/src/Language/Happy/Lexer.x
+++ b/src/Language/Happy/Lexer.x
@@ -5,6 +5,7 @@
 {-# LANGUAGE StandaloneDeriving #-}
 {-# LANGUAGE StrictData         #-}
 {-# OPTIONS_GHC -Wno-unused-imports #-}
+-- | Lexes Happy @.y@ files.
 module Language.Happy.Lexer
     ( Alex
     , AlexPosn (..)
@@ -47,6 +48,9 @@
 <0>		"%lexer"				{ mkL KwLexer }
 <0>		"%monad"				{ mkL KwMonad }
 <0>		"%name"					{ mkL KwName }
+<0>		"%nonassoc"				{ mkL KwNonassoc }
+<0>		"%partial"				{ mkL KwPartial }
+<0>		"%prec"					{ mkL KwPrec }
 <0>		"%right"				{ mkL KwRight }
 <0>		"%token"				{ mkL KwToken }
 <0>		"%tokentype"				{ mkL KwTokentype }
@@ -54,6 +58,9 @@
 <0>		"%%"					{ mkL PctPercentPercent }
 <0>		"::"					{ mkL PctColonColon }
 <0>		":"					{ mkL PctColon }
+<0>		","					{ mkL PctComma }
+<0>		"("					{ mkL PctLParen }
+<0>		")"					{ mkL PctRParen }
 <0>		"|"					{ mkL PctPipe }
 
 <0>		"--"\n					;
@@ -72,6 +79,7 @@
 instance FromJSON AlexPosn
 instance ToJSON AlexPosn
 
+-- | A token of a Happy file: where it is, what kind it is, and its text.
 data Lexeme text = L AlexPosn LexemeClass text
     deriving (Eq, Show, Generic, Functor, Foldable, Traversable)
 
@@ -101,6 +109,7 @@
 alexEOF :: Alex (Lexeme Text)
 alexEOF = return (L (AlexPn 0 0 0) Eof Text.empty)
 
+-- | Returns the tokens of a Happy file.
 alexScanTokens :: LBS.ByteString -> Either String [Lexeme Text]
 alexScanTokens str =
     runAlex str $ loop []
diff --git a/src/Language/Happy/Linker.hs b/src/Language/Happy/Linker.hs
new file mode 100644
--- /dev/null
+++ b/src/Language/Happy/Linker.hs
@@ -0,0 +1,189 @@
+{-# LANGUAGE OverloadedStrings #-}
+-- | Links the tokens of a Happy grammar to the rules of an Alex lexer that
+-- make them, and renders generated tokens as source text.
+module Language.Happy.Linker
+    ( LinkConfig (..)
+    , defaultLinkConfig
+    , Lexer
+    , StartCode
+    , TokenGen (..)
+    , generateChecked
+    , generateSource
+    , makeConfig
+    , renderChecked
+    , renderUnchecked
+    ) where
+
+import           Data.Map                 (Map)
+import qualified Data.Map                 as Map
+import           Data.Maybe               (fromMaybe, mapMaybe)
+import qualified Data.Set                 as Set
+import           Data.Text                (Text)
+import qualified Data.Text                as Text
+import           Language.Alex.Arbitrary  (fixedString, genRegex)
+import           Language.Alex.Ast        (AlexFile (..), Regex, Rule (..))
+import           Language.Happy.Arbitrary (Config (..), genTokens)
+import           Language.Happy.Ast       (Node)
+import           Language.Happy.Lexer     (Lexeme)
+import           Test.QuickCheck          (Gen, elements, suchThatMaybe)
+
+-- | How to find the token class in Happy and Alex code.
+data LinkConfig = LinkConfig
+    { happyTokenPattern :: Text -> Maybe Text
+      -- ^ The class that a @%token@ pattern matches.
+    , alexTokenPattern  :: Text -> Maybe Text
+      -- ^ The class that a lexer action makes, or 'Nothing' for none.
+    }
+
+-- | Patterns like @{ L _ IdVar _ }@ and actions like @{ mkL IdVar }@.
+defaultLinkConfig :: LinkConfig
+defaultLinkConfig = LinkConfig
+    { happyTokenPattern = wordAfter "L _ "
+    , alexTokenPattern  = wordAfter "mkL "
+    }
+
+-- | Returns the word after a marker, if the code has the marker.
+wordAfter :: Text -> Text -> Maybe Text
+wordAfter marker code = case Text.breakOn marker code of
+    (_, rest) | Text.null rest -> Nothing
+    (_, rest) -> case Text.words (Text.map separate (Text.drop (Text.length marker) rest)) of
+        word : _ -> Just word
+        []       -> Nothing
+  where
+    separate c = if c `elem` ("{}`()" :: String) then ' ' else c
+
+-- | The language's lexer: the classes of the tokens in a text, named as the
+-- t'LinkConfig' names them, or 'Nothing' if it can't lex the text.
+type Lexer = Text -> Maybe [Text]
+
+-- | An Alex start code, like @0@ or @comment@.
+type StartCode = Text
+
+-- | How to make the text of one token.
+data TokenGen = TokenGen
+    { tokenCode  :: Text
+      -- ^ The token's @%token@ pattern, without its braces.
+    , tokenClass :: Maybe Text
+      -- ^ 'Nothing' if 'happyTokenPattern' finds no class in the pattern.
+    , genToken   :: StartCode -> Maybe (Gen (String, StartCode))
+      -- ^ The token's text in a start code, and the start code after it.
+      -- 'Nothing' if no lexer rule makes the token there.
+    }
+
+-- | Generates source code that the lexer agrees with. A tree is drawn again if
+-- one of its tokens can't be rendered, up to 100 times.
+generateChecked :: LinkConfig -> AlexFile -> Lexer -> Text -> Node (Lexeme Text) -> Gen Text
+generateChecked cfg alex lexer start happy = go (100 :: Int) ""
+  where
+    -- Shared between tries, so the grammar is worked out once.
+    tokens = genTokens (makeConfig cfg alex) start happy
+    go 0 err = error $ "generateChecked: no tree could be rendered in 100 tries, the last one because " ++ Text.unpack err
+    go n _ = tokens >>= renderChecked lexer >>= either (go (n - 1)) pure
+
+-- | Generates source code without checking what the lexer makes of it.
+generateSource :: LinkConfig -> AlexFile -> Text -> Node (Lexeme Text) -> Gen (Either Text Text)
+generateSource cfg alex start happy = genTokens (makeConfig cfg alex) start happy >>= renderUnchecked
+
+-- | Joins the tokens' text so that the lexer finds exactly these tokens again.
+-- A token's text and the space before it are drawn again until the lexer
+-- agrees. After 20 tries we give up and say which token failed.
+renderChecked :: Lexer -> [TokenGen] -> Gen (Either Text Text)
+renderChecked lexer = go "" [] "0"
+  where
+    go out _ _ [] = return $ Right out
+    go out classes code (tok : toks) = case (tokenClass tok, genToken tok code) of
+        (Nothing, _) -> return $ Left $ unlinked tok
+        (Just cls, Nothing) -> return $ Left $ noRule cls code
+        (Just cls, Just gen) -> attempt (20 :: Int)
+          where
+            classes' = classes ++ [cls]
+            attempt 0 = return $ Left $ "the lexer never read " <> cls <> " back in start code " <> code
+            attempt n = do
+                (text, code') <- gen
+                space <- if Text.null out then return "" else elements ["", " ", "\n"]
+                let out' = out <> space <> Text.pack text
+                if lexer out' == Just classes'
+                    then go out' classes' code' toks
+                    else attempt (n - 1)
+
+-- | Joins the tokens' text with spaces, without checking what a lexer makes of
+-- it.
+renderUnchecked :: [TokenGen] -> Gen (Either Text Text)
+renderUnchecked = go [] "0"
+  where
+    go out _ [] = return $ Right $ Text.unwords (reverse out)
+    go out code (tok : toks) = case (tokenClass tok, genToken tok code) of
+        (Nothing, _) -> return $ Left $ unlinked tok
+        (Just cls, Nothing) -> return $ Left $ noRule cls code
+        (Just _, Just gen) -> do
+            (text, code') <- gen
+            go (Text.pack text : out) code' toks
+
+unlinked :: TokenGen -> Text
+unlinked tok = "the token pattern {" <> tokenCode tok <> "} has no class we know"
+
+noRule :: Text -> StartCode -> Text
+noRule cls code = "no lexer rule makes " <> cls <> " in start code " <> code
+
+-- | Rules that make a token class, by start code ('Nothing' for every start
+-- code), with the start code they switch to, if any.
+type TokenRules = Map (Maybe StartCode, Text) [(Regex, Maybe StartCode)]
+
+-- | Rules that make no token but switch start code, like the @" "+"*"@ at the
+-- start of a comment line.
+type Switches = Map (Maybe StartCode) [(Regex, StartCode)]
+
+-- | Makes tokens from the grammar's @%token@ patterns, with text from the
+-- lexer's rules. A token needs a rule in the current start code, or a chain
+-- of rules that only switch start code to get to one.
+makeConfig :: LinkConfig -> AlexFile -> Config TokenGen
+makeConfig cfg alex = Config $ \code ->
+    let cls = happyTokenPattern cfg code
+    in TokenGen code cls (\start -> genText start =<< cls)
+  where
+    (tokenRules, switches) = foldr addRule (Map.empty, Map.empty) (alexRules alex)
+
+    addRule :: Rule -> (TokenRules, Switches) -> (TokenRules, Switches)
+    addRule r (toks, sws) = case (alexTokenPattern cfg (ruleCode r), nextStartCode (ruleCode r)) of
+        (Just cls, next)     -> (Map.unionWith (++) (Map.fromList [ ((c, cls), [(ruleRegex r, next)]) | c <- codes r ]) toks, sws)
+        (Nothing, Just next) -> (toks, Map.unionWith (++) (Map.fromList [ (c, [(ruleRegex r, next)]) | c <- codes r ]) sws)
+        (Nothing, Nothing)   -> (toks, sws)
+    codes r = if null (ruleStartCodes r) then [Nothing] else map Just (ruleStartCodes r)
+
+    rulesIn table code = Map.findWithDefault [] (Just code) table ++ Map.findWithDefault [] Nothing table
+
+    -- Keywords, so that a regex like @[a-z]+@ doesn't make another class's
+    -- keyword (it would lex as that class).
+    keywords :: Map String Text
+    keywords = Map.fromList $ mapMaybe (\r -> (,) <$> fixedString (ruleRegex r) <*> alexTokenPattern cfg (ruleCode r)) (alexRules alex)
+
+    -- Lists every way to make the class from a start code: the switches to
+    -- take first, then the rule that makes it.
+    paths :: StartCode -> Text -> [([(Regex, StartCode)], (Regex, Maybe StartCode))]
+    paths start cls = go Set.empty [(start, [])]
+      where
+        go _ [] = []
+        go seen ((code, taken) : queue)
+            | Set.member code seen = go seen queue
+            | otherwise =
+                [ (reverse taken, rule) | rule <- Map.findWithDefault [] (Just code, cls) tokenRules ++ Map.findWithDefault [] (Nothing, cls) tokenRules ]
+                ++ go (Set.insert code seen) (queue ++ [ (next, (regex, next) : taken) | (regex, next) <- rulesIn switches code ])
+
+    genText :: StartCode -> Text -> Maybe (Gen (String, StartCode))
+    genText start cls = case paths start cls of
+        [] -> Nothing
+        ps -> Just $ do
+            (taken, (regex, next)) <- elements ps
+            prefix <- concat <$> mapM (genRegex . fst) taken
+            text <- fromMaybe <$> genRegex regex <*> (genRegex regex `suchThatMaybe` notOtherKeyword)
+            let afterSwitches = if null taken then start else snd (last taken)
+            return (prefix ++ text, fromMaybe afterSwitches next)
+      where
+        notOtherKeyword s = maybe True (== cls) (Map.lookup s keywords)
+
+-- | Returns the start code an action switches to, from @`andBegin` code@ or
+-- @begin code@.
+nextStartCode :: Text -> Maybe StartCode
+nextStartCode code = case wordAfter "`andBegin` " code of
+    Just next -> Just next
+    Nothing   -> wordAfter "begin " code
diff --git a/src/Language/Happy/Parser.y b/src/Language/Happy/Parser.y
--- a/src/Language/Happy/Parser.y
+++ b/src/Language/Happy/Parser.y
@@ -2,6 +2,7 @@
 {-# LANGUAGE CPP               #-}
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE TemplateHaskell   #-}
+-- | Parses Happy @.y@ files: @runAlex text parseGrammar@.
 module Language.Happy.Parser
     ( parseGrammar
     , source
@@ -30,7 +31,7 @@
 %token
     ID_NAME			{ L _ IdName			_ }
 
-    '{}'			{ L _ LitCode			_ }
+    '{code}'			{ L _ LitCode			_ }
 
     '%errorhandlertype'		{ L _ KwErrorhandlertype	_ }
     '%error'			{ L _ KwError			_ }
@@ -39,6 +40,9 @@
     '%lexer'			{ L _ KwLexer			_ }
     '%monad'			{ L _ KwMonad			_ }
     '%name'			{ L _ KwName			_ }
+    '%nonassoc'		{ L _ KwNonassoc		_ }
+    '%partial'			{ L _ KwPartial			_ }
+    '%prec'			{ L _ KwPrec			_ }
     '%right'			{ L _ KwRight			_ }
     '%token'			{ L _ KwToken			_ }
     '%tokentype'		{ L _ KwTokentype		_ }
@@ -46,6 +50,9 @@
     '%%'			{ L _ PctPercentPercent		_ }
     '::'			{ L _ PctColonColon		_ }
     ':'				{ L _ PctColon			_ }
+    ','				{ L _ PctComma			_ }
+    '('				{ L _ PctLParen			_ }
+    ')'				{ L _ PctRParen			_ }
     '|'				{ L _ PctPipe			_ }
 
     LIT_STRING			{ L _ LitString			_ }
@@ -59,8 +66,8 @@
 
 Code :: { [Term] }
 Code
-:	'{}'						{ [$1] }
-|	Code '{}'					{ $1 ++ [$2] }
+:	'{code}'					{ [$1] }
+|	Code '{code}'					{ $1 ++ [$2] }
 
 Pragmas :: { [NonTerm] }
 Pragmas
@@ -70,15 +77,19 @@
 Pragma :: { NonTerm }
 Pragma
 :	'%expect' LIT_INTEGER				{ Fix $ PragmaExpect $2 }
-|	'%name' ID_NAME ID_NAME				{ Fix $ PragmaName $2 $3 }
+|	'%name' ID_NAME					{ Fix $ PragmaName $2 Nothing }
+|	'%name' ID_NAME ID_NAME				{ Fix $ PragmaName $2 (Just $3) }
+|	'%partial' ID_NAME				{ Fix $ PragmaPartial $2 Nothing }
+|	'%partial' ID_NAME ID_NAME			{ Fix $ PragmaPartial $2 (Just $3) }
 |	'%errorhandlertype' ID_NAME			{ Fix $ PragmaErrorHandlerType $2 }
-|	'%error' '{}'					{ Fix $ PragmaError $2 }
-|	'%lexer' '{}' '{}'				{ Fix $ PragmaLexer $2 $3 }
-|	'%monad' '{}'					{ Fix $ PragmaMonad $2 }
-|	'%tokentype' '{}'				{ Fix $ PragmaTokenType $2 }
+|	'%error' '{code}'				{ Fix $ PragmaError $2 }
+|	'%lexer' '{code}' '{code}'			{ Fix $ PragmaLexer $2 $3 }
+|	'%monad' Code					{ Fix $ PragmaMonad $2 }
+|	'%tokentype' '{code}'				{ Fix $ PragmaTokenType $2 }
 |	'%token' Tokens					{ Fix $ PragmaToken $2 }
 |	'%left' TokenNames				{ Fix $ PragmaLeft $2 }
 |	'%right' TokenNames				{ Fix $ PragmaRight $2 }
+|	'%nonassoc' TokenNames				{ Fix $ PragmaNonassoc $2 }
 
 TokenNames :: { [Term] }
 TokenNames
@@ -92,7 +103,7 @@
 
 Token :: { NonTerm }
 Token
-:	TokenName '{}'					{ Fix $ Token $1 $2 }
+:	TokenName '{code}'				{ Fix $ Token $1 $2 }
 
 TokenName :: { Term }
 TokenName
@@ -106,16 +117,23 @@
 
 Rule :: { NonTerm }
 Rule
-:	RuleType RuleDefn				{ Fix $ Rule $1 $2 }
+:	RuleType					{ $1 }
+|	RuleDefn					{ $1 }
 
 RuleType :: { NonTerm }
 RuleType
-:	ID_NAME '::' '{}'				{ Fix $ RuleType $1 $3 }
+:	ID_NAME '::' '{code}'				{ Fix $ RuleType $1 $3 }
 
 RuleDefn :: { NonTerm }
 RuleDefn
-:	ID_NAME ':' RuleLines				{ Fix $ RuleDefn $1 $3 }
+:	ID_NAME ':' RuleLines				{ Fix $ RuleDefn $1 [] $3 }
+|	ID_NAME '(' RuleParams ')' ':' RuleLines	{ Fix $ RuleDefn $1 $3 $6 }
 
+RuleParams :: { [Term] }
+RuleParams
+:	ID_NAME						{ [$1] }
+|	RuleParams ',' ID_NAME				{ $1 ++ [$3] }
+
 RuleLines :: { [NonTerm] }
 RuleLines
 :	RuleLine					{ [$1] }
@@ -123,9 +141,26 @@
 
 RuleLine :: { NonTerm }
 RuleLine
-:	TokenNames '{}'					{ Fix $ RuleLine $1 $2 }
+:	'{code}'					{ Fix $ RuleLine [] $1 }
+|	Symbols '{code}'				{ Fix $ RuleLine $1 $2 }
+|	Symbols '%prec' ID_NAME '{code}'		{ Fix $ RuleLine $1 $4 }
 
+Symbols :: { [NonTerm] }
+Symbols
+:	Symbol						{ [$1] }
+|	Symbols Symbol					{ $1 ++ [$2] }
 
+Symbol :: { NonTerm }
+Symbol
+:	ID_NAME						{ Fix $ Symbol $1 [] }
+|	LIT_STRING					{ Fix $ Symbol $1 [] }
+|	ID_NAME '(' SymbolArgs ')'			{ Fix $ Symbol $1 $3 }
+
+SymbolArgs :: { [NonTerm] }
+SymbolArgs
+:	Symbol						{ [$1] }
+|	SymbolArgs ',' Symbol				{ $1 ++ [$3] }
+
 {
 type Term = Lexeme Text
 type NonTerm = Node Term
@@ -138,6 +173,7 @@
 lexwrap :: (Lexeme Text -> Alex a) -> Alex a
 lexwrap = (alexMonadScan >>=)
 
+-- | This parser's own grammar, if the build put it in (Bazel does).
 source :: BS.ByteString
 #ifdef SOURCE
 source = $(embedFile SOURCE)
diff --git a/src/Language/Happy/Sized.hs b/src/Language/Happy/Sized.hs
new file mode 100644
--- /dev/null
+++ b/src/Language/Happy/Sized.hs
@@ -0,0 +1,135 @@
+{-# LANGUAGE StrictData #-}
+-- | Trees of a given size in tokens. Every symbol knows the fewest and the
+-- most tokens it can make. A node picks one of the productions that can make
+-- its budget, and shares the budget among its children so that each of them
+-- can make its share. Both favour symbols that reach more of the grammar.
+module Language.Happy.Sized
+    ( Range (..)
+    , genSized
+    , ranges
+    ) where
+
+import           Control.Monad          (zipWithM)
+import           Data.List              (minimumBy, sortOn)
+import           Data.Map               (Map)
+import qualified Data.Map               as Map
+import           Data.Maybe             (mapMaybe)
+import           Data.Ord               (comparing)
+import           Data.Set               (Set)
+import qualified Data.Set               as Set
+import           Data.Text              (Text)
+import           Language.Happy.Ast     (Sym (..))
+import           Language.Happy.GenTree (GenTree (..))
+import           Language.Happy.Grammar (Rules)
+import           Test.QuickCheck        (Gen, choose, shuffle)
+
+-- | The fewest and the most tokens a symbol makes. 'Nothing' as the most
+-- means there's no limit.
+data Range = Range Int (Maybe Int)
+    deriving (Show, Eq)
+
+-- | Returns the size range of every nonterminal that makes a finite tree.
+ranges :: Rules -> Set Text -> Map Sym Range
+ranges grammar terminals = Map.intersectionWith Range mins maxes
+  where
+    size m s@(Sym name _)
+        | Set.member name terminals = Just 1
+        | otherwise = Map.lookup s m
+    best pick m = Map.mapMaybe (\prods -> case mapMaybe (fmap sum . mapM (size m)) prods of
+        [] -> Nothing
+        ns -> Just (pick ns)) grammar
+
+    -- The smallest tree has no path with a nonterminal on it twice, so as
+    -- many rounds as there are nonterminals are enough.
+    mins = iterate (best minimum) Map.empty !! (Map.size grammar + 1)
+
+    -- With n nonterminals, a most with a limit settles within n rounds. One
+    -- without a limit keeps growing, at least once every n rounds, because no
+    -- cycle is longer than n.
+    rounds = iterate (best maximum) (0 <$ mins)
+    settled = rounds !! (Map.size grammar + 1)
+    later = rounds !! (2 * Map.size grammar + 2)
+    maxes = Map.mapWithKey (\s n -> if Map.lookup s later == Just n then Just n else Nothing) settled
+
+-- | Draws a tree of the start symbol with @n@ tokens, or as close to it as the
+-- grammar allows.
+genSized :: Rules -> Map Text token -> Sym -> Int -> Gen (GenTree token)
+genSized grammar tokens start = \n -> build (clamp n (rangeOf start)) start
+  where
+    rs = ranges grammar (Map.keysSet tokens)
+    reached = reach grammar
+
+    -- The productions of every nonterminal that make finite trees, with their
+    -- size ranges and how likely they are: the square root of how many
+    -- symbols they reach, so that productions with more in them come up more
+    -- often without crowding out the small ones.
+    options = Map.map (\prods -> [ (prod, r, sqrt (fromIntegral (Set.size (Set.unions (map reachOf prod))))) | prod <- prods, Just r <- [prodRange prod] ]) grammar
+    reachOf s = Map.findWithDefault (Set.singleton s) s reached
+
+    rangeOf s@(Sym name _)
+        | Map.member name tokens = Range 1 (Just 1)
+        | otherwise = Map.findWithDefault (error $ "genSized: " ++ show s ++ " makes no finite tree") s rs
+
+    -- 'Nothing' if a symbol makes no finite tree.
+    prodRange prod = foldr add (Range 0 (Just 0)) <$> mapM symRange prod
+    symRange s@(Sym name _)
+        | Map.member name tokens = Just (Range 1 (Just 1))
+        | otherwise = Map.lookup s rs
+    add (Range a b) (Range c d) = Range (a + c) ((+) <$> b <*> d)
+
+    build b sym@(Sym name _) = case Map.lookup name tokens of
+        Just token -> return $ Leaf token
+        Nothing -> do
+            let candidates = Map.findWithDefault [] sym options
+                fitting = [ (w, (prod, r)) | (prod, r, w) <- candidates, fits b r ]
+            -- A size between the fewest and the most isn't always possible.
+            (prod, r) <- if null fitting
+                then return $ minimumBy (comparing (distance b . snd)) [ (prod, r) | (prod, r, _) <- candidates ]
+                else pickWeighted fitting
+            shares <- split (clamp b r) [ (rangeOf s, Set.size (reachOf s)) | s <- prod ]
+            Node sym <$> zipWithM build shares prod
+
+    fits b (Range lo hi) = lo <= b && maybe True (>= b) hi
+    distance b (Range lo hi) = max (lo - b) (maybe 0 (b -) hi)
+    clamp b (Range lo hi) = max lo (maybe b (min b) hi)
+
+-- | Picks one of the values with a probability proportional to its weight.
+pickWeighted :: [(Double, a)] -> Gen a
+pickWeighted options = do
+    r <- choose (0, sum (map fst options))
+    return $ pick r options
+  where
+    pick _ [(_, a)] = a
+    pick r ((w, a) : rest)
+        | r <= w = a
+        | otherwise = pick (r - w) rest
+    pick _ [] = error "pickWeighted: no options"
+
+-- | Returns the symbols each nonterminal can reach, itself included.
+reach :: Rules -> Map Sym (Set Sym)
+reach grammar = iterate step (Map.mapWithKey (\s _ -> Set.singleton s) grammar) !! (Map.size grammar + 1)
+  where
+    step sets = Map.mapWithKey (\s prods -> Set.insert s (Set.unions [ Map.findWithDefault (Set.singleton c) c sets | c <- concat prods ])) grammar
+
+-- | Shares a budget among children with these ranges and weights, in random
+-- order, so that the children after each one can still make what's left. A
+-- child gets its fewest tokens plus a part of the rest that grows with its
+-- weight (times a random factor): a list of one token can take any number of
+-- tokens, but a tree full of it tests less than one with more in it.
+split :: Int -> [(Range, Int)] -> Gen [Int]
+split budget children = do
+    order <- shuffle (zip [0 :: Int ..] children)
+    weighted <- mapM (\(i, (r, n)) -> (\u -> (i, r, fromIntegral n * u)) <$> choose (0, 1 :: Double)) order
+    return $ map snd . sortOn fst $ go budget weighted
+  where
+    go _ [] = []
+    go left ((i, Range lo hi, w) : rest) = (i, share) : go (left - share) rest
+      where
+        restLo = sum [ l | (_, Range l _, _) <- rest ]
+        restHi = sum <$> sequence [ h | (_, Range _ h, _) <- rest ]
+        from = max lo (maybe lo (left -) restHi)
+        to = maybe id min hi (left - restLo)
+        spare = left - lo - restLo
+        total = w + sum [ v | (_, _, v) <- rest ]
+        wanted = lo + if total > 0 then round (fromIntegral spare * w / total) else 0
+        share = max from (min to wanted)
diff --git a/src/Language/Happy/Tokens.hs b/src/Language/Happy/Tokens.hs
--- a/src/Language/Happy/Tokens.hs
+++ b/src/Language/Happy/Tokens.hs
@@ -7,6 +7,7 @@
 import           Data.Aeson   (FromJSON, ToJSON)
 import           GHC.Generics (Generic)
 
+-- | The kinds of tokens in a Happy file.
 data LexemeClass
     = IdName
 
@@ -17,14 +18,20 @@
     | KwLexer
     | KwMonad
     | KwName
+    | KwNonassoc
+    | KwPartial
+    | KwPrec
     | KwRight
     | KwToken
     | KwTokentype
 
     | PctColon
     | PctColonColon
+    | PctComma
+    | PctLParen
     | PctPercentPercent
     | PctPipe
+    | PctRParen
 
     | LitCode
     | LitInteger
diff --git a/test/Examples/CimpleSpec.hs b/test/Examples/CimpleSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Examples/CimpleSpec.hs
@@ -0,0 +1,28 @@
+{-# LANGUAGE NamedFieldPuns    #-}
+{-# LANGUAGE OverloadedStrings #-}
+module Examples.CimpleSpec (spec) where
+
+import qualified Data.Map                 as Map
+import           Data.Maybe               (isJust)
+import           Examples.Files           (readAlexFile, readHappyFile)
+import           Language.Alex.Ast        (AlexFile (..), Rule (..))
+import           Language.Happy.Arbitrary (Config (..))
+import qualified Language.Happy.Grammar   as Grammar
+import           Language.Happy.Linker    (TokenGen (..), defaultLinkConfig,
+                                           makeConfig)
+import           Test.Hspec               (Spec, describe, it, runIO, shouldBe)
+
+-- | Cimple's lexer and grammar: a real language with many start codes.
+spec :: Spec
+spec = describe "Cimple" $ do
+    alex <- runIO $ readAlexFile "test/examples/Cimple/Lexer.x"
+    happy <- runIO $ readHappyFile "test/examples/Cimple/Parser.y"
+
+    it "has a lexer rule for every token in some start code" $ do
+        let Config{parseToken} = makeConfig defaultLinkConfig alex
+            startCodes = "0" : concatMap ruleStartCodes (alexRules alex)
+            unlinked = [ tokenCode tok
+                       | tok <- map parseToken (Map.elems (Grammar.extractTokens id happy))
+                       , not (any (isJust . genToken tok) startCodes)
+                       ]
+        unlinked `shouldBe` []
diff --git a/test/Examples/Files.hs b/test/Examples/Files.hs
new file mode 100644
--- /dev/null
+++ b/test/Examples/Files.hs
@@ -0,0 +1,28 @@
+-- | Reads the example languages' files from Bazel's or cabal's working
+-- directory.
+module Examples.Files
+    ( readAlexFile
+    , readHappyFile
+    ) where
+
+import qualified Data.ByteString.Lazy  as LBS
+import           Data.Text             (Text)
+import qualified Data.Text.Encoding    as Text
+import           Language.Alex.Ast     (AlexFile)
+import           Language.Alex.Parser  (parseAlex)
+import           Language.Happy.Ast    (Node)
+import           Language.Happy.Lexer  (Lexeme, runAlex)
+import           Language.Happy.Parser (parseGrammar)
+import           System.Directory      (doesFileExist)
+
+readTestFile :: FilePath -> IO LBS.ByteString
+readTestFile path = do
+    let bazelPath = "hs-happy-arbitrary/" ++ path
+    inBazel <- doesFileExist bazelPath
+    LBS.readFile (if inBazel then bazelPath else path)
+
+readAlexFile :: FilePath -> IO AlexFile
+readAlexFile path = either (fail . ((path ++ ": ") ++)) return . parseAlex . Text.decodeUtf8 . LBS.toStrict =<< readTestFile path
+
+readHappyFile :: FilePath -> IO (Node (Lexeme Text))
+readHappyFile path = either (fail . ((path ++ ": ") ++)) return . flip runAlex parseGrammar =<< readTestFile path
diff --git a/test/Examples/Mini/Lexer.x b/test/Examples/Mini/Lexer.x
new file mode 100644
--- /dev/null
+++ b/test/Examples/Mini/Lexer.x
@@ -0,0 +1,81 @@
+{
+-- | A small language for testing the generator. Spaces matter in comments and
+-- in @#define@ lines, keywords look like variable names, and @==@ looks like 2
+-- @=@ without a space between them.
+module Examples.Mini.Lexer
+    ( Alex
+    , Lexeme (..)
+    , TokenClass (..)
+    , alexError
+    , alexMonadScan
+    , lexClasses
+    , runAlex
+    ) where
+}
+
+%wrapper "monad"
+
+tokens :-
+
+<0>		"if"			{ mkL KwIf }
+<0>		"print"			{ mkL KwPrint }
+<0>		"while"			{ mkL KwWhile }
+<0,ppSC>	[a-z][a-z0-9_]*		{ mkL IdVar }
+<0,ppSC>	[0-9]+			{ mkL LitInt }
+<0,ppSC>	"=="			{ mkL PctEqEq }
+<0>		"="			{ mkL PctEq }
+<0,ppSC>	"+"			{ mkL PctPlus }
+<0,ppSC>	"("			{ mkL PctLParen }
+<0,ppSC>	")"			{ mkL PctRParen }
+<0>		";"			{ mkL PctSemicolon }
+<0>		"{"			{ mkL PctLBrace }
+<0>		"}"			{ mkL PctRBrace }
+<0>		"#define"		{ mkL PpDefine `andBegin` ppSC }
+<ppSC>		\n			{ mkL PpNewline `andBegin` 0 }
+<ppSC>		" "+			;
+<0>		"/*"			{ mkL CmtStart `andBegin` cmtSC }
+<cmtSC>		[a-z]+			{ mkL CmtWord }
+<cmtSC>		" "+			{ mkL CmtSpace }
+<cmtSC>		"*/"			{ mkL CmtEnd `andBegin` 0 }
+<0>		[\ \n]+			;
+
+{
+data TokenClass
+    = KwIf
+    | KwPrint
+    | KwWhile
+    | IdVar
+    | LitInt
+    | PctEqEq
+    | PctEq
+    | PctPlus
+    | PctLParen
+    | PctRParen
+    | PctSemicolon
+    | PctLBrace
+    | PctRBrace
+    | PpDefine
+    | PpNewline
+    | CmtStart
+    | CmtWord
+    | CmtSpace
+    | CmtEnd
+    | Eof
+    deriving (Eq, Show)
+
+data Lexeme = L AlexPosn TokenClass String
+    deriving (Show)
+
+mkL :: TokenClass -> AlexInput -> Int -> Alex Lexeme
+mkL c (p, _, _, s) len = pure $ L p c (take len s)
+
+alexEOF :: Alex Lexeme
+alexEOF = pure $ L (AlexPn 0 0 0) Eof ""
+
+lexClasses :: String -> Either String [TokenClass]
+lexClasses s = runAlex s $ go []
+  where
+    go acc = do
+        L _ c _ <- alexMonadScan
+        if c == Eof then pure (reverse acc) else go (c : acc)
+}
diff --git a/test/Examples/Mini/Parser.y b/test/Examples/Mini/Parser.y
new file mode 100644
--- /dev/null
+++ b/test/Examples/Mini/Parser.y
@@ -0,0 +1,76 @@
+{
+module Examples.Mini.Parser (parseProgram) where
+
+import           Examples.Mini.Lexer
+}
+
+%name parseProgram Program
+%error {parseError}
+%lexer {lexwrap} {L _ Eof _}
+%monad {Alex}
+%tokentype {Lexeme}
+%token
+    if			{ L _ KwIf			_ }
+    print		{ L _ KwPrint			_ }
+    while		{ L _ KwWhile			_ }
+    ID_VAR		{ L _ IdVar			_ }
+    LIT_INT		{ L _ LitInt			_ }
+    '=='		{ L _ PctEqEq			_ }
+    '='			{ L _ PctEq			_ }
+    '+'			{ L _ PctPlus			_ }
+    '('			{ L _ PctLParen			_ }
+    ')'			{ L _ PctRParen			_ }
+    ';'			{ L _ PctSemicolon		_ }
+    '{'			{ L _ PctLBrace			_ }
+    '}'			{ L _ PctRBrace			_ }
+    '#define'		{ L _ PpDefine			_ }
+    '\n'		{ L _ PpNewline			_ }
+    '/*'		{ L _ CmtStart			_ }
+    CMT_WORD		{ L _ CmtWord			_ }
+    CMT_SPACE		{ L _ CmtSpace			_ }
+    '*/'		{ L _ CmtEnd			_ }
+
+%%
+
+Program :: { () }
+Program
+:	Stmts						{ () }
+
+Stmts :: { () }
+Stmts
+:							{ () }
+|	Stmts Stmt					{ () }
+
+Stmt :: { () }
+Stmt
+:	ID_VAR '=' Expr ';'				{ () }
+|	print Expr ';'					{ () }
+|	if '(' Expr ')' '{' Stmts '}'			{ () }
+|	while '(' Expr ')' '{' Stmts '}'		{ () }
+|	'#define' ID_VAR Expr '\n'			{ () }
+|	'/*' CmtWords '*/'				{ () }
+
+Expr :: { () }
+Expr
+:	Term						{ () }
+|	Expr '+' Term					{ () }
+|	Expr '==' Term					{ () }
+
+Term :: { () }
+Term
+:	ID_VAR						{ () }
+|	LIT_INT						{ () }
+|	'(' Expr ')'					{ () }
+
+CmtWords :: { () }
+CmtWords
+:	CMT_WORD					{ () }
+|	CmtWords CMT_SPACE CMT_WORD			{ () }
+
+{
+lexwrap :: (Lexeme -> Alex a) -> Alex a
+lexwrap = (alexMonadScan >>=)
+
+parseError :: Lexeme -> Alex a
+parseError (L _ c s) = alexError $ "parse error at " ++ show c ++ " " ++ show s
+}
diff --git a/test/Examples/MiniSpec.hs b/test/Examples/MiniSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Examples/MiniSpec.hs
@@ -0,0 +1,25 @@
+{-# LANGUAGE OverloadedStrings #-}
+module Examples.MiniSpec (spec) where
+
+import           Data.Either           (isRight)
+import qualified Data.Text             as Text
+import           Examples.Files        (readAlexFile, readHappyFile)
+import           Examples.Mini.Lexer   (lexClasses, runAlex)
+import           Examples.Mini.Parser  (parseProgram)
+import           Language.Happy.Linker (Lexer, defaultLinkConfig,
+                                        generateChecked)
+import           Test.Hspec            (Spec, describe, it, runIO,
+                                        shouldSatisfy)
+import           Test.QuickCheck       (forAll)
+
+miniLexer :: Lexer
+miniLexer = either (const Nothing) (Just . map (Text.pack . show)) . lexClasses . Text.unpack
+
+spec :: Spec
+spec = describe "generateChecked" $ do
+    alex <- runIO $ readAlexFile "test/Examples/Mini/Lexer.x"
+    happy <- runIO $ readHappyFile "test/Examples/Mini/Parser.y"
+
+    it "makes programs that the language's own parser accepts" $
+        forAll (generateChecked defaultLinkConfig alex miniLexer "Program" happy) $ \code ->
+            runAlex (Text.unpack code) parseProgram `shouldSatisfy` isRight
diff --git a/test/Language/Alex/ParserSpec.hs b/test/Language/Alex/ParserSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Language/Alex/ParserSpec.hs
@@ -0,0 +1,86 @@
+{-# LANGUAGE OverloadedStrings #-}
+module Language.Alex.ParserSpec (spec) where
+
+import qualified Data.Set             as Set
+import           Data.Text            (Text)
+import qualified Data.Text            as Text
+import           Language.Alex.Ast
+import           Language.Alex.Parser (parseAlex)
+import           Test.Hspec           (Spec, describe, it, shouldBe,
+                                       shouldSatisfy)
+
+-- | The regexes of the rules in a file.
+regexes :: [Text] -> Either String [Regex]
+regexes = fmap (map ruleRegex . alexRules) . parseAlex . Text.unlines
+
+only :: String -> Regex
+only = RSet . Only . Set.fromList
+
+spec :: Spec
+spec = describe "parseAlex" $ do
+    it "expands set macros, also inside brackets" $
+        regexes
+            [ "$lower = [a-z]"
+            , "$digit = 0-9"
+            , "tokens :-"
+            , "[$lower $digit \\_]+ ;"
+            ] `shouldBe` Right [RPlus (only (['a' .. 'z'] ++ ['0' .. '9'] ++ "_"))]
+
+    it "takes the difference and complement of sets" $
+        regexes
+            [ "$consonant = [a-z] # [aeiou]"
+            , "tokens :-"
+            , "$consonant ;"
+            , "~$consonant ;"
+            , "[^a] ;"
+            , ". ;"
+            ] `shouldBe` Right
+                [ only (filter (`notElem` ("aeiou" :: String)) ['a' .. 'z'])
+                , RSet (AllBut (Set.fromList (filter (`notElem` ("aeiou" :: String)) ['a' .. 'z'])))
+                , RSet (AllBut (Set.singleton 'a'))
+                , RSet (AllBut (Set.singleton '\n'))
+                ]
+
+    it "expands regex macros" $
+        regexes
+            [ "@word = [a-z]+"
+            , "tokens :-"
+            , "@word \"!\" ;"
+            ] `shouldBe` Right [RSeq [RPlus (only ['a' .. 'z']), RString "!"]]
+
+    it "repeats as many times as it says" $
+        regexes
+            [ "tokens :-"
+            , "a{2} ;"
+            , "a{1,} ;"
+            , "a{1,3} ;"
+            ] `shouldBe` Right
+                [ RSeq [only "a", only "a"]
+                , RSeq [only "a", RStar (only "a")]
+                , RSeq [only "a", ROpt (only "a"), ROpt (only "a")]
+                ]
+
+    it "reads start-code blocks, contexts and comments" $
+        fmap alexRules (parseAlex (Text.unlines
+            [ "{ module Lexer where }"
+            , "%wrapper \"monad\""
+            , "{- a {- nested -} comment -}"
+            , "lexer :-"
+            , "<cmt> {"
+            , "  \"x\" / \"y\" { mkL X } -- a comment"
+            , "  ^\"z\"$ ;"
+            , "}"
+            , "{ trailer }"
+            ])) `shouldBe` Right
+                [ Rule ["cmt"] (RString "x") " mkL X "
+                , Rule ["cmt"] (RString "z") ";"
+                ]
+
+    it "keeps braces in strings and characters in actions" $
+        fmap (map ruleCode . alexRules) (parseAlex (Text.unlines
+            [ "tokens :-"
+            , "\"x\" { f \"}\" '{' }"
+            ])) `shouldBe` Right [" f \"}\" '{' "]
+
+    it "rejects a macro that isn't defined" $
+        regexes ["tokens :-", "[$nope] ;"] `shouldSatisfy` either (const True) (const False)
diff --git a/test/Language/Happy/ArbitrarySpec.hs b/test/Language/Happy/ArbitrarySpec.hs
--- a/test/Language/Happy/ArbitrarySpec.hs
+++ b/test/Language/Happy/ArbitrarySpec.hs
@@ -7,7 +7,7 @@
 import           Data.Text                (Text)
 import qualified Data.Text                as Text
 import qualified Data.Text.Encoding       as Text
-import           Language.Happy.Arbitrary (genTokens)
+import           Language.Happy.Arbitrary (defConfig, genTokens)
 import           Language.Happy.Ast       (Node)
 import           Language.Happy.Lexer     (Lexeme, runAlex)
 import           Language.Happy.Parser    (parseGrammar)
@@ -29,14 +29,20 @@
     KwLexer            -> "%lexer"
     KwMonad            -> "%monad"
     KwName             -> "%name"
+    KwNonassoc         -> "%nonassoc"
+    KwPartial          -> "%partial"
+    KwPrec             -> "%prec"
     KwRight            -> "%right"
     KwToken            -> "%token"
     KwTokentype        -> "%tokentype"
 
     PctColon           -> ":"
     PctColonColon      -> "::"
+    PctComma           -> ","
+    PctLParen          -> "("
     PctPercentPercent  -> "%%"
     PctPipe            -> "|"
+    PctRParen          -> ")"
 
     LitCode            -> "{ code }"
     LitInteger         -> "0"
@@ -60,7 +66,7 @@
 spec = tryParseGrammar $ \g -> do
     describe "genTokens" $ do
         it "generates sequences that can be parsed again using the same grammar" $
-            forAll (Text.intercalate " " . map (sampleToken . parseToken) <$> genTokens "Grammar" g) $ \code -> do
+            forAll (Text.intercalate " " . map sampleToken <$> genTokens (defConfig parseToken) "Grammar" g) $ \code -> do
                 case runAlex (LBS.fromStrict . Text.encodeUtf8 $ code) parseGrammar of
                     Left err -> expectationFailure err
-                    Right ok -> print ok
+                    Right _  -> return ()
diff --git a/test/Language/Happy/LinkerSpec.hs b/test/Language/Happy/LinkerSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Language/Happy/LinkerSpec.hs
@@ -0,0 +1,83 @@
+{-# LANGUAGE OverloadedStrings #-}
+module Language.Happy.LinkerSpec (spec) where
+
+import qualified Data.ByteString.Lazy  as LBS
+import           Data.Text             (Text)
+import qualified Data.Text             as Text
+import qualified Data.Text.Encoding    as Text
+import           Language.Alex.Ast     (AlexFile)
+import           Language.Alex.Parser  (parseAlex)
+import           Language.Happy.Ast    (Node)
+import           Language.Happy.Lexer  (Lexeme, runAlex)
+import           Language.Happy.Linker (Lexer, defaultLinkConfig,
+                                        generateChecked, generateSource)
+import           Language.Happy.Parser (parseGrammar)
+import           Test.Hspec            (Spec, describe, it, shouldBe,
+                                        shouldSatisfy)
+import           Test.QuickCheck       (forAll, generate, vectorOf)
+
+alexFile :: [Text] -> AlexFile
+alexFile = either error id . parseAlex . Text.unlines
+
+happyFile :: [Text] -> Node (Lexeme Text)
+happyFile = either error id . flip runAlex parseGrammar . LBS.fromStrict . Text.encodeUtf8 . Text.unlines
+
+-- | Words, where @if@ is a keyword, and comments with words in them.
+wordsLexer :: AlexFile
+wordsLexer = alexFile
+    [ "tokens :-"
+    , "<0> \"if\" { mkL KwIf }"
+    , "<0> [a-z]+ { mkL IdVar }"
+    , "<0> \"/*\" { mkL CmtStart `andBegin` cmt }"
+    , "<cmt> [a-z]+ { mkL CmtWord }"
+    , "<cmt> \"*/\" { mkL CmtEnd `andBegin` 0 }"
+    , "\" \"+ ;"
+    ]
+
+wordsGrammar :: [Text] -> Node (Lexeme Text)
+wordsGrammar rules = happyFile $
+    [ "{ module Words where }"
+    , "%token"
+    , "    if { L _ KwIf _ }"
+    , "    ID { L _ IdVar _ }"
+    , "    '/*' { L _ CmtStart _ }"
+    , "    WORD { L _ CmtWord _ }"
+    , "    '*/' { L _ CmtEnd _ }"
+    , "    NONE { L _ Missing _ }"
+    , "    ODD { Odd }"
+    , "%%"
+    ] ++ rules ++ ["{ }"]
+
+-- | What the lexer above reads in text that only has words and spaces.
+readWords :: Lexer
+readWords text
+    | Text.all (\c -> c == ' ' || (c >= 'a' && c <= 'z')) text = Just [ if w == "if" then "KwIf" else "IdVar" | w <- Text.words text ]
+    | otherwise = Nothing
+
+isComment :: [Text] -> Bool
+isComment ["/*", _, "*/"] = True
+isComment _               = False
+
+spec :: Spec
+spec = do
+    describe "generateSource" $ do
+        it "doesn't make another token's keyword" $ do
+            results <- generate $ vectorOf 200 $ generateSource defaultLinkConfig wordsLexer "S" (wordsGrammar ["S : ID { () }"])
+            results `shouldSatisfy` all (either (const False) (/= "if"))
+
+        it "switches start code before a token that needs it" $ do
+            result <- generate $ generateSource defaultLinkConfig wordsLexer "S" (wordsGrammar ["S : '/*' WORD '*/' { () }"])
+            fmap Text.words result `shouldSatisfy` either (const False) isComment
+
+        it "says which token has no lexer rule" $ do
+            result <- generate $ generateSource defaultLinkConfig wordsLexer "S" (wordsGrammar ["S : NONE { () }"])
+            result `shouldBe` Left "no lexer rule makes Missing in start code 0"
+
+        it "says which token has no class" $ do
+            result <- generate $ generateSource defaultLinkConfig wordsLexer "S" (wordsGrammar ["S : ODD { () }"])
+            result `shouldBe` Left "the token pattern { Odd } has no class we know"
+
+    describe "generateChecked" $
+        it "keeps tokens apart that would lex as one" $
+            forAll (generateChecked defaultLinkConfig wordsLexer readWords "S" (wordsGrammar ["S : ID ID { () }"])) $ \code ->
+                readWords code `shouldBe` Just ["IdVar", "IdVar"]
diff --git a/test/Language/Happy/SizedSpec.hs b/test/Language/Happy/SizedSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Language/Happy/SizedSpec.hs
@@ -0,0 +1,48 @@
+{-# LANGUAGE OverloadedStrings #-}
+module Language.Happy.SizedSpec (spec) where
+
+import qualified Data.Map               as Map
+import           Data.Text              (Text)
+import           Language.Happy.Ast     (Sym (..))
+import           Language.Happy.GenTree (flatten)
+import           Language.Happy.Grammar (Rules)
+import           Language.Happy.Sized   (Range (..), genSized, ranges)
+import           Test.Hspec             (Spec, describe, it, shouldBe)
+import           Test.QuickCheck        (choose, forAll, (===))
+
+sym :: Text -> Sym
+sym name = Sym name []
+
+-- | @Pair : A A@, @A : x | x y@, @List : | List x@, @Gap : x | x x x@.
+rules :: Rules
+rules = Map.fromList
+    [ (sym "Pair", [[sym "A", sym "A"]])
+    , (sym "A", [[sym "x"], [sym "x", sym "y"]])
+    , (sym "List", [[], [sym "List", sym "x"]])
+    , (sym "Gap", [[sym "x"], [sym "x", sym "x", sym "x"]])
+    , (sym "Never", [[sym "Never", sym "x"]])
+    ]
+
+tokens :: Map.Map Text Text
+tokens = Map.fromList [("x", "x"), ("y", "y")]
+
+spec :: Spec
+spec = do
+    describe "ranges" $
+        it "finds the fewest and the most tokens, and leaves out what makes no tree" $
+            ranges rules (Map.keysSet tokens) `shouldBe` Map.fromList
+                [ (sym "Pair", Range 2 (Just 4))
+                , (sym "A", Range 1 (Just 2))
+                , (sym "List", Range 0 Nothing)
+                , (sym "Gap", Range 1 (Just 3))
+                ]
+
+    describe "genSized" $ do
+        it "makes trees of exactly the size asked for" $
+            forAll (choose (0, 300)) $ \n ->
+                forAll (genSized rules tokens (sym "List") n) $ \tree ->
+                    length (flatten tree) === n
+
+        it "makes the closest size when the asked one is impossible" $
+            forAll (genSized rules tokens (sym "Gap") 2) $ \tree ->
+                length (flatten tree) `elem` [1, 3]
diff --git a/test/examples/Cimple/Lexer.x b/test/examples/Cimple/Lexer.x
new file mode 100644
--- /dev/null
+++ b/test/examples/Cimple/Lexer.x
@@ -0,0 +1,409 @@
+{
+{-# LANGUAGE DeriveFunctor      #-}
+{-# LANGUAGE DeriveGeneric      #-}
+{-# LANGUAGE DeriveTraversable  #-}
+{-# LANGUAGE StandaloneDeriving #-}
+{-# LANGUAGE StrictData         #-}
+{-# OPTIONS_GHC -Wno-unused-imports #-}
+module Language.Cimple.Lexer
+    ( Alex
+    , AlexPosn (..)
+    , alexError
+    , alexScanTokens
+    , alexMonadScan
+    , Lexeme (..)
+    , lexemeClass
+    , lexemePosn
+    , lexemeText
+    , lexemeLine
+    , runAlex
+    , pushContext
+    , popContext
+    , getContext
+    , Context (..)
+    , ParseError (..)
+    ) where
+
+import           Data.Aeson             (FromJSON, FromJSONKey (..),
+                                         FromJSONKeyFunction (..), ToJSON,
+                                         ToJSONKey (..), ToJSONKeyFunction (..),
+                                         toEncoding, toJSON)
+import qualified Data.Aeson.Types       as Aeson
+import qualified Data.ByteString        as BS
+import qualified Data.ByteString.Lazy   as LBS
+import           Data.Hashable          (Hashable (..))
+import           Data.Text              (Text)
+import qualified Data.Text              as Text
+import qualified Data.Text.Encoding     as Text
+import           GHC.Generics           (Generic)
+import           Language.Cimple.Ast    (Node)
+import           Language.Cimple.Tokens (LexemeClass (..))
+import           Test.QuickCheck        (Arbitrary (..))
+}
+
+%wrapper "monadUserState-bytestring"
+
+$digit          = [0-9]
+$alpha          = [a-zA-Z]
+$upper          = [A-Z]
+$lower          = [a-z]
+
+@alphanum       = $alpha | $digit
+@alphanum_      = $alpha | $digit | \_
+
+@ident_upper    = $upper ($upper | $digit | \_)*
+@ident_lower    = $lower ($lower | $digit | \_)*
+
+@upper_snake    = $upper ($upper | $digit)* \_ ($upper | $digit | \_)*
+@lower_snake    = $lower ($lower | $digit)* \_ ($lower | $digit | \_)*
+@pascal_case    = $upper @alphanum_* $lower @alphanum_*
+@camel_case     = $lower @alphanum_* $upper @alphanum_*
+
+@win_type_prefix = WSA (EVENT | DATA) | LP (STR | TSTR | SOCKADDR)
+@win_type_suffix = $upper @alphanum* (INFO | DATA | PARAMS | HEADER | STRUCT | UNION | INTEGER | TIME | STATUS | EVENT)
+@win_type_extra  = IP_ADAPTER_INFO | LARGE_INTEGER | ULARGE_INTEGER
+@win_type_common = DWORD | WORD | BYTE | BOOL | SOCKET | INT | UINT | LONG | ULONG | SHORT | USHORT | CHAR | UCHAR | FILETIME | HANDLE | LONGLONG
+@win_type        = @win_type_prefix | @win_type_suffix | @win_type_extra | @win_type_common | u_long | u_int | u_short | u_char
+
+tokens :-
+
+-- Ignore attributes.
+<0>		"GNU_ALLOC_SIZE"			{ mkL KwGnuAllocSize }
+<0>		"GNU_PRINTF"				{ mkL KwGnuPrintf }
+<0>		"VLA"					{ mkL KwVla }
+
+-- Winapi functions.
+<0>		"Device" @pascal_case			{ mkL IdVar }
+<0>		"FormatMessage" [AW]?			{ mkL IdVar }
+<0>		"Get" @pascal_case			{ mkL IdVar }
+<0>		("Local"|"Heap") ("Alloc"|"Free")	{ mkL IdVar }
+<0>		"Query" @pascal_case			{ mkL IdVar }
+<0>		"SecureZeroMemory"			{ mkL IdVar }
+<0>		"Sleep"					{ mkL IdVar }
+<0>		"WSA" @pascal_case			{ mkL IdVar }
+
+-- Winapi struct members.
+<0>		"GatewayList"				{ mkL IdVar }
+<0>		"IpAddressList"				{ mkL IdVar }
+<0>		"IpAddress"				{ mkL IdVar }
+<0>		"IpMask"				{ mkL IdVar }
+<0>		"Next"					{ mkL IdVar }
+<0>		"QuadPart"				{ mkL IdVar }
+<0>		"String"				{ mkL IdVar }
+
+-- Windows typedefs.
+<0,ppSC>	@win_type				{ mkL IdStdType }
+
+-- System struct types.
+<0>		"addrinfo"				{ mkL IdSueType }
+<0>		"ifconf"				{ mkL IdSueType }
+<0>		"ifreq"					{ mkL IdSueType }
+<0>		"epoll_event"				{ mkL IdSueType }
+<0>		"ev_async"				{ mkL IdSueType }
+<0>		"ev_io"					{ mkL IdSueType }
+<0>		"ev_loop"				{ mkL IdSueType }
+<0>		"fd_set"				{ mkL IdSueType }
+<0>		"in_addr"				{ mkL IdSueType }
+<0>		"in6_addr"				{ mkL IdSueType }
+<0>		"ipv6_mreq"				{ mkL IdSueType }
+<0>		"pollfd"				{ mkL IdSueType }
+<0>		"sockaddr"("_in"|"_in6"|"_storage")?	{ mkL IdSueType }
+<0>		"timespec"				{ mkL IdSueType }
+<0>		"timeval"				{ mkL IdSueType }
+
+-- Sodium types.
+<0>		"crypto_generichash_blake2b_state"	{ mkL IdSueType }
+
+-- Sodium constants.
+<0,ppSC>	"crypto_"[a-z0-9_]+[A-Z][A-Z0-9_]*	{ mkL IdConst }
+
+-- Clang nullability qualifiers.
+<0,ppSC>	"_Nonnull"				{ mkL KwNonnull }
+<0,ppSC>	"_Nullable"				{ mkL KwNullable }
+
+-- Standard C (ish).
+<ppSC>		defined					{ mkL PpDefined }
+<ppSC>		\"[^\"]*\"				{ mkL LitString }
+<ppSC>		\n					{ mkL PpNewline `andBegin` 0 }
+<ppSC>		\\\n					;
+<ppSC>		" "					;
+<ppSC>		$white					{ mkE ErrorToken }
+
+<ignoreSC>	"//!TOKSTYLE+"				{ mkL IgnEnd `andBegin` 0 }
+<ignoreSC>	([^\/]+|.|\n)				{ mkL IgnBody }
+
+<0,ppSC>	"//"\n					;
+<0,ppSC>	"// ".*					;
+<0>		[\ \n]+					;
+<0>		$white					{ mkE ErrorToken }
+<0>		"//!TOKSTYLE-"				{ mkL IgnStart `andBegin` ignoreSC }
+<0>		"/*!"					{ mkL CmtStartCode }
+<0>		"*/"					{ mkL CmtEnd }
+<0>		"/*"					{ mkL CmtStart `andBegin` cmtSC }
+<0>		"/**"					{ mkL CmtStartDoc `andBegin` cmtSC }
+<0>		"/** @{"				{ mkL CmtStartDocSection `andBegin` cmtSC }
+<0>		"/** @} */"				{ mkL CmtEndDocSection }
+<0>		"/**""*"+				{ mkL CmtStartBlock `andBegin` cmtSC }
+<0,cmtSC>	\"(\\.|[^\"])*\"			{ mkL LitString }
+<0>		'(\\|[^'])*'				{ mkL LitChar }
+<0>		"<"[a-z0-9\.\/_]+">"			{ mkL LitSysInclude }
+<0>		"#if"					{ mkL PpIf `andBegin` ppSC }
+<0>		"#ifdef"				{ mkL PpIfdef }
+<0>		"#ifndef"				{ mkL PpIfndef }
+<0>		"#elif"					{ mkL PpElif `andBegin` ppSC }
+<0>		"#else"					{ mkL PpElse }
+<0>		"#endif"				{ mkL PpEndif }
+<0>		"#define"				{ mkL PpDefine `andBegin` ppSC }
+<0>		"#undef"				{ mkL PpUndef }
+<0>		"#include"				{ mkL PpInclude }
+<0,ppSC>	"tox_"?"bitwise"			{ mkL KwBitwise }
+<0,ppSC>	"tox_"?"force"				{ mkL KwForce }
+<0,ppSC>	"tox_"?"owner"				{ mkL KwOwner }
+<0,ppSC>	"_Owner"				{ mkL KwOwner }
+<0,ppSC>	"_Owned"				{ mkL KwOwner }
+<0,ppSC>	"break"					{ mkL KwBreak }
+<0,ppSC>	"case"					{ mkL KwCase }
+<0,ppSC>	"const"					{ mkL KwConst }
+<0,ppSC>	"continue"				{ mkL KwContinue }
+<0,ppSC>	"default"				{ mkL KwDefault }
+<0,ppSC>	"do"					{ mkL KwDo }
+<0,ppSC>	"else"					{ mkL KwElse }
+<0,ppSC>	"enum"					{ mkL KwEnum }
+<0,ppSC>	"extern"				{ mkL KwExtern }
+<0,ppSC>	"for"					{ mkL KwFor }
+<0,ppSC>	"goto"					{ mkL KwGoto }
+<0,ppSC>	"if"					{ mkL KwIf }
+<0,ppSC>	"return"				{ mkL KwReturn }
+<0,ppSC>	"sizeof"				{ mkL KwSizeof }
+<0,ppSC>	"static"				{ mkL KwStatic }
+<0,ppSC>	"static_assert"				{ mkL KwStaticAssert }
+<0,ppSC>	"struct"				{ mkL KwStruct }
+<0,ppSC>	"switch"				{ mkL KwSwitch }
+<0,ppSC>	"typedef"				{ mkL KwTypedef }
+<0,ppSC>	"union"					{ mkL KwUnion }
+<0,ppSC>	"void"					{ mkL KwVoid }
+<0,ppSC>	"while"					{ mkL KwWhile }
+<0,ppSC>	"bool"					{ mkL IdStdType }
+<0,ppSC>	"char"					{ mkL IdStdType }
+<0,ppSC>	"double"				{ mkL IdStdType }
+<0,ppSC>	"float"					{ mkL IdStdType }
+<0,ppSC>	"int"					{ mkL IdStdType }
+<0,ppSC>	"long int"				{ mkL IdStdType }
+<0,ppSC>	"long signed int"			{ mkL IdStdType }
+<0,ppSC>	"long"					{ mkL IdStdType }
+<0,ppSC>	"long long"				{ mkL IdStdType }
+<0,ppSC>	"signed int"				{ mkL IdStdType }
+<0,ppSC>	"unsigned int"				{ mkL IdStdType }
+<0,ppSC>	"unsigned long"				{ mkL IdStdType }
+<0,ppSC>	"unsigned long long"			{ mkL IdStdType }
+<0,ppSC>	"unsigned"				{ mkL IdStdType }
+<0,ppSC>	"va_list"				{ mkL IdStdType }
+<0,ppSC>	"false"					{ mkL LitFalse }
+<0,ppSC>	"true"					{ mkL LitTrue }
+<0,ppSC>	"__func__"				{ mkL IdVar }
+<0,ppSC>	"nullptr"				{ mkL IdConst }
+<0,ppSC>	"nullptr"				{ mkL IdConst }
+<0,ppSC>	"__" @alphanum_+ "__"?			{ mkL IdConst }
+<0,ppSC>	"_" @ident_upper			{ mkL IdConst }
+<0,ppSC>	$upper ($upper | $digit | \_){1,2}	{ mkL IdSueType }
+<0,ppSC>	@ident_upper				{ mkL IdConst }
+<0,ppSC>	@pascal_case				{ mkL IdSueType }
+<0,ppSC>	"cmp_" @ident_lower "_" [suet]		{ mkL IdSueType }
+<0,ppSC>	@ident_lower "_t"			{ mkL IdStdType }
+<0,ppSC>	@ident_lower "_cb"			{ mkL IdFuncType }
+<0,ppSC>	"cmp_" ("reader"|"writer"|"skipper")	{ mkL IdFuncType }
+<0,ppSC>	@camel_case				{ mkL IdVar }
+<0,ppSC>	@ident_lower				{ mkL IdVar }
+<0,ppSC,cmtSC>	[0-9]+[LU]*				{ mkL LitInteger }
+<0,ppSC,cmtSC>	[0-9]+"."[0-9]+[Ff]?			{ mkL LitFloat }
+<0,ppSC>	0x[0-9a-fA-F]+[LU]*			{ mkL LitInteger }
+<0,ppSC,cmtSC>	"="					{ mkL PctEq }
+<0,ppSC,cmtSC>	"=="					{ mkL PctEqEq }
+<0,ppSC>	"&"					{ mkL PctAmpersand }
+<0,ppSC>	"&&"					{ mkL PctAmpersandAmpersand }
+<0,ppSC>	"&="					{ mkL PctAmpersandEq }
+<0,ppSC>	"->"					{ mkL PctArrow }
+<0,ppSC,cmtSC>	","					{ mkL PctComma }
+<0,ppSC,cmtSC>	"+"					{ mkL PctPlus }
+<0,ppSC>	"++"					{ mkL PctPlusPlus }
+<0,ppSC>	"+="					{ mkL PctPlusEq }
+<0,ppSC,cmtSC>	"-"					{ mkL PctMinus }
+<0,ppSC>	"--"					{ mkL PctMinusMinus }
+<0,ppSC>	"-="					{ mkL PctMinusEq }
+<0,ppSC>	"~"					{ mkL PctTilde }
+<0,ppSC,cmtSC>	"/"					{ mkL PctSlash }
+<0,ppSC>	"/="					{ mkL PctSlashEq }
+<0,ppSC,cmtSC>	"."					{ mkL PctPeriod }
+<0,ppSC,cmtSC>	"..."					{ mkL PctEllipsis }
+<0,ppSC>	"%"					{ mkL PctPercent }
+<0,ppSC>	"%="					{ mkL PctPercentEq }
+<0,ppSC,cmtSC>	";"					{ mkL PctSemicolon }
+<0,ppSC,cmtSC>	":"					{ mkL PctColon }
+<0,ppSC,cmtSC>	"<"					{ mkL PctLess }
+<0,ppSC>	"<<"					{ mkL PctLessLess }
+<0,ppSC>	"<<="					{ mkL PctLessLessEq }
+<0,ppSC>	"<="					{ mkL PctLessEq }
+<0,ppSC,cmtSC>	">"					{ mkL PctGreater }
+<0,ppSC>	">>"					{ mkL PctGreaterGreater }
+<0,ppSC>	">>="					{ mkL PctGreaterGreaterEq }
+<0,ppSC,cmtSC>	">="					{ mkL PctGreaterEq }
+<0,ppSC>	"|"					{ mkL PctPipe }
+<0,ppSC>	"||"					{ mkL PctPipePipe }
+<0,ppSC>	"|="					{ mkL PctPipeEq }
+<0,ppSC>	"["					{ mkL PctLBrack }
+<0,ppSC>	"]"					{ mkL PctRBrack }
+<0,ppSC>	"{"					{ mkL PctLBrace }
+<0,ppSC>	"}"					{ mkL PctRBrace }
+<0,ppSC,cmtSC>	"("					{ mkL PctLParen }
+<0,ppSC,cmtSC>	")"					{ mkL PctRParen }
+<0,ppSC,cmtSC>	"?"					{ mkL PctQMark }
+<0,ppSC,cmtSC>	"!"					{ mkL PctEMark }
+<0,ppSC,cmtSC>	"!="					{ mkL PctEMarkEq }
+<0,ppSC>	"*"					{ mkL PctAsterisk }
+<0,ppSC>	"*="					{ mkL PctAsteriskEq }
+<0,ppSC>	"^"					{ mkL PctCaret }
+<0,ppSC>	"^="					{ mkL PctCaretEq }
+
+-- Comments.
+<cmtSC>		"Copyright ©"				{ mkL CmtSpdxCopyright }
+<cmtSC>		"SPDX-License-Identifier:"		{ mkL CmtSpdxLicense }
+<cmtSC>		"GPL-3.0-or-later"			{ mkL CmtWord }
+<cmtSC>		"TODO("[^\)]+"):"			{ mkL CmtWord }
+<cmtSC>		[0-2][0-9](":"[0-5][0-9]){2}"."[0-9]{3}	{ mkL CmtWord }
+<cmtSC>		"v"?[0-9]+("."[0-9]+)+			{ mkL CmtWord }
+<cmtSC>		[A-Z][A-Za-z]+"::"[a-z_]+		{ mkL CmtWord }
+<cmtSC>		([a-z]+"/")+[A-Za-z]+("."[a-z_]+)+	{ mkL CmtWord }
+<cmtSC>		[a-z]+("."[a-z_]+)+			{ mkL CmtWord }
+<cmtSC>		[a-z]+("-"[a-z_]+)+			{ mkL CmtWord }
+<cmtSC>		"@code"					{ mkL CmtCode `andBegin` codeSC }
+<cmtSC>		"<code>"				{ mkL CmtCode `andBegin` codeSC }
+<cmtSC>		"["[^\]]+"]"				{ mkL CmtAttr }
+<cmtSC>		[@\\][a-z_]+				{ mkL CmtCommand }
+<cmtSC>		"*"[A-Za-z][A-Za-z0-9_']*"*"		{ mkL CmtWord }
+<cmtSC>		"#"[A-Za-z][A-Za-z0-9_]*		{ mkL CmtRef }
+<cmtSC>		"_"*[A-Za-z][A-Za-z0-9_']*		{ mkL CmtWord }
+<cmtSC>		"#"[0-9]+				{ mkL CmtWord }
+<cmtSC>		"http://"[^\ ]+				{ mkL CmtWord }
+<cmtSC>		[0-9]+"%"				{ mkL LitInteger }
+<cmtSC>		"`"([^`]|"\`")+"`"			{ mkL CmtCode }
+<cmtSC>		"${"([^\}])+"}"				{ mkL CmtCode }
+<cmtSC>		"-"+					{ mkL CmtWord }
+<cmtSC>		[&\|]+					{ mkL CmtWord }
+<cmtSC>		"–"					{ mkL CmtWord }
+<cmtSC>		"*/"					{ mkL CmtEnd `andBegin` 0 }
+<cmtSC>		\n					{ mkL PpNewline `andBegin` cmtNewlineSC }
+<cmtSC>		" "+					{ mkL CmtSpace }
+
+<cmtNewlineSC>	" "+"*"+"/"				{ mkL CmtEnd `andBegin` 0 }
+<cmtNewlineSC>	" "+"*"					{ begin cmtSC }
+
+<codeStartSC>	" "+					{ mkL CmtSpace `andBegin` codeSC }
+<codeStartSC>	\n					{ mkL PpNewline `andBegin` codeNewlineSC }
+
+<codeNewlineSC>	" "+"*"					{ begin codeStartSC }
+
+-- <code></code> blocks in comments.
+<codeSC>	"@endcode"				{ mkL CmtCode `andBegin` cmtSC }
+<codeSC>	"</code>"				{ mkL CmtCode `andBegin` cmtSC }
+<codeSC>	\n					{ mkL PpNewline `andBegin` codeNewlineSC }
+<codeSC>	[^@\<]+					{ mkL CmtCode }
+
+-- Error handling.
+<0,ppSC,cmtSC,codeSC>	.				{ mkL ErrorToken }
+
+{
+deriving instance Generic AlexPosn
+instance FromJSON AlexPosn
+instance FromJSONKey AlexPosn where fromJSONKey = Aeson.FromJSONKeyText (read . Text.unpack)
+instance ToJSON AlexPosn
+instance ToJSONKey AlexPosn where toJSONKey = Aeson.toJSONKeyText (Text.pack . show)
+instance Hashable AlexPosn
+deriving instance Read AlexPosn
+
+instance Arbitrary AlexPosn where
+    arbitrary = AlexPn <$> arbitrary <*> arbitrary <*> arbitrary
+
+data Lexeme text = L AlexPosn LexemeClass text
+    deriving (Eq, Show, Read, Generic, Functor, Foldable, Traversable, Ord)
+
+instance Arbitrary text => Arbitrary (Lexeme text) where
+    arbitrary = L <$> arbitrary <*> arbitrary <*> arbitrary
+
+
+instance FromJSON text => FromJSON (Lexeme text)
+instance ToJSON text => ToJSON (Lexeme text)
+instance Hashable text => Hashable (Lexeme text) where
+    hashWithSalt s (L p c t) = s `hashWithSalt` p `hashWithSalt` c `hashWithSalt` t
+
+mkL :: LexemeClass -> AlexInput -> Int64 -> Alex (Lexeme Text)
+mkL c (p, _, str, _) len = pure $ L p c (piece str)
+  where piece = Text.decodeUtf8 . LBS.toStrict . LBS.take len
+
+mkE :: LexemeClass -> AlexInput -> Int64 -> Alex (Lexeme Text)
+mkE c (p, _, str, _) len = alexError $ ": " <> show (L p c (piece str))
+  where piece = Text.decodeUtf8 . LBS.toStrict . LBS.take len
+
+lexemePosn :: Lexeme text -> AlexPosn
+lexemePosn (L p _ _) = p
+
+lexemeClass :: Lexeme text -> LexemeClass
+lexemeClass (L _ c _) = c
+
+lexemeText :: Lexeme text -> text
+lexemeText (L _ _ s) = s
+
+lexemeLine :: Lexeme text -> Int
+lexemeLine (L (AlexPn _ l _) _ _) = l
+
+alexEOF :: Alex (Lexeme Text)
+alexEOF = return (L (AlexPn 0 0 0) Eof Text.empty)
+
+data Context
+    = Context String
+    | ContextLexeme String (Lexeme Text)
+    | ContextNode String (Node (Lexeme Text))
+    deriving (Eq, Show, Read, Generic)
+
+instance FromJSON Context
+instance ToJSON Context
+instance Hashable Context
+
+data AlexUserState = AlexUserState { alex_context :: [Context] }
+alexInitUserState = AlexUserState []
+
+data ParseError = ParseError
+    { errorPosn     :: AlexPosn
+    , errorContext  :: [Context]
+    , errorExpected :: [String]
+    , errorLexeme   :: Lexeme Text
+    } deriving (Eq, Show, Read, Generic)
+
+instance FromJSON ParseError
+instance ToJSON ParseError
+instance Hashable ParseError
+
+pushContext :: Context -> Alex ()
+pushContext ctx = Alex $ \s ->
+    let us = alex_ust s
+        us' = us { alex_context = ctx : alex_context us }
+    in Right (s { alex_ust = us' }, ())
+
+popContext :: Alex ()
+popContext = Alex $ \s ->
+    let us = alex_ust s
+        us' = us { alex_context = case alex_context us of [] -> []; (_:cs) -> cs }
+    in Right (s { alex_ust = us' }, ())
+
+getContext :: Alex [Context]
+getContext = Alex $ \s -> Right (s, alex_context (alex_ust s))
+
+alexScanTokens :: LBS.ByteString -> Either String [Lexeme Text]
+alexScanTokens str =
+    runAlex str $ loop []
+  where
+    loop toks = do
+        tok@(L _ cl _) <- alexMonadScan
+        if cl == Eof
+            then return $ reverse toks
+            else loop $! (tok:toks)
+}
diff --git a/test/examples/Cimple/Parser.y b/test/examples/Cimple/Parser.y
new file mode 100644
--- /dev/null
+++ b/test/examples/Cimple/Parser.y
@@ -0,0 +1,844 @@
+{
+{-# LANGUAGE CPP               #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE TemplateHaskell   #-}
+module Language.Cimple.Parser
+    ( parseExpr
+    , parseStmt
+    , parseTranslationUnit
+    , preprocessorEnabled
+    , source
+    ) where
+
+import qualified Data.ByteString             as BS
+import           Data.FileEmbed              (embedFile)
+import           Data.Fix                    (Fix (..))
+import           Data.Text                   (Text)
+import qualified Data.Text                   as Text
+import           Language.Cimple.Ast         (AssignOp (..), BinaryOp (..),
+                                              CommentStyle (..),
+                                              LiteralType (..), Node,
+                                              NodeF (..), Nullability (..),
+                                              Scope (..), UnaryOp (..))
+import           Language.Cimple.Parser.Error (parseError)
+import           Language.Cimple.Lexer       (Alex, AlexPosn (..), Lexeme (..),
+                                              alexError, alexMonadScan)
+import           Language.Cimple.Tokens      (LexemeClass (..))
+}
+
+%expect 0
+
+%name parseTranslationUnit TranslationUnit
+%name parseExpr Expr
+%name parseStmt Stmt
+
+%error {parseError}
+%errorhandlertype explist
+%lexer {lexwrap} {L _ Eof _}
+%monad {Alex}
+%tokentype {Term}
+%token
+    ID_CONST			{ L _ IdConst			_ }
+    ID_FUNC_TYPE		{ L _ IdFuncType		_ }
+    ID_STD_TYPE			{ L _ IdStdType			_ }
+    ID_SUE_TYPE			{ L _ IdSueType			_ }
+    ID_VAR			{ L _ IdVar			_ }
+    bitwise			{ L _ KwBitwise			_ }
+    break			{ L _ KwBreak			_ }
+    case			{ L _ KwCase			_ }
+    const			{ L _ KwConst			_ }
+    continue			{ L _ KwContinue		_ }
+    default			{ L _ KwDefault			_ }
+    do				{ L _ KwDo			_ }
+    else			{ L _ KwElse			_ }
+    enum			{ L _ KwEnum			_ }
+    extern			{ L _ KwExtern			_ }
+    for				{ L _ KwFor			_ }
+    force			{ L _ KwForce			_ }
+    GNU_ALLOC_SIZE		{ L _ KwGnuAllocSize		_ }
+    GNU_PRINTF			{ L _ KwGnuPrintf		_ }
+    goto			{ L _ KwGoto			_ }
+    if				{ L _ KwIf			_ }
+    nonnull			{ L _ KwNonnull			_ }
+    nullable			{ L _ KwNullable		_ }
+    owner			{ L _ KwOwner			_ }
+    return			{ L _ KwReturn			_ }
+    sizeof			{ L _ KwSizeof			_ }
+    static			{ L _ KwStatic			_ }
+    static_assert		{ L _ KwStaticAssert		_ }
+    struct			{ L _ KwStruct			_ }
+    switch			{ L _ KwSwitch			_ }
+    typedef			{ L _ KwTypedef			_ }
+    union			{ L _ KwUnion			_ }
+    VLA				{ L _ KwVla			_ }
+    void			{ L _ KwVoid			_ }
+    while			{ L _ KwWhile			_ }
+    LIT_CHAR			{ L _ LitChar			_ }
+    LIT_FLOAT			{ L _ LitFloat			_ }
+    LIT_FALSE			{ L _ LitFalse			_ }
+    LIT_TRUE			{ L _ LitTrue			_ }
+    LIT_INTEGER			{ L _ LitInteger		_ }
+    LIT_STRING			{ L _ LitString			_ }
+    LIT_SYS_INCLUDE		{ L _ LitSysInclude		_ }
+    '&'				{ L _ PctAmpersand		_ }
+    '&&'			{ L _ PctAmpersandAmpersand	_ }
+    '&='			{ L _ PctAmpersandEq		_ }
+    '->'			{ L _ PctArrow			_ }
+    '*'				{ L _ PctAsterisk		_ }
+    '*='			{ L _ PctAsteriskEq		_ }
+    '^'				{ L _ PctCaret			_ }
+    '^='			{ L _ PctCaretEq		_ }
+    ':'				{ L _ PctColon			_ }
+    ','				{ L _ PctComma			_ }
+    '!'				{ L _ PctEMark			_ }
+    '!='			{ L _ PctEMarkEq		_ }
+    '='				{ L _ PctEq			_ }
+    '=='			{ L _ PctEqEq			_ }
+    '>'				{ L _ PctGreater		_ }
+    '>='			{ L _ PctGreaterEq		_ }
+    '>>'			{ L _ PctGreaterGreater		_ }
+    '>>='			{ L _ PctGreaterGreaterEq	_ }
+    '{'				{ L _ PctLBrace			_ }
+    '['				{ L _ PctLBrack			_ }
+    '<'				{ L _ PctLess			_ }
+    '<='			{ L _ PctLessEq			_ }
+    '<<'			{ L _ PctLessLess		_ }
+    '<<='			{ L _ PctLessLessEq		_ }
+    '('				{ L _ PctLParen			_ }
+    '-'				{ L _ PctMinus			_ }
+    '-='			{ L _ PctMinusEq		_ }
+    '--'			{ L _ PctMinusMinus		_ }
+    '%'				{ L _ PctPercent		_ }
+    '%='			{ L _ PctPercentEq		_ }
+    '.'				{ L _ PctPeriod			_ }
+    '...'			{ L _ PctEllipsis		_ }
+    '|'				{ L _ PctPipe			_ }
+    '|='			{ L _ PctPipeEq			_ }
+    '||'			{ L _ PctPipePipe		_ }
+    '+'				{ L _ PctPlus			_ }
+    '+='			{ L _ PctPlusEq			_ }
+    '++'			{ L _ PctPlusPlus		_ }
+    '?'				{ L _ PctQMark			_ }
+    '}'				{ L _ PctRBrace			_ }
+    ']'				{ L _ PctRBrack			_ }
+    ')'				{ L _ PctRParen			_ }
+    ';'				{ L _ PctSemicolon		_ }
+    '/'				{ L _ PctSlash			_ }
+    '/='			{ L _ PctSlashEq		_ }
+    '~'				{ L _ PctTilde			_ }
+    'defined'			{ L _ PpDefined			_ }
+    '#define'			{ L _ PpDefine			_ }
+    '#elif'			{ L _ PpElif			_ }
+    '#else'			{ L _ PpElse			_ }
+    '#endif'			{ L _ PpEndif			_ }
+    '#if'			{ L _ PpIf			_ }
+    '#ifdef'			{ L _ PpIfdef			_ }
+    '#ifndef'			{ L _ PpIfndef			_ }
+    '#include'			{ L _ PpInclude			_ }
+    '#undef'			{ L _ PpUndef			_ }
+    '\n'			{ L _ PpNewline			_ }
+    '/*'			{ L _ CmtStart			_ }
+    '/*!'			{ L _ CmtStartCode		_ }
+    '/**'			{ L _ CmtStartDoc		_ }
+    '/** @{'			{ L _ CmtStartDocSection	_ }
+    '/** @} */'			{ L _ CmtEndDocSection		_ }
+    '/***'			{ L _ CmtStartBlock		_ }
+    ' '				{ L _ CmtSpace			_ }
+    '*/'			{ L _ CmtEnd			_ }
+    'Copyright'			{ L _ CmtSpdxCopyright		_ }
+    'License'			{ L _ CmtSpdxLicense		_ }
+    CMT_ATTR			{ L _ CmtAttr			_ }
+    CMT_CODE			{ L _ CmtCode			_ }
+    CMT_COMMAND			{ L _ CmtCommand		_ }
+    CMT_WORD			{ L _ CmtWord			_ }
+    CMT_REF			{ L _ CmtRef			_ }
+    IGN_START			{ L _ IgnStart			_ }
+    IGN_BODY			{ L _ IgnBody			_ }
+    IGN_END			{ L _ IgnEnd			_ }
+
+%left ','
+%right '=' '+=' '-=' '*=' '/=' '%=' '<<=' '>>=' '&=' '^=' '|='
+%right '?' ':'
+%left '||'
+%left '&&'
+%left '|'
+%left '^'
+%left '&'
+%left '!=' '=='
+%left '<' '<=' '>' '>='
+%left '<<' '>>'
+%left '+' '-'
+%left '*' '/' '%'
+%right CAST ADDRESS NEG DEREF sizeof '!' '~' '++' '--'
+%left '->' '.' '(' '['
+
+%%
+
+TranslationUnit :: { [NonTerm] }
+TranslationUnit
+:	ToplevelDecls						{ reverse $1 }
+|	LicenseDecl ToplevelDecls				{ $1 : reverse $2 }
+
+LicenseDecl :: { NonTerm }
+LicenseDecl
+:	'/*' ' ' 'License' ' ' CMT_WORD '\n' CopyrightDecls '*/'	{ Fix $ LicenseDecl $5 (reverse $7) }
+
+CopyrightDecls :: { [NonTerm] }
+CopyrightDecls
+:	CopyrightDecl						{ [$1] }
+|	CopyrightDecls CopyrightDecl				{ $2 : $1 }
+
+CopyrightDecl :: { NonTerm }
+CopyrightDecl
+:	' ' 'Copyright' ' ' CopyrightDates ' ' CopyrightOwner '\n'	{ Fix $ CopyrightDecl (fst $4) (snd $4) $6 }
+
+CopyrightDates :: { (Term, Maybe Term) }
+CopyrightDates
+:	LIT_INTEGER						{ ($1, Nothing) }
+|	LIT_INTEGER '-' LIT_INTEGER				{ ($1, Just $3) }
+
+CopyrightOwner :: { [Term] }
+CopyrightOwner
+:	CMT_WORD CommentWords					{ $1 : reverse $2 }
+
+ToplevelDecls :: { [NonTerm] }
+ToplevelDecls
+:	ToplevelDecl						{ [$1] }
+|	ToplevelDecls ToplevelDecl				{ $2 : $1 }
+
+ToplevelDecl :: { NonTerm }
+ToplevelDecl
+:	AggregateDecl						{ $1 }
+|	Comment							{ $1 }
+|	ConstDecl						{ $1 }
+|	EnumDecl						{ $1 }
+|	ExternC							{ $1 }
+|	FunctionDecl						{ $1 }
+|	PreprocDefine						{ $1 }
+|	PreprocIfdef(ToplevelDecls)				{ $1 }
+|	PreprocIf(ToplevelDecls)				{ $1 }
+|	PreprocInclude						{ $1 }
+|	PreprocUndef						{ $1 }
+|	StaticAssert						{ $1 }
+|	TypedefDecl						{ $1 }
+
+StaticAssert :: { NonTerm }
+StaticAssert
+:	static_assert '(' ConstExpr ',' LIT_STRING ')' ';'	{ Fix $ StaticAssert $3 $5 }
+
+Comment :: { NonTerm }
+Comment
+:	'/*' CommentTokens '*/'					{ Fix $ Comment Regular $1 (reverse $2) $3 }
+|	'/**' CommentTokens '*/'				{ Fix $ Comment Doxygen $1 (reverse $2) $3 }
+|	'/** @{' CommentTokens '*/'				{ Fix $ Comment Section $1 (reverse $2) $3 }
+|	'/***' CommentTokens '*/'				{ Fix $ Comment Block $1 (reverse $2) $3 }
+|	'/** @} */'						{ Fix $ CommentSectionEnd $1 }
+|	Ignore							{ $1 }
+
+CommentTokens :: { [Term] }
+CommentTokens
+:	CommentToken						{ [$1] }
+|	CommentTokens CommentToken				{ $2 : $1 }
+
+CommentToken :: { Term }
+CommentToken
+:	CommentWord						{ $1 }
+|	'\n'							{ $1 }
+
+CommentWords :: { [Term] }
+CommentWords
+:								{ [] }
+|	CommentWords CommentWord				{ $2 : $1 }
+
+CommentWord :: { Term }
+CommentWord
+:	CMT_WORD						{ $1 }
+|	CMT_COMMAND						{ $1 }
+|	CMT_ATTR						{ $1 }
+|	CMT_REF							{ $1 }
+|	CMT_CODE						{ $1 }
+|	LIT_FLOAT						{ $1 }
+|	LIT_INTEGER						{ $1 }
+|	LIT_STRING						{ $1 }
+|	' '							{ $1 }
+|	'.'							{ $1 }
+|	'...'							{ $1 }
+|	'?'							{ $1 }
+|	'!'							{ $1 }
+|	','							{ $1 }
+|	';'							{ $1 }
+|	':'							{ $1 }
+|	'('							{ $1 }
+|	')'							{ $1 }
+|	'<'							{ $1 }
+|	'>'							{ $1 }
+|	'/'							{ $1 }
+|	'+'							{ $1 }
+|	'-'							{ $1 }
+|	'='							{ $1 }
+|	'=='							{ $1 }
+|	'!='							{ $1 }
+|	'>='							{ $1 }
+
+Ignore :: { NonTerm }
+Ignore
+:	IGN_START IgnoreBody IGN_END				{ Fix $ Comment Ignore $1 (reverse $2) $3 }
+
+IgnoreBody :: { [Term] }
+IgnoreBody
+:	IGN_BODY						{ [$1] }
+|	IgnoreBody IGN_BODY					{ $2 : $1 }
+
+PreprocIfdef(decls)
+:	'#ifdef' ID_CONST decls PreprocElif(decls) Endif	{ Fix $ PreprocIfdef $2 (reverse $3) $4 }
+|	'#ifndef' ID_CONST decls PreprocElif(decls) Endif	{ Fix $ PreprocIfndef $2 (reverse $3) $4 }
+
+PreprocIf(decls)
+:	'#if' PreprocConstExpr '\n' decls PreprocElif(decls) Endif	{ Fix $ PreprocIf $2 (reverse $4) $5 }
+
+PreprocElif(decls)
+:	PreprocElse(decls)					{ $1 }
+|	'#elif' PreprocConstExpr '\n' decls PreprocElif(decls)	{ Fix $ PreprocElif $2 (reverse $4) $5 }
+
+PreprocElse(decls)
+:								{ Fix $ PreprocElse [] }
+|	'#else' decls						{ Fix $ PreprocElse (reverse $2) }
+
+Endif :: { [Term] }
+Endif
+:	'#endif' Comment					{ [$1] }
+
+PreprocInclude :: { NonTerm }
+PreprocInclude
+:	'#include' LIT_STRING					{ Fix $ PreprocInclude $2 }
+|	'#include' LIT_SYS_INCLUDE				{ Fix $ PreprocInclude $2 }
+
+PreprocDefine :: { NonTerm }
+PreprocDefine
+:	'#define' ID_CONST '\n'					{ Fix $ PreprocDefine $2 }
+|	'#define' ID_CONST PreprocSafeExpr(ConstExpr) '\n'	{ Fix $ PreprocDefineConst $2 $3 }
+|	'#define' ID_CONST MacroParamList MacroBody '\n'	{ Fix $ PreprocDefineMacro $2 $3 $4 }
+
+PreprocUndef :: { NonTerm }
+PreprocUndef
+:	'#undef' ID_CONST					{ Fix $ PreprocUndef $2 }
+
+PreprocConstExpr :: { NonTerm }
+PreprocConstExpr
+:	PreprocSafeExpr(PreprocConstExpr)			{ $1 }
+|	PureExprOps(PreprocConstExpr)				{ $1 }
+|	'defined' '(' ID_CONST ')'				{ Fix $ PreprocDefined $3 }
+
+MacroParamList :: { [NonTerm] }
+MacroParamList
+:	'(' ')'							{ [] }
+|	'(' MacroParams ')'					{ reverse $2 }
+|	'(' MacroParams ',' '...' ')'				{ reverse $ Fix Ellipsis : $2 }
+
+MacroParams :: { [NonTerm] }
+MacroParams
+:	MacroParam						{ [$1] }
+|	MacroParams ',' MacroParam				{ $3 : $1 }
+
+MacroParam :: { NonTerm }
+MacroParam
+:	ID_VAR							{ Fix $ MacroParam $1 }
+
+MacroBody :: { NonTerm }
+MacroBody
+:	do CompoundStmt while '(' LIT_INTEGER ')'		{% macroBodyStmt $2 $5 }
+|	FunctionCall						{ Fix $ MacroBodyFunCall $1 }
+
+ExternC :: { NonTerm }
+ExternC
+:	'#ifdef' ID_CONST
+	extern LIT_STRING '{'
+	'#endif'
+	ToplevelDecls
+	'#ifdef' ID_CONST
+	'}' Comment
+	'#endif'						{% externC $2 $4 (reverse $7) $9 }
+
+Stmts :: { [NonTerm] }
+Stmts
+:	Stmt							{ [$1] }
+|	Stmts Stmt						{ $2 : $1 }
+
+Stmt :: { NonTerm }
+Stmt
+:	PreprocIfdef(Stmts)					{ $1 }
+|	PreprocIf(Stmts)					{ $1 }
+|	PreprocDefine Stmts PreprocUndef			{ Fix $ PreprocScopedDefine $1 (reverse $2) $3 }
+|	DeclStmt						{ $1 }
+|	CompoundStmt						{ $1 }
+|	IfStmt(ReturnStmt)					{ $1 }
+|	IfStmt(CompoundStmt)					{ $1 }
+|	ForStmt							{ $1 }
+|	WhileStmt						{ $1 }
+|	DoWhileStmt						{ $1 }
+|	StaticAssert						{ $1 }
+|	AssignExpr ';'						{ Fix $ ExprStmt $1 }
+|	ExprStmt ';'						{ Fix $ ExprStmt $1 }
+|	FunctionCall ';'					{ Fix $ ExprStmt $1 }
+|	break ';'						{ Fix $ Break }
+|	goto ID_CONST ';'					{ Fix $ Goto $2 }
+|	ID_CONST ':' Stmt					{ Fix $ Label $1 $3 }
+|	continue ';'						{ Fix $ Continue }
+|	switch '(' Expr ')' '{' SwitchCases '}'			{ Fix $ SwitchStmt $3 (reverse $6) }
+|	ReturnStmt						{ $1 }
+|	Comment							{ $1 }
+
+ReturnStmt :: { NonTerm }
+ReturnStmt
+:	return ';'						{ Fix $ Return Nothing }
+|	return Expr ';'						{ Fix $ Return (Just $2) }
+
+IfStmt(x)
+:	if '(' Expr ')' x					{ Fix $ IfStmt $3 $5 Nothing }
+|	if '(' Expr ')' x else x				{ Fix $ IfStmt $3 $5 (Just $7) }
+|	if '(' Expr ')' x else IfStmt(x)			{ Fix $ IfStmt $3 $5 (Just $7) }
+
+ForStmt :: { NonTerm }
+ForStmt
+:	for '(' ForInit Expr ';' ForNext ')' CompoundStmt	{ Fix $ ForStmt $3 $4 $6 $8 }
+
+ForInit :: { NonTerm }
+ForInit
+:	AssignExpr ';'						{ Fix $ ExprStmt $1 }
+|	VarDeclStmt						{ $1 }
+
+ForNext :: { NonTerm }
+ForNext
+:	ExprStmt						{ $1 }
+|	AssignExpr						{ $1 }
+
+WhileStmt :: { NonTerm }
+WhileStmt
+:	while '(' Expr ')' CompoundStmt				{ Fix $ WhileStmt $3 $5 }
+
+DoWhileStmt :: { NonTerm }
+DoWhileStmt
+:	do CompoundStmt while '(' Expr ')' ';'			{ Fix $ DoWhileStmt $2 $5 }
+
+SwitchCases :: { [NonTerm] }
+SwitchCases
+:	SwitchCase						{ [$1] }
+|	SwitchCases SwitchCase					{ $2 : $1 }
+
+SwitchCase :: { NonTerm }
+SwitchCase
+:	case Expr ':' SwitchCaseBody				{ Fix $ Case $2 $4 }
+|	default ':' SwitchCaseBody				{ Fix $ Default $3 }
+
+SwitchCaseBody :: { NonTerm }
+SwitchCaseBody
+:	CompoundStmt						{ $1 }
+|	SwitchCase						{ $1 }
+|	break ';'						{ Fix $ Break }
+|	return Expr ';'						{ Fix $ Return (Just $2) }
+
+DeclStmt :: { NonTerm }
+DeclStmt
+:	VarDeclStmt						{ $1 }
+|	VLA '(' QualType(GlobalLeafType) ',' ID_VAR ',' Expr ')' ';'	{ Fix $ VLA $3 $5 $7 }
+
+VarDeclStmt :: { NonTerm }
+VarDeclStmt
+:	VarDecl '=' InitialiserExpr ';'				{ Fix $ VarDeclStmt $1 (Just $3) }
+|	VarDecl ';'						{ Fix $ VarDeclStmt $1 Nothing }
+
+VarDecl :: { NonTerm }
+VarDecl
+:	QualType(LocalLeafType) ID_VAR DeclSpecArrays		{ Fix $ VarDecl $1 $2 $3 }
+
+DeclSpecArrays :: { [NonTerm] }
+DeclSpecArrays
+:								{ [] }
+|	DeclSpecArrays DeclSpecArray				{ $2 : $1 }
+
+DeclSpecArray :: { NonTerm }
+DeclSpecArray
+:	'[' Nullability ']'					{ Fix $ DeclSpecArray $2 Nothing }
+|	'[' Nullability Expr ']'				{ Fix $ DeclSpecArray $2 (Just $3) }
+|	'[' '/*!' Expr '*/' ']'					{ Fix $ DeclSpecArray NullabilityUnspecified (Just $3) }
+|	'[' nullable '/*!' Expr '*/' ']'			{ Fix $ DeclSpecArray Nullable (Just $4) }
+|	'[' nonnull '/*!' Expr '*/' ']'				{ Fix $ DeclSpecArray Nonnull (Just $4) }
+|	'[' CommentNullability ']'				{ Fix $ DeclSpecArray $2 Nothing }
+|	'[' CommentNullability Expr ']'				{ Fix $ DeclSpecArray $2 (Just $3) }
+
+InitialiserExpr :: { NonTerm }
+InitialiserExpr
+:	InitialiserList						{ Fix $ InitialiserList $1 }
+|	Expr							{ $1 }
+
+InitialiserList :: { [NonTerm] }
+InitialiserList
+:	'{' Initialisers '}'					{ reverse $2 }
+|	'{' Initialisers ',' '}'				{ reverse $2 }
+
+Initialisers :: { [NonTerm] }
+Initialisers
+:	Initialiser						{ [$1] }
+|	Initialisers ',' Initialiser				{ $3 : $1 }
+
+Initialiser :: { NonTerm }
+Initialiser
+:	Expr							{ $1 }
+|	InitialiserList						{ Fix $ InitialiserList $1 }
+
+CompoundStmt :: { NonTerm }
+CompoundStmt
+:	'{' Stmts '}'						{ Fix $ CompoundStmt (reverse $2) }
+
+-- Expressions that are safe for use as macro body without () around it..
+PreprocSafeExpr(x)
+:	PreprocAtoms(x)						{ $1 }
+|	'(' QualType(LocalLeafType) ')' x %prec CAST		{ Fix $ CastExpr $2 $4 }
+|	sizeof '(' Expr ')'					{ Fix $ SizeofExpr $3 }
+|	sizeof '(' QualType(LocalLeafType) ')'			{ Fix $ SizeofType $3 }
+
+PreprocAtoms(x)
+:	LiteralExpr						{ $1 }
+|	'(' x ')'						{ Fix $ ParenExpr $2 }
+
+ConstExpr :: { NonTerm }
+ConstExpr
+:	PreprocSafeExpr(ConstExpr)				{ $1 }
+|	PureExprOps(ConstExpr)					{ $1 }
+|	'defined' '(' ID_CONST ')'				{ Fix $ PreprocDefined $3 }
+
+PureExprOps(x)
+:	x '!=' x						{ Fix $ BinaryExpr $1 BopNe $3 }
+|	x '==' x						{ Fix $ BinaryExpr $1 BopEq $3 }
+|	x '||' x						{ Fix $ BinaryExpr $1 BopOr $3 }
+|	x '^' x							{ Fix $ BinaryExpr $1 BopBitXor $3 }
+|	x '|' x							{ Fix $ BinaryExpr $1 BopBitOr $3 }
+|	x '&&' x						{ Fix $ BinaryExpr $1 BopAnd $3 }
+|	x '&' x							{ Fix $ BinaryExpr $1 BopBitAnd $3 }
+|	x '/' x							{ Fix $ BinaryExpr $1 BopDiv $3 }
+|	x '*' x							{ Fix $ BinaryExpr $1 BopMul $3 }
+|	x '%' x							{ Fix $ BinaryExpr $1 BopMod $3 }
+|	x '+' x							{ Fix $ BinaryExpr $1 BopPlus $3 }
+|	x '-' x							{ Fix $ BinaryExpr $1 BopMinus $3 }
+|	x '<' x							{ Fix $ BinaryExpr $1 BopLt $3 }
+|	x '<=' x						{ Fix $ BinaryExpr $1 BopLe $3 }
+|	x '<<' x						{ Fix $ BinaryExpr $1 BopLsh $3 }
+|	x '>' x							{ Fix $ BinaryExpr $1 BopGt $3 }
+|	x '>=' x						{ Fix $ BinaryExpr $1 BopGe $3 }
+|	x '>>' x						{ Fix $ BinaryExpr $1 BopRsh $3 }
+|	x '?' x ':' x						{ Fix $ TernaryExpr $1 $3 $5 }
+|	'!' x							{ Fix $ UnaryExpr UopNot $2 }
+|	'~' x							{ Fix $ UnaryExpr UopNeg $2 }
+|	'-' x %prec NEG						{ Fix $ UnaryExpr UopMinus $2 }
+|	'&' x %prec ADDRESS					{ Fix $ UnaryExpr UopAddress $2 }
+
+LiteralExpr :: { NonTerm }
+LiteralExpr
+:	StringLiteralExpr					{ $1 }
+|	LIT_CHAR						{ Fix $ LiteralExpr Char $1 }
+|	LIT_FLOAT						{ Fix $ LiteralExpr Float $1 }
+|	LIT_INTEGER						{ Fix $ LiteralExpr Int $1 }
+|	LIT_FALSE						{ Fix $ LiteralExpr Bool $1 }
+|	LIT_TRUE						{ Fix $ LiteralExpr Bool $1 }
+|	ID_CONST						{ Fix $ LiteralExpr ConstId $1 }
+
+StringLiteralExpr :: { NonTerm }
+StringLiteralExpr
+:	LIT_STRING						{ Fix $ LiteralExpr String $1 }
+|	StringLiteralExpr LIT_STRING				{ $1 }
+
+PrimaryExpr :: { NonTerm }
+PrimaryExpr
+:	ID_VAR							{ Fix $ VarExpr $1 }
+|	LiteralExpr						{ $1 }
+|	CompoundLiteral						{ $1 }
+|	'(' Expr ')'						{ Fix $ ParenExpr $2 }
+
+PostfixExpr :: { NonTerm }
+PostfixExpr
+:	PrimaryExpr						{ $1 }
+|	PostfixExpr '[' Expr ']'				{ Fix $ ArrayAccess $1 $3 }
+|	PostfixExpr '.' ID_VAR					{ Fix $ MemberAccess $1 $3 }
+|	PostfixExpr '->' ID_VAR					{ Fix $ PointerAccess $1 $3 }
+|	FunctionCall						{ $1 }
+
+LhsExpr :: { NonTerm }
+LhsExpr
+:	PostfixExpr						{ $1 }
+|	'*' LhsExpr %prec DEREF					{ Fix $ UnaryExpr UopDeref $2 }
+
+Expr :: { NonTerm }
+Expr
+:	LhsExpr							{ $1 }
+|	PureExprOps(Expr)					{ $1 }
+|	'(' QualType(LocalLeafType) ')' Expr %prec CAST		{ Fix $ CastExpr $2 $4 }
+|	sizeof '(' Expr ')'					{ Fix $ SizeofExpr $3 }
+|	sizeof '(' QualType(LocalLeafType) ')'			{ Fix $ SizeofType $3 }
+|	ExprStmt						{ $1 }
+
+-- Allow `(Type){0}` to set struct values to all-zero.
+CompoundLiteral :: { NonTerm }
+CompoundLiteral
+:	'(' QualType(LocalLeafType) ')' '{' ZeroInitExpr '}'	{ Fix $ CompoundLiteral $2 $5 }
+
+ZeroInitExpr :: { NonTerm }
+ZeroInitExpr
+:	ID_VAR							{ Fix $ VarExpr $1 }
+|	LIT_CHAR						{ Fix $ LiteralExpr Char $1 }
+|	LIT_FLOAT						{ Fix $ LiteralExpr Float $1 }
+|	LIT_INTEGER						{ Fix $ LiteralExpr Int $1 }
+|	LIT_FALSE						{ Fix $ LiteralExpr Bool $1 }
+|	ID_CONST						{ Fix $ LiteralExpr ConstId $1 }
+|	'{' ZeroInitExpr '}'					{ Fix $ InitialiserList [$2] }
+
+AssignExpr :: { NonTerm }
+AssignExpr
+:	LhsExpr AssignOperator Expr				{ Fix $ AssignExpr $1 $2 $3 }
+
+AssignOperator :: { AssignOp }
+AssignOperator
+:	'='							{ AopEq      }
+|	'*='							{ AopMul     }
+|	'/='							{ AopDiv     }
+|	'+='							{ AopPlus    }
+|	'-='							{ AopMinus   }
+|	'&='							{ AopBitAnd  }
+|	'|='							{ AopBitOr   }
+|	'^='							{ AopBitXor  }
+|	'%='							{ AopMod     }
+|	'<<='							{ AopLsh     }
+|	'>>='							{ AopRsh     }
+
+ExprStmt :: { NonTerm }
+ExprStmt
+:	'++' Expr						{ Fix $ UnaryExpr UopIncr $2 }
+|	'--' Expr						{ Fix $ UnaryExpr UopDecr $2 }
+
+FunctionCall :: { NonTerm }
+FunctionCall
+:	PostfixExpr ArgList					{ Fix $ FunctionCall $1 $2 }
+
+ArgList :: { [NonTerm] }
+ArgList
+:	'(' ')'							{ [] }
+|	'(' Args ')'						{ reverse $2 }
+
+Args :: { [NonTerm] }
+Args
+:	Arg							{ [$1] }
+|	Args ',' Arg						{ $3 : $1 }
+
+Arg :: { NonTerm }
+Arg
+:	Expr							{ $1 }
+|	Comment Expr						{ Fix $ CommentExpr $1 $2 }
+
+EnumDecl :: { NonTerm }
+EnumDecl
+:	enum ID_SUE_TYPE EnumeratorList ';'			{ Fix $ EnumConsts (Just $2) $3 }
+|	enum             EnumeratorList ';'			{ Fix $ EnumConsts Nothing $2 }
+|	typedef enum ID_SUE_TYPE EnumeratorList ID_SUE_TYPE ';'	{ Fix $ EnumDecl $3 $4 $5 }
+
+EnumeratorList :: { [NonTerm] }
+EnumeratorList
+:	'{' Enumerators '}'					{ reverse $2 }
+|	'{' Enumerators ',' '}'					{ reverse $2 }
+|	'{' Enumerators Comment '}'				{ reverse $2 }  -- TODO(iphydf): Don't throw away the comment.
+|	'{' Enumerators ',' Comment '}'				{ reverse $2 }  -- TODO(iphydf): Don't throw away the comment.
+
+Enumerators :: { [NonTerm] }
+Enumerators
+:	Enumerator						{ [$1] }
+|	Enumerators ',' Enumerator				{ $3 : $1 }
+
+Enumerator :: { NonTerm }
+Enumerator
+:	EnumeratorName						{ Fix $ Enumerator $1 Nothing }
+|	EnumeratorName '=' ConstExpr				{ Fix $ Enumerator $1 (Just $3) }
+|	Comment Enumerator					{ Fix $ Commented $1 $2 }
+
+EnumeratorName :: { Term }
+EnumeratorName
+:	ID_CONST						{ $1 }
+|	ID_SUE_TYPE						{ $1 }
+
+AggregateDecl :: { NonTerm }
+AggregateDecl
+:	AggregateType ';'					{ Fix $ AggregateDecl $1 }
+|	typedef AggregateType ID_SUE_TYPE ';'			{ Fix $ Typedef $2 $3 [] }
+
+AggregateType :: { NonTerm }
+AggregateType
+:	struct ID_SUE_TYPE '{' MemberDeclList '}'		{ Fix $ Struct $2 $4 }
+|	union ID_SUE_TYPE '{' MemberDeclList '}'		{ Fix $ Union $2 $4 }
+
+MemberDeclList :: { [NonTerm] }
+MemberDeclList
+:	MemberDecls						{ reverse $1 }
+
+MemberDecls :: { [NonTerm] }
+MemberDecls
+:	MemberDecl						{ [$1] }
+|	MemberDecls MemberDecl					{ $2 : $1 }
+
+MemberDecl :: { NonTerm }
+MemberDecl
+:	VarDecl ';'						{ Fix $ MemberDecl $1 Nothing }
+|	VarDecl ':' LIT_INTEGER ';'				{ Fix $ MemberDecl $1 (Just $3) }
+|	PreprocIfdef(MemberDecls)				{ $1 }
+|	Comment							{ $1 }
+
+TypedefDecl :: { NonTerm }
+TypedefDecl
+:	typedef QualType(GlobalLeafType) ID_SUE_TYPE DeclSpecArrays ';'	{ Fix $ Typedef $2 $3 $4 }
+|	typedef FunctionPrototype(ID_FUNC_TYPE) ';'		{ Fix $ TypedefFunction $2 }
+|	struct ID_SUE_TYPE ';'					{ Fix $ Typedef (Fix (TyStruct $2)) $2 [] }
+
+QualType(leafType)
+:	bitwise ID_STD_TYPE					{ Fix (TyBitwise (Fix (TyStd $2))) }
+|	force QualType(leafType)				{ Fix (TyForce $2) }
+|	PtrType(leafType)					{ $1 }
+
+PtrType(leafType)
+:	leafType QualMaybe					{ $2 $1 }
+|	const leafType QualMaybe				{ $3 (tyConst $2) }
+|	PtrType(leafType) '*' QualMaybe				{ $3 (tyPointer $1) }
+
+QualList :: { NonTerm -> NonTerm }
+QualList
+:	Qual QualList						{ $1 . $2 }
+|	Qual							{ $1 }
+
+QualMaybe :: { NonTerm -> NonTerm }
+QualMaybe
+:	QualList						{ $1 }
+|								{ id }
+
+Qual :: { NonTerm -> NonTerm }
+Qual
+:	const							{ tyConst }
+|	nonnull							{ tyNonnull }
+|	nullable						{ tyNullable }
+|	owner							{ tyOwner }
+|	'/*!' nonnull '*/'					{ tyNonnull }
+|	'/*!' nullable '*/'					{ tyNullable }
+
+-- | A header's nullability before it can say @_Nullable@: @/*! _Nullable */@.
+CommentNullability :: { Nullability }
+CommentNullability
+:	'/*!' nullable '*/'					{ Nullable }
+|	'/*!' nonnull '*/'					{ Nonnull }
+
+Nullability :: { Nullability }
+Nullability
+:								{ NullabilityUnspecified }
+|	nullable						{ Nullable }
+|	nonnull							{ Nonnull }
+
+GlobalLeafType :: { NonTerm }
+GlobalLeafType
+:	struct ID_SUE_TYPE					{ Fix $ TyStruct $2 }
+|	union ID_SUE_TYPE					{ Fix $ TyUnion $2 }
+|	void							{ Fix $ TyStd $1 }
+|	ID_STD_TYPE						{ Fix $ TyStd $1 }
+|	ID_SUE_TYPE						{ Fix $ TyUserDefined $1 }
+
+LocalLeafType :: { NonTerm }
+LocalLeafType
+:	GlobalLeafType						{ $1 }
+|	ID_FUNC_TYPE						{ Fix $ TyFunc $1 }
+
+FunctionDecl :: { NonTerm }
+FunctionDecl
+:	FunctionDeclarator					{ $1 Global }
+|	static FunctionDeclarator				{ $2 Static }
+|	Attrs FunctionDeclarator				{ $1 $ $2 Global }
+
+Attrs :: { NonTerm -> NonTerm }
+Attrs
+:	GNU_PRINTF '(' LIT_INTEGER ',' LIT_INTEGER ')'		{ Fix . AttrPrintf $3 $5 }
+|	GNU_ALLOC_SIZE '(' LIT_INTEGER ')'			{ Fix . AttrAllocSize [$3] }
+|	GNU_ALLOC_SIZE '(' LIT_INTEGER ',' LIT_INTEGER ')'	{ Fix . AttrAllocSize [$3, $5] }
+
+FunctionDeclarator :: { Scope -> NonTerm }
+FunctionDeclarator
+:	FunctionPrototype(ID_VAR) ';'				{ \s -> Fix $ FunctionDecl s $1 }
+|	FunctionPrototype(ID_VAR) CompoundStmt			{ \s -> Fix $ FunctionDefn s $1 $2 }
+|	CallbackDecl ';'					{ \s -> Fix $ FunctionDecl s $1 }
+
+CallbackDecl :: { NonTerm }
+CallbackDecl
+:	ID_FUNC_TYPE ID_VAR					{ Fix $ CallbackDecl $1 $2 }
+
+FunctionPrototype(id)
+:	QualType(GlobalLeafType) id FunctionParamList		{ Fix $ FunctionPrototype $1 $2 $3 }
+|	ID_FUNC_TYPE '*' QualMaybe id FunctionParamList		{ Fix $ FunctionPrototype ($3 (Fix $ TyPointer $ Fix $ TyFunc $1)) $4 $5 }
+
+FunctionParamList :: { [NonTerm] }
+FunctionParamList
+:	'(' ')'							{ [] }
+|	'(' void ')'						{ [Fix $ TyStd $2] }
+|	'(' FunctionParams ')'					{ reverse $2 }
+|	'(' FunctionParams ',' '...' ')'			{ reverse $ Fix Ellipsis : $2 }
+
+FunctionParams :: { [NonTerm] }
+FunctionParams
+:	FunctionParam						{ [$1] }
+|	FunctionParams ',' FunctionParam			{ $3 : $1 }
+
+FunctionParam :: { NonTerm }
+FunctionParam
+:	VarDecl							{ $1 }
+
+ConstDecl :: { NonTerm }
+ConstDecl
+:	extern QualType(GlobalLeafType) ID_VAR ';'			{ Fix $ ConstDecl $2 $3 }
+|	QualType(GlobalLeafType) ID_VAR '=' InitialiserExpr ';'	{ Fix $ ConstDefn Global $1 $2 $4 }
+|	static QualType(GlobalLeafType) ID_VAR '=' InitialiserExpr ';'	{ Fix $ ConstDefn Static $2 $3 $5 }
+
+{
+type Term = Lexeme Text
+type NonTerm = Node Term
+
+tyPointer, tyConst, tyOwner :: NonTerm -> NonTerm
+tyPointer = Fix . TyPointer
+tyConst = Fix . TyConst
+tyOwner = Fix . TyOwner
+tyNullable = Fix . TyNullable
+tyNonnull = Fix . TyNonnull
+
+lexwrap :: (Lexeme Text -> Alex a) -> Alex a
+lexwrap = (alexMonadScan >>=)
+
+externC
+    :: Term
+    -> Term
+    -> [NonTerm]
+    -> Term
+    -> Alex NonTerm
+externC (L _ _ "__cplusplus") (L _ _ "\"C\"") decls (L _ _ "__cplusplus") =
+    return $ Fix $ ExternC decls
+externC _ lang _ _ =
+    alexError $ show lang
+        <> ": extern \"C\" declaration invalid (did you spell __cplusplus right?)"
+
+macroBodyStmt
+    :: NonTerm
+    -> Term
+    -> Alex NonTerm
+macroBodyStmt decls (L _ _ "0") =
+    return $ Fix $ MacroBodyStmt decls
+macroBodyStmt _ cond =
+    alexError $ show cond
+        <> ": macro do-while body must end in 'while (0)'"
+
+source :: Maybe BS.ByteString
+#ifdef SOURCE
+source = Just $(embedFile SOURCE)
+#else
+source = Nothing
+#endif
+
+preprocessorEnabled :: Bool
+preprocessorEnabled = False
+}
