lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


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