diff options
Diffstat (limited to 'examples')
| -rw-r--r-- | examples/expect.md | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/examples/expect.md b/examples/expect.md new file mode 100644 index 0000000..544a55e --- /dev/null +++ b/examples/expect.md | |||
| @@ -0,0 +1,66 @@ | |||
| 1 | Here's an example of an LPegLabel grammar that make its own function called | ||
| 2 | 'expect', which takes a pattern and a label as parameters and throws the label | ||
| 3 | if the pattern fails to be matched. This function can be extended later on to | ||
| 4 | record all errors encountered once error recovery is implemented. | ||
| 5 | |||
| 6 | ```lua | ||
| 7 | local lpeg = require"lpeglabel" | ||
| 8 | |||
| 9 | local R, S, P, V, T = lpeg.R, lpeg.S, lpeg.P, lpeg.V, lpeg.T | ||
| 10 | |||
| 11 | local labels = { | ||
| 12 | {"NoExp", "no expression found"}, | ||
| 13 | {"Extra", "extra chracters found after the expression"}, | ||
| 14 | {"ExpTerm", "expected a term after the operator"}, | ||
| 15 | {"ExpExp", "expected an expression after the parenthesis"}, | ||
| 16 | {"MisClose", "missing a closing ')' after the expression"}, | ||
| 17 | } | ||
| 18 | |||
| 19 | local function expect(patt, labname) | ||
| 20 | for i, elem in ipairs(labels) do | ||
| 21 | if elem[1] == labname then | ||
| 22 | return patt + T(i) | ||
| 23 | end | ||
| 24 | end | ||
| 25 | |||
| 26 | error("could not find label: " .. labname) | ||
| 27 | end | ||
| 28 | |||
| 29 | local num = R("09")^1 | ||
| 30 | local op = S("+-*/") | ||
| 31 | |||
| 32 | local g = P { | ||
| 33 | "Exp", | ||
| 34 | Exp = V"Term" * (op * expect(V"Term", "ExpTerm"))^0; | ||
| 35 | Term = num + V"Group"; | ||
| 36 | Group = "(" * expect(V"Exp", "ExpExp") * expect(")", "MisClose"); | ||
| 37 | } | ||
| 38 | |||
| 39 | g = expect(g, "NoExp") * expect(-P(1), "Extra") | ||
| 40 | |||
| 41 | local function check(input) | ||
| 42 | result, label, suffix = g:match(input) | ||
| 43 | if result ~= nil then | ||
| 44 | return "ok" | ||
| 45 | else | ||
| 46 | local pos = input:len() - suffix:len() + 1 | ||
| 47 | local msg = labels[label][2] | ||
| 48 | return "syntax error: " .. msg .. " (at index " .. pos .. ")" | ||
| 49 | end | ||
| 50 | end | ||
| 51 | |||
| 52 | print(check "(1+1-1*2/2") | ||
| 53 | --> syntax error: missing a closing ')' after the expression (at index 11) | ||
| 54 | |||
| 55 | print(check "(1+)-1*(2/2)") | ||
| 56 | --> syntax error: expected a term after the operator (at index 4) | ||
| 57 | |||
| 58 | print(check "(1+1)-1*(/2)") | ||
| 59 | --> syntax error: expected an expression after the parenthesis (at index 10) | ||
| 60 | |||
| 61 | print(check "1+(1-(1*2))/2x") | ||
| 62 | --> syntax error: extra chracters found after the expression (at index 14) | ||
| 63 | |||
| 64 | print(check "-1+(1-(1*2))/2") | ||
| 65 | --> syntax error: no expression found (at index 1) | ||
| 66 | ``` | ||
