r/tinycode • • Oct 01 '13

Parse Lisp in five lines of code (and it's not written in Lisp)

It's Lua (5.1 or greater) and LPeg (0.12):

lisp = require "re".compile [[
prog    <-       {| list*                        |}
list    <- space {| '(' (atom / list)* space ')' |}
atom    <- space {  [^%s();]+                     }
space   <- (%s / ';' [^%nl]* %nl)*
]]

The resulting Lisp code is stored in a nested Lua table.

5 Upvotes

7 comments sorted by

1

u/gfixler Oct 02 '13

Isn't that really just one, wrapped line of code?

1

u/spc476 Oct 04 '13

The first line is Lua; the others are a form of BNF that LPeg can parse (well, the re submodule of LPeg). Technically, it could all be done on one line, but I went for clarity.

0

u/[deleted] Oct 01 '13

[deleted]

1

u/spc476 Oct 01 '13 edited Oct 01 '13

I know it would be larger using lex and yacc (two other libraries used for parsing).

Also, this would be shorter if I didn't have to parse comments.

0

u/[deleted] Oct 01 '13

[deleted]

5

u/tikhonjelvis Oct 01 '13

At some point, that logic applies to essentially any program; after all, the compiler, garbage collector, runtime system, operating system, standard library and so on are gigantic!

Since this isn't specifically a lisp parser, it's still an interesting program.

0

u/[deleted] Oct 01 '13

[deleted]

1

u/spc476 Oct 04 '13

It's still using regular expressions, which could be considered a library (if it weren't built into the language).

Also, that doesn't support Lisp comments.

1

u/fullouterjoin Nov 28 '13

Since when did /r/tinycode start counting the LOC in dependencies ? I think of it more as the beautiful fucking snow cone on the top of the tower of abstraction.

Esp if one is calling into a library with good semantic separation. How is regex different than lpeg?

13

u/klusark Oct 01 '13
simulate_the_universe();