my blog lives here now
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

883 lines
32 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. ---
  2. title: "Parsing Layout, or: Haskell's Syntax is a Mess"
  3. date: September 3rd, 2021
  4. abbreviations:
  5. sparkles: ✨
  6. ---
  7. Hello! Today we're going to talk about something I'm actually _good_ at, for a change: writing compilers. Specifically, I'm going to demonstrate how to wrangle [Alex] and [Happy] to implement a parser for a simple language with the same indentation sensitive parsing behaviour as Haskell, the _layout rule_.
  8. [Alex]: https://www.haskell.org/alex/
  9. [Happy]: https://www.haskell.org/happy/
  10. Alex and Happy are incredibly important parts of the Haskell ecosystem. If you're a Haskeller, you use a program using an Alex lexer and a Happy parser _every single day_ - every single working day, at least - GHC! Despite this fundamental importance, Alex and Happy are... _sparsely_ documented, to say the least. Hopefully this post can serve as an example of how to do something non-trivial using them.
  11. However! While I'm going to talk about Alex and Happy here, it would be entirely possible to write a layout parser using Alex and whatever flavour of Parsec is popular this week, as long as your combinators are expressed on top of a monad transformer. It's also entirely possible to write a layout parser without Alex at all, but that's beyond my abilities. I am a mere mortal, after all.
  12. Get ready to read the word "layout" a lot. Layout layout layout. How's your semantic satiation going? Should I say layout a couple more times?
  13. # The Offside Rule
  14. So, how does Haskell layout work? A small subset of tokens (`where`, `of`, `let`, `do`[^1]), called _layout keywords_, are followed by a _laid out block_ (my terminology). The happiest (hah) case is where one of these keywords is followed by a `{` token. In this case, layout parsing doesn't happen at all!
  15. [^1]: GHC extends this set to also contain the "token" `\case`. However, `LambdaCase` isn't a single token! The &sparkles; correct &sparkles; specification is that `case` is a layout keyword if the preceding token is `\`.
  16. ```{.haskell .notag}
  17. main = do { putStrLn
  18. "foo"
  19. ; putStrLn "bar"
  20. ; putStrLn "quux" }
  21. ```
  22. This _abomination_ is perfectly valid Haskell code, since layout is disabled in a context that was started with a `{`. Great success though, since this is a very simple thing to support in a parser. The unhappy case is when we actually have to do layout parsing. In that case, the starting column of the token immediately following the layout token becomes the _reference column_ (again my terminology), we emit a (virtual) opening brace, and the **offside rule** applies.
  23. The offside rule says that a player must have at least two opposing players, counting the goalkeep- No no, that's not right. Give me a second. Ah! Yes. The offside rule governs automatic insertion of (virtual) semicolons and closing braces. When we encounter the first token of a new line, we are burdened to compare its starting column with the reference:
  24. - If it's on the same column as the reference column, we emit a semicolon. This is a new statement/declaration/case.
  25. <div class=mathpar>
  26. ```haskell
  27. do foo
  28. bar
  29. -- ^ same column, insert ; before.
  30. ```
  31. ```haskell
  32. do
  33. foo
  34. bar
  35. -- ^ same column, insert ; before.
  36. -- yes, three spaces
  37. ```
  38. </div>
  39. The two token streams above have the same prefix as `do { foo; bar }`{.haskell}.
  40. - If it's further indented than the reference column, we.. do nothing! Just go back to normal lexing. Tokens indented to the right of the reference column are interpreted as continuing the statement in the previous line. That's why you can do this:
  41. ```haskell
  42. do
  43. putStrLn $
  44. wavy
  45. function
  46. application
  47. please
  48. don't
  49. though
  50. ```
  51. _All_ of those tokens are (in addition to being the first token in a line) indented further than `putStrLn`, which is our reference column. This block has no semicolons at all!
  52. - If it's less indented than the reference column, we emit a virtual closing `}` (to end the block) and _**apply the rule again**_. This last bit is crucial: it says a single token can end all of the layout contexts it's leaving. For instance:
  53. ```haskell
  54. foo = do a -- context 1
  55. do b -- context 2
  56. do c -- context 3
  57. do d -- context 4
  58. e
  59. bar = 123
  60. ```
  61. Assuming there was a layout context at the first column, i.e., we're in a module, then the token `bar` will be responsible for closing 4 whole layout contexts:
  62. - It's to the left of `d`, so it closes context 4;
  63. - It's to the left of `c`, so it closes context 3;
  64. - It's to the left of `b`, so it closes context 2;
  65. - It's to the left of `a`, so it closes context 1.
  66. With all the semicolons we have a right to, the code above is this:
  67. ``` haskell
  68. ; foo = do { a -- context 1
  69. ; do { b -- context 2
  70. ; do { c -- context 3
  71. ; do { d -- context 4
  72. ; e
  73. }
  74. }
  75. }
  76. }
  77. ; bar = 123
  78. ```
  79. Why do we have semicolons before `foo` and `bar`? Why, because they're in the same column as the reference token, which was presumably an import or something.
  80. # Laid-out blocks
  81. With that, the parser productions for laid out blocks should be clear - or, at least, easily approximable. Right?
  82. Wrong.
  83. You might think the production for `do` blocks is something like the following, and you'd be forgiven for doing so. It's clean, it's reasonable, it's not _actually_ Happy syntax, but it's a close enough approximation. Except that it's way incorrect!
  84. ```
  85. expr
  86. : ...
  87. | 'do' '{' statement ';' ... '}' { ... }
  88. | 'do' VOpen statement VSemi ... VClose { ... }
  89. ```
  90. Well, for `do` you might be able to get away with that. But consider the laid-out code on the left, and what the lexer naïvely produces for us on the right.
  91. <div class=mathpar>
  92. ```haskell
  93. foo = let x = 1 in x
  94. ```
  95. ```haskell
  96. ; foo = let { x = 1 in x
  97. ```
  98. </div>
  99. You see it, right? Since no token was on a column before that of the token `x` (the reference token for the layout context started by `let`), no close brace was emitted before `in`. Woe is us! However, the Haskell report has a way around this. They write it cryptically, like this:
  100. >
  101. ```
  102. ...
  103. L (t : ts) (m : ms) = } : (L (t : ts) ms) if m ≠ 0 and parse-error(t)
  104. ...
  105. ```
  106. > The side condition `parse-error(t)` is to be interpreted as follows: if the tokens generated so far by `L` together with the next token `t` represent an invalid prefix of the Haskell grammar, and the tokens generated so far by `L` followed by the token `}` represent a valid prefix of the Haskell grammar, then `parse-error(t)` is true.
  107. >
  108. > The test `m ≠ 0` checks that an implicitly-added closing brace would match an implicit open brace.
  109. I'll translate, since I'm fluent in standardese: Parse errors are allowed to terminate layout blocks, as long as no explicit `{` was given. This is the entire reason that Happy has an `error` token, which "matches parse errors"! For further reference, `L` is a function `[Token] -> [Int] -> [Token]`{.haskell} which is responsible for inserting virtual `{`, `;` and `}` tokens. The `[Int]`{.haskell} argument is the stack of reference columns.
  110. So a better approximation of the grammar is:
  111. ```
  112. expr
  113. : ...
  114. | 'do' '{' statement ';' ... '}' { ... }
  115. | 'do' VOpen statement VSemi ... LClose { ... }
  116. LClose
  117. : VClose {- lexer inserted '}' -}
  118. | error {- parse error generated '}' -}
  119. ```
  120. We have unfortunately introduced some dragons, since the parser now needs to finesse the lexer state, meaning they must be interleaved _explicitly_, instead of being run in sequence (using a lazy list of tokens or similar). They must be in the same Monad.
  121. So. How do we implement this?
  122. # How we implement this
  123. ## Preliminaries
  124. To start with, we create a new Haskell project. I'd normally gloss over this, but in this case, there are adjustments to the Cabal file that must be made to inform our build of the dependencies on `alex` and `happy`. I use Stack; You can use whatever.
  125. ```bash
  126. % stack new layout simple
  127. ```
  128. To our Cabal file, we add a `build-tool-depends` on Alex and Happy. Cabal (the build system) comes with built-in rules to detect `.x` and `.y` files and compile these as Ale**x** and Happ**y** respectively.
  129. ```{.haskell tag="layout.cabal"}
  130. build-tool-depends: alex:alex >= 3.2.4 && < 4.0
  131. , happy:happy >= 1.19.12 && < 2.0
  132. build-depends: base >= 4.7 && < 5
  133. , array >= 0.5 && < 0.6
  134. ```
  135. This has been the recommended way of depending on build tools since Cabal 2. The syntax of build-tool-depends entries is `package:executable [version bound]`, where the version bound is optional but good style. With this, running `stack build` (and/or `cabal build`) will automatically compile parser and lexer specifications **listed in your `other-modules` field** to Haskell files.
  136. Alex generated code has a dependency on the `array` package.
  137. ## What are we parsing
  138. For the language we're parsing, I've chosen to go with a representative subset of Haskell's grammar: Variables, lambda expressions, `let` expressions, and application. For the top-level, we'll support function definitions, where the lhs must be a sequence of variables, and the rhs can optionally have a `where` clause.
  139. ```{ .haskell tag="src/Syntax.hs" }
  140. module Syntax (Expr(..), Decl(..), Program) where
  141. data Expr
  142. = Var String
  143. | App Expr Expr
  144. | Lam String Expr
  145. | Let [Decl] Expr
  146. deriving (Eq, Show)
  147. data Decl
  148. = Decl { declName :: String
  149. , declRhs :: Expr
  150. , declWhere :: Maybe [Decl]
  151. }
  152. deriving (Eq, Show)
  153. type Program = [Decl]
  154. ```
  155. For simplicity, identifiers will be ASCII only. We're also using strings and lists everywhere, instead of more appropriate data structures (`Text` and `Seq`), for clarity. Don't forget to add the `Syntax` module to the `other-modules` field in `layout.cabal`.
  156. ## The Lexer
  157. Before we can parse, we must lex. But before we can lex, we must know the type of tokens. We create a separate Haskell module to contain the definition of the token type and `Lexer` monad. This is mostly done because HIE does not support Alex and Happy, and I've become dependent on HIE for writing correct code fast.
  158. We'll call this new module `Lexer.Support`, just because. Our type of tokens must contain our keywords, but also punctuation (`=`, `{`, `;`, `}`, `\\`, `->`) and _virtual_ punctuation (tokens inserted by layout). We declare:
  159. ```{.haskell tag="src/Lexer/Support.hs"}
  160. module Lexer.Support where
  161. data Token
  162. = TkIdent String -- identifiers
  163. -- Keywords
  164. | TkLet | TkIn | TkWhere
  165. -- Punctuation
  166. | TkEqual | TkOpen | TkSemi | TkClose
  167. | TkLParen | TkRParen
  168. | TkBackslash | TkArrow
  169. -- Layout punctuation
  170. | TkVOpen | TkVSemi | TkVClose
  171. -- End of file
  172. | TkEOF
  173. deriving (Eq, Show)
  174. ```
  175. ### An Alex file
  176. Alex modules always start with a Haskell header, between braces. In general, braces in Alex code represent a bit of Haskell we're inserting: The header, lexer actions, and the footer.
  177. ```{.alex tag="src/Lexer.x"}
  178. {
  179. module Lexer where
  180. import Lexer.Support
  181. }
  182. %encoding "latin1"
  183. ```
  184. After the header, we can also include magical incantations: `%wrapper` will tell Alex to include a support code template with our lexer, and `%encoding` will tell it whether to work with bytes or with Unicode. _Nobody uses the Unicode support_, not even GHC: The community wisdom is to trick Alex into reading Unicode by compressing Unicode classes down into high byte characters. Yeah, **yikes**.
  185. Our file can then have some macro definitions. Macros with the `$` sigil are character classes, and `@` macros are complete regular expressions.
  186. ```{.alex tag="src/Lexer.x"}
  187. $lower = [ a-z ]
  188. $upper = [ A-Z ]
  189. @ident = $lower [ $lower $upper _ ' ]*
  190. ```
  191. And, finally, comes the actual lexer specification. We include the final magic word `:-` on a line by itself, and then list a bunch of lexing rules. Lexing rules are specified by:
  192. - A _startcode_, which names a _state_. These are written `<ident>` or `<0>`, where `<0>` is taken to be the "default" startcode. Rules are by default enabled in all states, and can be enabled in many;
  193. - A _left context_, which is a regular expression matched against the character immediately preceding the token;
  194. - A _regular expression_, describing the actual token;
  195. - A _right context_, which can be a regular expression to be matched after the token or a fragment of Haskell code, called a _predicate_. If the predicate is present, it must have the following type:
  196. ```{.haskell .notag}
  197. { ... } :: user -- predicate state
  198. -> AlexInput -- input stream before the token
  199. -> Int -- length of the token
  200. -> AlexInput -- input stream after the token
  201. -> Bool -- True <=> accept the token
  202. ```
  203. - An _action_, which can be `;`, causing the lexer to skip the token, or some Haskell code, which can be any expression, as long as every action has the same type.
  204. Here's a couple rules so we can get started. Don't worry - `emit` is a secret tool that will help us later.
  205. ```{.alex tag="src/Lexer.x"}
  206. :-
  207. [\ \t]+ ;
  208. <0> @ident { emit TkIdent }
  209. ```
  210. Alright, let's compile this code and see what we get! Oh, we get some type errors. Okay. Let's see what's up:
  211. ```
  212. Not in scope: type constructor or class ‘AlexInput’
  213. |
  214. 264 | | AlexLastSkip !AlexInput !Int
  215. | ^^^^^^^^^
  216. ```
  217. ### Making our own wrapper
  218. Right. That's probably related to that `%wrapper` thing I told you about. You'd be correct: The wrappers solve this problem by including a handful of common patterns pre-made, but we can very well supply our own! The interface to an Alex-generated lexer is documented [here](https://www.haskell.org/alex/doc/html/api.html), but we're interested in §5.1 specifically. We have to provide the following definitions:
  219. ```{.haskell .notag}
  220. type AlexInput
  221. alexGetByte :: AlexInput -> Maybe (Word8, AlexInput)
  222. alexInputPrevChar :: AlexInput -> Char
  223. ```
  224. And we get in return a lexing function, whose type and interface I'm not going to copy-paste here. The `alexGetByte` function is called by the lexer whenever it wants input, so that's the natural place to do position handling, which, yes, we have to do ourselves. Let's fill in these definitions in the `Lexer.Support` module.
  225. Here's an okay choice for `AlexInput`:
  226. ```{.haskell tag="src/Lexer/Support.hs"}
  227. data AlexInput
  228. = Input { inpLine :: {-# UNPACK #-} !Int
  229. , inpColumn :: {-# UNPACK #-} !Int
  230. , inpLast :: {-# UNPACK #-} !Char
  231. , inpStream :: String
  232. }
  233. deriving (Eq, Show)
  234. ```
  235. We can immediately take `alexInputPrevChar = inpLast` as the definition of that function and be done with it, which is fantastic. `alexGetByte`, on the other hand, is a bit more involved, since it needs to update the position based on what character was read. The column _must_ be set properly, otherwise layout won't work! The line counter is less important, though.
  236. ```haskell
  237. alexGetByte :: AlexInput -> Maybe (Word8, AlexInput)
  238. alexGetByte [email protected]{inpStream = str} = advance <$> uncons str where
  239. advance ('\n', rest) =
  240. ( fromIntegral (ord '\n')
  241. , Input { inpLine = inpLine inp + 1
  242. , inpColumn = 1
  243. , inpLast = '\n'
  244. , inpStream = rest }
  245. )
  246. advance (c, rest) =
  247. ( fromIntegral (ord c)
  248. , Input { inpLine = inpLine inp
  249. , inpColumn = inpColumn inp + 1
  250. , inpLast = c
  251. , inpStream = rest }
  252. )
  253. ```
  254. Now, our lexer has a lot of state. We have the start codes, which form a stack. We have the stack of reference columns, and we have the input. Let's use a State monad to keep track of this, with an `Either String` base to keep track of errors.
  255. ```{.haskell tag="src/Lexer/Support.hs"}
  256. newtype Lexer a = Lexer { _getLexer :: StateT LexerState (Either String) a }
  257. deriving
  258. ( Functor
  259. , Applicative
  260. , Monad
  261. , MonadState LexerState
  262. , MonadError String
  263. )
  264. data Layout = ExplicitLayout | LayoutColumn Int
  265. deriving (Eq, Show, Ord)
  266. data LexerState
  267. = LS { lexerInput :: {-# UNPACK #-} !AlexInput
  268. , lexerStartCodes :: {-# UNPACK #-} !(NonEmpty Int)
  269. , lexerLayout :: [Layout]
  270. }
  271. deriving (Eq, Show)
  272. initState :: String -> LexerState
  273. initState str = LS { lexerInput = Input 0 1 '\n' str
  274. , lexerStartCodes = 0 :| []
  275. , lexerLayout = []
  276. }
  277. runLexer :: Lexer a -> String -> Either String a
  278. runLexer act s = fst <$> runStateT (_getLexer act) (initState s)
  279. ```
  280. <details>
  281. <summary> I'll spare you the boring stack manipulation stuff by putting it in one of these \<details\> elements you can expand: </summary>
  282. ```haskell
  283. startCode :: Lexer Int
  284. startCode = gets (NE.head . lexerStartCodes)
  285. pushStartCode :: Int -> Lexer ()
  286. pushStartCode i = modify' $ \st ->
  287. st { lexerStartCodes = NE.cons i (lexerStartCodes st )
  288. }
  289. -- If there is no start code to go back to, we go back to the 0 start code.
  290. popStartCode :: Lexer ()
  291. popStartCode = modify' $ \st ->
  292. st { lexerStartCodes =
  293. case lexerStartCodes st of
  294. _ :| [] -> 0 :| []
  295. _ :| (x:xs) -> x :| xs
  296. }
  297. layout :: Lexer (Maybe Layout)
  298. layout = gets (fmap fst . uncons . lexerLayout)
  299. pushLayout :: Layout -> Lexer ()
  300. pushLayout i = modify' $ \st ->
  301. st { lexerLayout = i:lexerLayout st }
  302. popLayout :: Lexer ()
  303. popLayout = modify' $ \st ->
  304. st { lexerLayout =
  305. case lexerLayout st of
  306. _:xs -> xs
  307. [] -> []
  308. }
  309. ```
  310. </details>
  311. ### Putting it all together
  312. It's up to us to specify what an action is - remember, the action is the code block following a lexer rule - so we'll go with `String -> Lexer Token`. The `String` argument is the lexed token, and we'll have to take this slice ourselves when we implement the interface between the Alex lexer and our `Lexer` monad. The `emit` action is simple, and we'll throw in `token` for no extra cost:
  313. ```haskell
  314. emit :: (String -> Token) -> String -> Lexer Token
  315. emit = (pure .)
  316. token :: Token -> String -> Lexer Token
  317. token = const . pure
  318. ```
  319. Back to our `Lexer.x`, we have to write the function to interpret Alex lexer results as `Lexer` monad actions. It goes like this:
  320. ```{.haskell tag="src/Lexer.x, add at the bottom" }
  321. {
  322. handleEOF = do
  323. -- TODO: handle layout
  324. pure TkEOF
  325. scan :: Lexer Token
  326. scan = do
  327. [email protected](Input _ _ _ string) <- gets lexerInput
  328. startcode <- startCode
  329. case alexScan input startcode of
  330. AlexEOF -> handleEOF
  331. AlexError (Input _ _ _ inp) ->
  332. throwError $ "Lexical error: " ++ show (head inp)
  333. AlexSkip input' _ -> do
  334. modify' $ \s -> s { lexerInput = input' }
  335. scan
  336. AlexToken input' tokl action -> do
  337. modify' $ \s -> s { lexerInput = input' }
  338. action (take tokl string)
  339. }
  340. ```
  341. Now we can do a `stack build` to compile the lexer and `stack repl` to play around with it!
  342. ```{.haskell tag="Did you know my Myers-Briggs type is GHCI?"}
  343. λ runLexer scan "abc"
  344. Right (TkIdent "abc")
  345. λ runLexer scan " abc"
  346. Right (TkIdent "abc")
  347. λ runLexer scan " {"
  348. Left "Lexical error: '{'"
  349. ```
  350. Okay, yeah, let's fill out our lexer a bit more.
  351. ```{.alex tag="src/Lexer.x, lexing rules"}
  352. <0> in { token TkIn }
  353. <0> \\ { token TkBackslash }
  354. <0> "->" { token TkArrow }
  355. <0> \= { token TkEqual }
  356. <0> \( { token TkLParen }
  357. <0> \) { token TkRParen }
  358. <0> \{ { token TkOpen }
  359. <0> \} { token TkClose }
  360. ```
  361. That's all of the easy rules we can do - All of the others interact with the layout state, which we'll see how to do in the paragraph immediately following this one. I'm writing a bit of padding here so you can take a breather and prepare yourself for the lexer states that we'll deal with now. But, please believe me when I say we're doing this lexer madness so our parser can be sane.
  362. ### Actually Doing Layout (trademark pending)
  363. We'll need two rules for the layout keywords. Alex rules are matched in order, top-to-bottom, so **make sure your keywords are before your identifier rule**.
  364. ```{.alex tag="src/Lexer.x"}
  365. <0> let { layoutKw TkLet }
  366. <0> where { layoutKw TkWhere }
  367. ```
  368. And the action for layout keywords, which has to go in the lexer since it'll refer to a startcode. Alex automatically generates definitions for all the startcodes we mention.
  369. ```haskell
  370. layoutKw t _ = do
  371. pushStartCode layout
  372. pure t
  373. ```
  374. The interesting rules for handling layout are in the `layout` startcode, which we'll declare as a block to keep things a bit tidier. When in this startcode, we need to handle either an explicitly laid-out block (that is, `{`), or the start of a layout context: The indentation of the next token determines where we start.
  375. ```{.alex tag="src/Lexer.x"}
  376. <layout> {
  377. -- Skip comments and whitespace
  378. "--" .* \n ;
  379. \n ;
  380. \{ { openBrace }
  381. () { startLayout }
  382. }
  383. ```
  384. The `openBrace` and `startLayout` lexer actions are also simple:
  385. ```haskell
  386. openBrace _ = do
  387. popStartCode
  388. pushLayout ExplicitLayout
  389. pure TkOpen
  390. startLayout _ = do
  391. popStartCode
  392. reference <- Lexer.Support.layout
  393. col <- gets (inpColumn . lexerInput)
  394. if Just (LayoutColumn col) <= reference
  395. then pushStartCode empty_layout
  396. else pushLayout (LayoutColumn col)
  397. pure TkVOpen
  398. ```
  399. Here's another rule. suppose we have:
  400. ```haskell
  401. foo = bar where
  402. spam = ham
  403. ```
  404. If we just apply the rule that the next token after a layout keyword determines the column for the layout context, then we're starting another layout context at column 1! that's definitely not what we want.
  405. The fix: A new layout context only starts if the first token is to the right of the previous layout context. That is: a block only starts if it's on the same column as the layout context, or indented further.
  406. But! We still need to emit a closing `}` for the one that `openBrace` generated! This is the sole function of the `empty_layout` startcode:
  407. <div class=mathpar>
  408. ```
  409. <empty_layout> () { emptyLayout }
  410. ```
  411. ```haskell
  412. emptyLayout _ = do
  413. popStartCode
  414. pushStartCode newline
  415. pure TkVClose
  416. ```
  417. </div>
  418. We're on the home stretch. I mentioned another startcode - `newline`. It's where we do the offside rule, and our lexer will finally be complete.
  419. ### The Offside Rule, again
  420. The `newline` state is entered in two places: After an empty layout block (as a short-circuit), and after, well, a new line character. Comments also count as newline characters, by the way.
  421. ```{.alex tag="src/Lexer.x, rule"}
  422. <0> "--" .* \n { \_ -> pushStartCode newline *> scan }
  423. <0> \n { \_ -> pushStartCode newline *> scan }
  424. ```
  425. In the `newline` state, we again scan for a token, and call for an action, just like for `layout`. The difference is only in the action: Whenever _any_ token is encountered, we perform the offside rule, _if_ we're in a layout context that mandates it.
  426. ```{.alex tag="src/Lexer.x, rule"}
  427. <newline> {
  428. \n ;
  429. "--" .* \n ;
  430. () { offsideRule }
  431. }
  432. ```
  433. The code for the offside rule is a bit hairy, but follows from the spec:
  434. ```{.haskell tag="src/Lexer.x, epilogue code"}
  435. offsideRule _ = do
  436. context <- Lexer.Support.layout
  437. col <- gets (inpColumn . lexerInput)
  438. let continue = popStartCode *> scan
  439. case context of
  440. Just (LayoutColumn col') -> do
  441. case col `compare` col' of
  442. EQ -> do
  443. popStartCode
  444. pure TkVSemi
  445. GT -> continue
  446. LT -> do
  447. popLayout
  448. pure TkVClose
  449. _ -> continue
  450. ```
  451. Check out how cleanly those three cases map to the rules I described [way back when](#h0). We `compare`{.haskell} the current column with the reference, and:
  452. - If it's `EQ`, add a semicolon.
  453. - If it's `GT`, continue lexing.
  454. - If it's `LT`, close as many layout contexts as possible.
  455. <details>
  456. <summary>
  457. **Exercise**: In the `handleEOF` action, close all the pending layout contexts. As a hint, the easiest way to emit a token that doesn't is using a startcode and a lexer action. Figuring out when we've run out is part of the challenge :)
  458. </summary>
  459. The rule:
  460. ```{.alex tag="src/Lexer.x, rule"}
  461. <eof> () { doEOF }
  462. ```
  463. The action:
  464. ```{.haskell tag="src/Lexer.x, epilogue code"}
  465. handleEOF = pushStartCode eof *> scan
  466. doEOF _ = do
  467. t <- Lexer.Support.layout
  468. case t of
  469. Nothing -> do
  470. popStartCode
  471. pure TkEOF
  472. _ -> do
  473. popLayout
  474. pure TkVClose
  475. ```
  476. </details>
  477. We can write a `Lexer` action (not a lexer action!) to lex and `Debug.Trace.trace`{.haskell} - sue me - as many tokens as the lexer wants to give us, until an EOF is reached:
  478. ```haskell
  479. lexAll :: Lexer ()
  480. lexAll = do
  481. tok <- scan
  482. case tok of
  483. TkEOF -> pure ()
  484. x -> do
  485. traceM (show x)
  486. lexAll
  487. ```
  488. Now we can actually lex some Haskell code! Well, not much of it. Forget numbers, strings, and most keywords, but we _can_ lex this:
  489. <div class="mathpar">
  490. ```haskell
  491. foo = let
  492. x = let
  493. y = z
  494. in y
  495. in x
  496. ```
  497. ```haskell
  498. TkIdent "foo"
  499. TkEqual
  500. TkLet
  501. TkVOpen
  502. TkIdent "x"
  503. TkEqual
  504. TkLet
  505. TkVOpen
  506. TkIdent "y"
  507. TkEqual
  508. TkIdent "z"
  509. TkVSemi
  510. TkIn
  511. TkIdent "y"
  512. TkVClose
  513. TkVClose
  514. TkIn
  515. TkIdent "x"
  516. ```
  517. </div>
  518. That is, that code is lexed as if it had been written:
  519. ```{.haskell tag="Hmm..."}
  520. foo = let {
  521. x = let {
  522. y = z
  523. ; in y
  524. }} in x
  525. ```
  526. That's... Yeah. Hmm. That's _not right_. What are we forgetting? Ah, who am I kidding, you've guessed this bit. I even said it myself!
  527. > Parse errors are allowed to terminate layout blocks.
  528. We don't have a parser to get errors from, so our layout blocks are terminating too late. Let's write a parser!
  529. ## The Parser
  530. Happy is, fortunately, less picky about how to generate code. Instead of appealing to some magic symbols that it just hopes really hard are in scope, Happy asks us how we want it to interface with the lexer. We'll do it &sparkles; Monadically &sparkles;, of course.
  531. Happy files start the same way as Alex files: A Haskell code block, between braces, and some magic words. You can look up what the magic words do in the documentation, or you can guess - I'm just gonna include all the header here:
  532. ```{.happy tag="src/Parser.y"}
  533. {
  534. module Parser where
  535. import Control.Monad.Error
  536. import Lexer.Support
  537. }
  538. %name parseExpr Expr
  539. %tokentype { Token }
  540. %monad { Lexer }
  541. %lexer { lexer } { TkEOF }
  542. %errorhandlertype explist
  543. %error { parseError }
  544. ```
  545. After these magic incantations (by the way, if you can't find the docs for errorhandlertype, that's because the docs you're looking at are out of date. See [here](https://monlih.github.io/happy-docs/)), we list our tokens in the `%token` directive. In the braces we write Haskell - not an expression, but a pattern.
  546. ```{.happy tag="src/Parser.y, after the directives"}
  547. %token
  548. VAR { TkIdent $$ }
  549. 'let' { TkLet }
  550. 'in' { TkIn }
  551. 'where' { TkWhere }
  552. '=' { TkEqual }
  553. '{' { TkOpen }
  554. ';' { TkSemi }
  555. '}' { TkClose }
  556. '\\' { TkBackslash }
  557. '->' { TkArrow }
  558. '(' { TkLParen }
  559. ')' { TkRParen }
  560. OPEN { TkVOpen }
  561. SEMI { TkVSemi }
  562. CLOSE { TkVClose }
  563. %%
  564. ```
  565. The special `$$` pattern says that if we use a `VAR` token in a production, its value should be the string contained in the token, rather than the token itself. We write productions after the `%%`, and they have this general syntax:
  566. ```happy
  567. Production :: { Type }
  568. : rule1 { code1 }
  569. | rule2 { code2 }
  570. | ...
  571. ```
  572. For starters, we have these productions. You can see that in the code associated with a rule, we can refer to the tokens parsed using `$1, $2, $3, ...`.
  573. ```{.happy tag="src/Parser.y, after the %%"}
  574. Atom :: { Expr }
  575. : VAR { Var $1 }
  576. | '(' Expr ')' { $2 }
  577. Expr :: { Expr }
  578. : '\\' VAR '->' Expr { Lam $2 $4 }
  579. | FuncExpr { $1 }
  580. FuncExpr :: { Expr }
  581. : FuncExpr Atom { App $1 $2 }
  582. | Atom { $1 }
  583. ```
  584. In the epilogue, we need to define two functions, since I mentioned them way up there in the directives. The `lexer` function is a continuation-passing style function that needs to call `cont` with the next token from the lexer. The `parseError` function is how we should deal with parser errors.
  585. ```{.happy tag="src/Parser.y, on the very bottom"}
  586. {
  587. lexer cont = scan >>= cont
  588. parseError = throwError . show
  589. }
  590. ```
  591. By using the `%name` directive we can export a parser production as an action in the `Lexer` monad (since that's what we told Happy to use). Combining that with our `runLexer`, we can parse some expressions, yay!
  592. ```haskell
  593. λ runLexer parseExpr "(\\x -> x) (\\y -> y)"
  594. Right (App (Lam "x" (Var "x")) (Lam "y" (Var "y")))
  595. ```
  596. ### Laid-out productions
  597. Now we'll introduce some productions for parsing laid-out lists of declarations, then we'll circle back and finish with the parser for declarations itself.
  598. ```{.happy tag="src/Parser.y, add wherever"}
  599. DeclBlock :: { [Decl] }
  600. : '{' DeclListSemi '}' { $2 }
  601. | OPEN DeclListSEMI Close { $2 }
  602. DeclListSemi :: { [Decl] }
  603. : Decl ';' DeclListSemi { $1:$3 }
  604. | Decl { [$1] }
  605. | {- empty -} { [] }
  606. DeclListSEMI :: { [Decl] }
  607. : Decl SEMI DeclListSemi { $1:$3 }
  608. | Decl { [$1] }
  609. | {- empty -} { [] }
  610. ```
  611. That is, a block of declarations is either surrounded by `{ ... }` or by `OPEN ... Close`. But what's `Close`? That's right, you've guessed this bit too:
  612. ```{.happy tag="src/Parser.y, add wherever"}
  613. Close
  614. : CLOSE { () }
  615. | error {% popLayout }
  616. ```
  617. Say it louder for the folks in the cheap seats - Parse! Errors! Can! End! Layout! Blocks! Isn't that just magical?
  618. Now we can write a production for `let` (in `Expr`):
  619. ```{.happy tag="src/Parser.y, add to Expr"}
  620. | 'let' DeclBlock 'in' Expr { Let $2 $4 }
  621. ```
  622. And one for declarations:
  623. ```{.happy tag="src/Parser.y, add wherever"}
  624. Decl
  625. : VAR '=' Expr { Decl $1 $3 Nothing }
  626. | VAR '=' Expr 'where' DeclBlock { Decl $1 $3 (Just $5) }
  627. ```
  628. Add a name directive for `Decl` and..
  629. ```{.happy tag="src/Parser.y, add to the directives"}
  630. %name parseDecl Decl
  631. ```
  632. We're done!
  633. # No, seriously, that's it.
  634. Yeah, 3000 words is all it takes to implement a parser for Haskell layout. Running this on the example where the lexer dropped the ball from earlier, we can see that the parser has correctly inserted all the missing `}`s in the right place because of the `Close` production, and the AST we get is what we expect:
  635. ```haskell
  636. λ runLexer parseDecl <$> readFile "that-code-from-before.hs"
  637. Right
  638. (Decl { declName = "foo"
  639. , declRhs =
  640. Let [ Decl { declName = "x"
  641. , declRhs =
  642. Let
  643. [ Decl { declName = "y", declRhs = Var "z"
  644. , declWhere = Nothing} ]
  645. (Var "y")
  646. , declWhere = Nothing
  647. }
  648. ]
  649. (Var "x")
  650. , declWhere = Nothing
  651. })
  652. ```
  653. I've thrown the code from this post up in an organised manner on [my Gitea](https://git.amelia.how/amelia/layout-parser/). The lexer worked out to be 130 lines, and the parser - just 81.
  654. Here's why I favour this approach:
  655. - It's maintainable. Apart from the rendezvous in `Close`, the lexer and the parser are completely independent. They're also entirely declarative - Reading the lexer rules tells you exactly what the lexer does, without having to drop down to how the actions are implemented.
  656. - It cleanly extends to supporting ASTs with annotations - you'd change our current `Token`{.haskell} type to a `TokenClass`{.haskell} type, and a `Token` would be finished using the line and column from the lexer state. Annotating the AST with these positions can be done by projecting from `$N` in the Happy rules.
  657. - It's performant. Obviously the implementation here, using `String`, is not, but by changing how the `AlexInput` type behaves internally, we can optimise by using e.g. a lazy ByteString, a lazy Text, or some other kind of crazy performant stream type. I don't think anyone's ever complained about parsing being their bottleneck with GHC.
  658. - It's popular! The code implemented here is a simplification (wild simplification) of the approach used in GHC and Agda.
  659. Thank you for reading this post. I have no idea what I'm going to write about next!