[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: [LPeg] How can I signal parsing errors with LPeg?
- From: "Soni L." <fakedme@...>
- Date: Fri, 29 Jul 2016 19:56:56 -0300
As seen in http://stackoverflow.com/q/38664815/3691554
----
I'm writing an LPeg-based parser. How can I make it so a parsing error
returns `nil, errmsg`?
I know I can use `error()`, but as far as I know that creates a normal
error, not `nil, errmsg`.
The code is [pretty
long](https://bitbucket.org/SoniEx2/mdxml/src/ed38151d8e395134c39c0abaeda84ebfbc5ae278/mdxml.lua),
but the relevant part is this:
local eof = lpeg.P(-1)
local nl = (lpeg.P "\r")^-1 * lpeg.P "\n" + lpeg.P "\\n" + eof --
\r for winblows compat
local nlnoeof = (lpeg.P "\r")^-1 * lpeg.P "\n" + lpeg.P "\\n"
local ws = lpeg.S(" \t")
local inlineComment = lpeg.P("`") * (1 - (lpeg.S("`") + nl * nl)) ^
0 * lpeg.P("`")
local wsc = ws + inlineComment -- comments count as whitespace
local backslashEscaped
= lpeg.P("\\ ") / " " -- escaped spaces
+ lpeg.P("\\\\") / "\\" -- escaped escape character
+ lpeg.P("\\#") / "#"
+ lpeg.P("\\>") / ">"
+ lpeg.P("\\`") / "`"
+ lpeg.P("\\n") -- \\n newlines count as backslash escaped
+ lpeg.P("\\") * lpeg.P(function(_, i)
error("Unknown backslash escape at position " .. i) -- this
error() is what I wanna get rid of.
end)
local Line = lpeg.C((wsc + (backslashEscaped + 1 - nl))^0) /
function(x) return x end * nl * lpeg.Cp()
local Data = lpeg.S(" \t")^0 * lpeg.Cs((ws / " " + inlineComment /
"" + backslashEscaped + 1 - (lpeg.S(" \t")^0 * nl))^0) * lpeg.S(" \t")^0
* nl
----
`Line` and `Data` are the things that when `:match()`ed should return
`nil, errmsg` on parsing error. Note that only `Line` decides whether a
line is valid or not, so that's where parsing errors happen. `Data` only
extracts the data from a (valid) line.
--
Disclaimer: these emails may be made public at any given time, with or without reason. If you don't agree with this, DO NOT REPLY.