[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: LPEG S-expression grammar
- From: Sean Conner <sean@...>
- Date: Thu, 10 Aug 2023 18:07:46 -0400
It was thus said that the Great Chris Smith once stated:
> Hi,
>
> Has anyone written an LPEG grammar for parsing S-expressions?
Yes, and very simplistic S-expression grammar is:
local lisp = lpeg.P {
'lisp',
lisp = lpeg.V"atom" + lpeg.V"list",
atom = lpeg.V"space" * lpeg.C(lpeg.R("!'","*~")^1),
list = lpeg.V"space" * lpeg.P'(' * lpeg.Ct((lpeg.V'list' + lpeg.V'atom')^0) * lpeg.P')',
space = lpeg.S" \t\v\r\n"^0
}
And as a test, it will parse
(a b (c d e f) g h i j k (l m))
into the following Lua table:
{
[1] = "a",
[2] = "b",
[3] =
{
[1] = "c",
[2] = "d",
[3] = "e",
[4] = "f",
},
[4] = "g",
[5] = "h",
[6] = "i",
[7] = "j",
[8] = "k",
[9] =
{
[1] = "l",
[2] = "m",
},
}
I'll leave it as an exercise to the reader to support strings and
comments.
-spc