• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

andremm / lua-parser / #26

13 Nov 2026 04:46PM UTC coverage: 97.849% (-0.6%) from 98.427%
#26

push

github

web-flow
Merge pull request #19 from Validark/patch-1

Polyfill utf8.char

12 of 25 new or added lines in 1 file covered. (48.0%)

2138 of 2185 relevant lines covered (97.85%)

23.15 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.83
/lua-parser/parser.lua
1
--[[
2
This module implements a parser for Lua 5.3 with LPeg,
3
and generates an Abstract Syntax Tree that is similar to the one generated by Metalua.
4
For more information about Metalua, please, visit:
5
https://github.com/fab13n/metalua-parser
6

7
block: { stat* }
8

9
stat:
10
    `Do{ stat* }
11
  | `Set{ {lhs+} {expr+} }                    -- lhs1, lhs2... = e1, e2...
12
  | `While{ expr block }                      -- while e do b end
13
  | `Repeat{ block expr }                     -- repeat b until e
14
  | `If{ (expr block)+ block? }               -- if e1 then b1 [elseif e2 then b2] ... [else bn] end
15
  | `Fornum{ ident expr expr expr? block }    -- for ident = e, e[, e] do b end
16
  | `Forin{ {ident+} {expr+} block }          -- for i1, i2... in e1, e2... do b end
17
  | `Local{ {ident+} {expr+}? }               -- local i1, i2... = e1, e2...
18
  | `Localrec{ ident expr }                   -- only used for 'local function'
19
  | `Goto{ <string> }                         -- goto str
20
  | `Label{ <string> }                        -- ::str::
21
  | `Return{ <expr*> }                        -- return e1, e2...
22
  | `Break                                    -- break
23
  | apply
24

25
expr:
26
    `Nil
27
  | `Dots
28
  | `Boolean{ <boolean> }
29
  | `Number{ <number> }
30
  | `String{ <string> }
31
  | `Function{ { `Id{ <string> }* `Dots? } block }
32
  | `Table{ ( `Pair{ expr expr } | expr )* }
33
  | `Op{ opid expr expr? }
34
  | `Paren{ expr }       -- significant to cut multiple values returns
35
  | apply
36
  | lhs
37

38
apply:
39
    `Call{ expr expr* }
40
  | `Invoke{ expr `String{ <string> } expr* }
41

42
lhs: `Id{ <string> } | `Index{ expr expr }
43

44
opid:  -- includes additional operators from Lua 5.3 and all relational operators
45
    'add'  | 'sub' | 'mul'  | 'div'
46
  | 'idiv' | 'mod' | 'pow'  | 'concat'
47
  | 'band' | 'bor' | 'bxor' | 'shl' | 'shr'
48
  | 'eq'   | 'ne'  | 'lt'   | 'gt'  | 'le'   | 'ge'
49
  | 'and'  | 'or'  | 'unm'  | 'len' | 'bnot' | 'not'
50
]]
51

52
local utf8_char = (utf8 or {
1 ✔
53
        char = function(...)
54
                local results = { ... }
1 ✔
55
                local n = select("#", ...)
1 ✔
56

57
                for i = 1, n do
2 ✔
58
                        local a = results[i]
1 ✔
59

60
                        if type(a) ~= "number" then
1 ✔
NEW
61
                                a = tonumber(a) or error("bad argument #" .. i .. " to 'char' (number expected, got " .. type(a) .. ")", 2)
×
62
                        end
63

64
                        if not (0 <= a) or a > 1114111 or a % 1 ~= 0 then
1 ✔
NEW
65
                                error("bad argument #" .. i .. " to 'char' (expected an integer in the range [0, 1114111], got " .. a .. ")", 2)
×
66
                        end
67

68
                        if a >= 128 then
1 ✔
NEW
69
                                local _1 = a % 64
×
NEW
70
                                local b = (a - _1) / 64
×
71

NEW
72
                                if a >= 2048 then
×
NEW
73
                                        local _64 = b % 64
×
NEW
74
                                        local c = (b - _64) / 64
×
75

NEW
76
                                        if a >= 65536 then
×
NEW
77
                                                local _4096 = c % 64
×
NEW
78
                                                local d = (c - _4096) / 64
×
NEW
79
                                                results[i] = string.char(d + 240, _4096 + 128, _64 + 128, _1 + 128)
×
80
                                        else
NEW
81
                                                results[i] = string.char(c + 224, _64 + 128, _1 + 128)
×
82
                                        end
83
                                else
NEW
84
                                        results[i] = string.char(b + 192, _1 + 128)
×
85
                                end
86
                        else
87
                                results[i] = string.char(a)
1 ✔
88
                        end
89
                end
90
                return table.concat(results, nil, 1, n)
1 ✔
91
        end
92
}).char
1 ✔
93

94
local lpeg = require "lpeglabel"
1 ✔
95

96
lpeg.locale(lpeg)
1 ✔
97

98
local P, S, V = lpeg.P, lpeg.S, lpeg.V
1 ✔
99
local C, Carg, Cb, Cc = lpeg.C, lpeg.Carg, lpeg.Cb, lpeg.Cc
1 ✔
100
local Cf, Cg, Cmt, Cp, Cs, Ct = lpeg.Cf, lpeg.Cg, lpeg.Cmt, lpeg.Cp, lpeg.Cs, lpeg.Ct
1 ✔
101
local Lc, T = lpeg.Lc, lpeg.T
1 ✔
102

103
local alpha, digit, alnum = lpeg.alpha, lpeg.digit, lpeg.alnum
1 ✔
104
local xdigit = lpeg.xdigit
1 ✔
105
local space = lpeg.space
1 ✔
106

107

108
-- error message auxiliary functions
109

110
local labels = {
1 ✔
111
  { "ErrExtra", "unexpected character(s), expected EOF" },
1 ✔
112
  { "ErrInvalidStat", "unexpected token, invalid start of statement" },
1 ✔
113

114
  { "ErrEndIf", "expected 'end' to close the if statement" },
1 ✔
115
  { "ErrExprIf", "expected a condition after 'if'" },
1 ✔
116
  { "ErrThenIf", "expected 'then' after the condition" },
1 ✔
117
  { "ErrExprEIf", "expected a condition after 'elseif'" },
1 ✔
118
  { "ErrThenEIf", "expected 'then' after the condition" },
1 ✔
119

120
  { "ErrEndDo", "expected 'end' to close the do block" },
1 ✔
121
  { "ErrExprWhile", "expected a condition after 'while'" },
1 ✔
122
  { "ErrDoWhile", "expected 'do' after the condition" },
1 ✔
123
  { "ErrEndWhile", "expected 'end' to close the while loop" },
1 ✔
124
  { "ErrUntilRep", "expected 'until' at the end of the repeat loop" },
1 ✔
125
  { "ErrExprRep", "expected a conditions after 'until'" },
1 ✔
126

127
  { "ErrForRange", "expected a numeric or generic range after 'for'" },
1 ✔
128
  { "ErrEndFor", "expected 'end' to close the for loop" },
1 ✔
129
  { "ErrExprFor1", "expected a starting expression for the numeric range" },
1 ✔
130
  { "ErrCommaFor", "expected ',' to split the start and end of the range" },
1 ✔
131
  { "ErrExprFor2", "expected an ending expression for the numeric range" },
1 ✔
132
  { "ErrExprFor3", "expected a step expression for the numeric range after ','" },
1 ✔
133
  { "ErrInFor", "expected '=' or 'in' after the variable(s)" },
1 ✔
134
  { "ErrEListFor", "expected one or more expressions after 'in'" },
1 ✔
135
  { "ErrDoFor", "expected 'do' after the range of the for loop" },
1 ✔
136

137
  { "ErrDefLocal", "expected a function definition or assignment after local" },
1 ✔
138
  { "ErrNameLFunc", "expected a function name after 'function'" },
1 ✔
139
  { "ErrEListLAssign", "expected one or more expressions after '='" },
1 ✔
140
  { "ErrEListAssign", "expected one or more expressions after '='" },
1 ✔
141

142
  { "ErrFuncName", "expected a function name after 'function'" },
1 ✔
143
  { "ErrNameFunc1", "expected a function name after '.'" },
1 ✔
144
  { "ErrNameFunc2", "expected a method name after ':'" },
1 ✔
145
  { "ErrOParenPList", "expected '(' for the parameter list" },
1 ✔
146
  { "ErrCParenPList", "expected ')' to close the parameter list" },
1 ✔
147
  { "ErrEndFunc", "expected 'end' to close the function body" },
1 ✔
148
  { "ErrParList", "expected a variable name or '...' after ','" },
1 ✔
149

150
  { "ErrLabel", "expected a label name after '::'" },
1 ✔
151
  { "ErrCloseLabel", "expected '::' after the label" },
1 ✔
152
  { "ErrGoto", "expected a label after 'goto'" },
1 ✔
153
  { "ErrRetList", "expected an expression after ',' in the return statement" },
1 ✔
154

155
  { "ErrVarList", "expected a variable name after ','" },
1 ✔
156
  { "ErrExprList", "expected an expression after ','" },
1 ✔
157

158
  { "ErrOrExpr", "expected an expression after 'or'" },
1 ✔
159
  { "ErrAndExpr", "expected an expression after 'and'" },
1 ✔
160
  { "ErrRelExpr", "expected an expression after the relational operator" },
1 ✔
161
  { "ErrBOrExpr", "expected an expression after '|'" },
1 ✔
162
  { "ErrBXorExpr", "expected an expression after '~'" },
1 ✔
163
  { "ErrBAndExpr", "expected an expression after '&'" },
1 ✔
164
  { "ErrShiftExpr", "expected an expression after the bit shift" },
1 ✔
165
  { "ErrConcatExpr", "expected an expression after '..'" },
1 ✔
166
  { "ErrAddExpr", "expected an expression after the additive operator" },
1 ✔
167
  { "ErrMulExpr", "expected an expression after the multiplicative operator" },
1 ✔
168
  { "ErrUnaryExpr", "expected an expression after the unary operator" },
1 ✔
169
  { "ErrPowExpr", "expected an expression after '^'" },
1 ✔
170

171
  { "ErrExprParen", "expected an expression after '('" },
1 ✔
172
  { "ErrCParenExpr", "expected ')' to close the expression" },
1 ✔
173
  { "ErrNameIndex", "expected a field name after '.'" },
1 ✔
174
  { "ErrExprIndex", "expected an expression after '['" },
1 ✔
175
  { "ErrCBracketIndex", "expected ']' to close the indexing expression" },
1 ✔
176
  { "ErrNameMeth", "expected a method name after ':'" },
1 ✔
177
  { "ErrMethArgs", "expected some arguments for the method call (or '()')" },
1 ✔
178

179
  { "ErrArgList", "expected an expression after ',' in the argument list" },
1 ✔
180
  { "ErrCParenArgs", "expected ')' to close the argument list" },
1 ✔
181

182
  { "ErrCBraceTable", "expected '}' to close the table constructor" },
1 ✔
183
  { "ErrEqField", "expected '=' after the table key" },
1 ✔
184
  { "ErrExprField", "expected an expression after '='" },
1 ✔
185
  { "ErrExprFKey", "expected an expression after '[' for the table key" },
1 ✔
186
  { "ErrCBracketFKey", "expected ']' to close the table key" },
1 ✔
187

188
  { "ErrDigitHex", "expected one or more hexadecimal digits after '0x'" },
1 ✔
189
  { "ErrDigitDeci", "expected one or more digits after the decimal point" },
1 ✔
190
  { "ErrDigitExpo", "expected one or more digits for the exponent" },
1 ✔
191

192
  { "ErrQuote", "unclosed string" },
1 ✔
193
  { "ErrHexEsc", "expected exactly two hexadecimal digits after '\\x'" },
1 ✔
194
  { "ErrOBraceUEsc", "expected '{' after '\\u'" },
1 ✔
195
  { "ErrDigitUEsc", "expected one or more hexadecimal digits for the UTF-8 code point" },
1 ✔
196
  { "ErrCBraceUEsc", "expected '}' after the code point" },
1 ✔
197
  { "ErrEscSeq", "invalid escape sequence" },
1 ✔
198
  { "ErrCloseLStr", "unclosed long string" },
1 ✔
199
}
1 ✔
200

201
local function throw(label)
202
  label = "Err" .. label
76 ✔
203
  for i, labelinfo in ipairs(labels) do
2,919 ✔
204
    if labelinfo[1] == label then
2,919 ✔
205
      return T(i)
76 ✔
206
    end
207
  end
208

209
  error("Label not found: " .. label)
×
210
end
211

212
local function expect (patt, label)
213
  return patt + throw(label)
74 ✔
214
end
215

216

217
-- regular combinators and auxiliary functions
218

219
local function token (patt)
220
  return patt * V"Skip"
93 ✔
221
end
222

223
local function sym (str)
224
  return token(P(str))
59 ✔
225
end
226

227
local function kw (str)
228
  return token(P(str) * -V"IdRest")
31 ✔
229
end
230

231
local function dec(n)
232
  return n - 1
1,403 ✔
233
end
234

235
local function tagC (tag, patt)
236
  return Ct(Cg(Cp(), "pos") * Cg(Cc(tag), "tag") * patt * Cg(Cp() / dec, "end_pos"))
36 ✔
237
end
238

239
local function unaryOp (op, e)
240
  return { tag = "Op", pos = e.pos, end_pos = e.end_pos, [1] = op, [2] = e }
8 ✔
241
end
242

243
local function binaryOp (e1, op, e2)
244
  if not op then
856 ✔
245
    return e1
793 ✔
246
  else
247
    return { tag = "Op", pos = e1.pos, end_pos = e2.end_pos, [1] = op, [2] = e1, [3] = e2 }
63 ✔
248
  end
249
end
250

251
local function sepBy (patt, sep, label)
252
  if label then
15 ✔
253
    return patt * Cg(sep * expect(patt, label))^0
13 ✔
254
  else
255
    return patt * Cg(sep * patt)^0
2 ✔
256
  end
257
end
258

259
local function cut(s, idx, match)
260
  return idx, match
3,216 ✔
261
end
262

263
local function chainOp (patt, sep, label)
264
  return Cmt(Cf(sepBy(patt, sep, label), binaryOp), cut)
9 ✔
265
end
266

267
local function commaSep (patt, label)
268
  return sepBy(patt, sym(","), label)
5 ✔
269
end
270

271
local function tagDo (block)
272
  block.tag = "Do"
15 ✔
273
  return block
15 ✔
274
end
275

276
local function fixFuncStat (func)
277
  if func[1].is_method then table.insert(func[2][1], 1, { tag = "Id", [1] = "self" }) end
17 ✔
278
  func[1] = {func[1]}
17 ✔
279
  func[2] = {func[2]}
17 ✔
280
  return func
17 ✔
281
end
282

283
local function addDots (params, dots)
284
  if dots then table.insert(params, dots) end
11 ✔
285
  return params
11 ✔
286
end
287

288
local function insertIndex (t, index)
289
  return { tag = "Index", pos = t.pos, end_pos = index.end_pos, [1] = t, [2] = index }
4 ✔
290
end
291

292
local function markMethod(t, method)
293
  if method then
12 ✔
294
    return { tag = "Index", pos = t.pos, end_pos = method.end_pos, is_method = true, [1] = t, [2] = method }
2 ✔
295
  end
296
  return t
10 ✔
297
end
298

299
local function makeIndexOrCall (t1, t2)
300
  if t2.tag == "Call" or t2.tag == "Invoke" then
45 ✔
301
    local t = { tag = t2.tag, pos = t1.pos, end_pos = t2.end_pos, [1] = t1 }
33 ✔
302
    for k, v in ipairs(t2) do
48 ✔
303
      table.insert(t, v)
15 ✔
304
    end
305
    return t
33 ✔
306
  end
307
  return { tag = "Index", pos = t1.pos, end_pos = t2.end_pos, [1] = t1, [2] = t2[1] }
12 ✔
308
end
309

310
-- grammar
311
local G = { V"Lua",
1 ✔
312
  Lua      = V"Shebang"^-1 * V"Skip" * V"Block" * expect(P(-1), "Extra");
1 ✔
313
  Shebang  = P"#!" * (P(1) - P"\n")^0;
1 ✔
314

315
  Block       = tagC("Block", V"Stat"^0 * V"RetStat"^-1);
1 ✔
316
  Stat        = V"IfStat" + V"DoStat" + V"WhileStat" + V"RepeatStat" + V"ForStat"
1 ✔
317
              + V"LocalStat" + V"FuncStat" + V"BreakStat" + V"LabelStat" + V"GoToStat"
1 ✔
318
              + V"FuncCall" + V"Assignment" + sym(";") + -V"BlockEnd" * throw("InvalidStat");
1 ✔
319
  BlockEnd    = P"return" + "end" + "elseif" + "else" + "until" + -1;
1 ✔
320

321
  IfStat      = tagC("If", V"IfPart" * V"ElseIfPart"^0 * V"ElsePart"^-1 * expect(kw("end"), "EndIf"));
1 ✔
322
  IfPart      = kw("if") * expect(V"Expr", "ExprIf") * expect(kw("then"), "ThenIf") * V"Block";
1 ✔
323
  ElseIfPart  = kw("elseif") * expect(V"Expr", "ExprEIf") * expect(kw("then"), "ThenEIf") * V"Block";
1 ✔
324
  ElsePart    = kw("else") * V"Block";
1 ✔
325

326
  DoStat      = kw("do") * V"Block" * expect(kw("end"), "EndDo") / tagDo;
1 ✔
327
  WhileStat   = tagC("While", kw("while") * expect(V"Expr", "ExprWhile") * V"WhileBody");
1 ✔
328
  WhileBody   = expect(kw("do"), "DoWhile") * V"Block" * expect(kw("end"), "EndWhile");
1 ✔
329
  RepeatStat  = tagC("Repeat", kw("repeat") * V"Block" * expect(kw("until"), "UntilRep") * expect(V"Expr", "ExprRep"));
1 ✔
330

331
  ForStat   = kw("for") * expect(V"ForNum" + V"ForIn", "ForRange") * expect(kw("end"), "EndFor");
1 ✔
332
  ForNum    = tagC("Fornum", V"Id" * sym("=") * V"NumRange" * V"ForBody");
1 ✔
333
  NumRange  = expect(V"Expr", "ExprFor1") * expect(sym(","), "CommaFor") *expect(V"Expr", "ExprFor2")
1 ✔
334
            * (sym(",") * expect(V"Expr", "ExprFor3"))^-1;
1 ✔
335
  ForIn     = tagC("Forin", V"NameList" * expect(kw("in"), "InFor") * expect(V"ExprList", "EListFor") * V"ForBody");
1 ✔
336
  ForBody   = expect(kw("do"), "DoFor") * V"Block";
1 ✔
337

338
  LocalStat    = kw("local") * expect(V"LocalFunc" + V"LocalAssign", "DefLocal");
1 ✔
339
  LocalFunc    = tagC("Localrec", kw("function") * expect(V"Id", "NameLFunc") * V"FuncBody") / fixFuncStat;
1 ✔
340
  LocalAssign  = tagC("Local", V"NameList" * (sym("=") * expect(V"ExprList", "EListLAssign") + Ct(Cc())));
1 ✔
341
  Assignment   = tagC("Set", V"VarList" * sym("=") * expect(V"ExprList", "EListAssign"));
1 ✔
342

343
  FuncStat    = tagC("Set", kw("function") * expect(V"FuncName", "FuncName") * V"FuncBody") / fixFuncStat;
1 ✔
344
  FuncName    = Cf(V"Id" * (sym(".") * expect(V"StrId", "NameFunc1"))^0, insertIndex)
1 ✔
345
              * (sym(":") * expect(V"StrId", "NameFunc2"))^-1 / markMethod;
1 ✔
346
  FuncBody    = tagC("Function", V"FuncParams" * V"Block" * expect(kw("end"), "EndFunc"));
1 ✔
347
  FuncParams  = expect(sym("("), "OParenPList") * V"ParList" * expect(sym(")"), "CParenPList");
1 ✔
348
  ParList     = V"NameList" * (sym(",") * expect(tagC("Dots", sym("...")), "ParList"))^-1 / addDots
1 ✔
349
              + Ct(tagC("Dots", sym("...")))
1 ✔
350
              + Ct(Cc()); -- Cc({}) generates a bug since the {} would be shared across parses
1 ✔
351

352
  LabelStat  = tagC("Label", sym("::") * expect(V"Name", "Label") * expect(sym("::"), "CloseLabel"));
1 ✔
353
  GoToStat   = tagC("Goto", kw("goto") * expect(V"Name", "Goto"));
1 ✔
354
  BreakStat  = tagC("Break", kw("break"));
1 ✔
355
  RetStat    = tagC("Return", kw("return") * commaSep(V"Expr", "RetList")^-1 * sym(";")^-1);
1 ✔
356

357
  NameList  = tagC("NameList", commaSep(V"Id"));
1 ✔
358
  VarList   = tagC("VarList", commaSep(V"VarExpr", "VarList"));
1 ✔
359
  ExprList  = tagC("ExpList", commaSep(V"Expr", "ExprList"));
1 ✔
360

361
  Expr        = V"OrExpr";
1 ✔
362
  OrExpr      = chainOp(V"AndExpr", V"OrOp", "OrExpr");
1 ✔
363
  AndExpr     = chainOp(V"RelExpr", V"AndOp", "AndExpr");
1 ✔
364
  RelExpr     = chainOp(V"BOrExpr", V"RelOp", "RelExpr");
1 ✔
365
  BOrExpr     = chainOp(V"BXorExpr", V"BOrOp", "BOrExpr");
1 ✔
366
  BXorExpr    = chainOp(V"BAndExpr", V"BXorOp", "BXorExpr");
1 ✔
367
  BAndExpr    = chainOp(V"ShiftExpr", V"BAndOp", "BAndExpr");
1 ✔
368
  ShiftExpr   = chainOp(V"ConcatExpr", V"ShiftOp", "ShiftExpr");
1 ✔
369
  ConcatExpr  = V"AddExpr" * (V"ConcatOp" * expect(V"ConcatExpr", "ConcatExpr"))^-1 / binaryOp;
1 ✔
370
  AddExpr     = chainOp(V"MulExpr", V"AddOp", "AddExpr");
1 ✔
371
  MulExpr     = chainOp(V"UnaryExpr", V"MulOp", "MulExpr");
1 ✔
372
  UnaryExpr   = V"UnaryOp" * expect(V"UnaryExpr", "UnaryExpr") / unaryOp
1 ✔
373
              + V"PowExpr";
1 ✔
374
  PowExpr     = V"SimpleExpr" * (V"PowOp" * expect(V"UnaryExpr", "PowExpr"))^-1 / binaryOp;
1 ✔
375

376
  SimpleExpr = tagC("Number", V"Number")
1 ✔
377
             + tagC("String", V"String")
1 ✔
378
             + tagC("Nil", kw("nil"))
1 ✔
379
             + tagC("Boolean", kw("false") * Cc(false))
1 ✔
380
             + tagC("Boolean", kw("true") * Cc(true))
1 ✔
381
             + tagC("Dots", sym("..."))
1 ✔
382
             + V"FuncDef"
1 ✔
383
             + V"Table"
1 ✔
384
             + V"SuffixedExpr";
1 ✔
385

386
  FuncCall  = Cmt(V"SuffixedExpr", function(s, i, exp) return exp.tag == "Call" or exp.tag == "Invoke", exp end);
154 ✔
387
  VarExpr   = Cmt(V"SuffixedExpr", function(s, i, exp) return exp.tag == "Id" or exp.tag == "Index", exp end);
150 ✔
388

389
  SuffixedExpr  = Cf(V"PrimaryExpr" * (V"Index" + V"Call")^0, makeIndexOrCall);
1 ✔
390
  PrimaryExpr   = V"Id" + tagC("Paren", sym("(") * expect(V"Expr", "ExprParen") * expect(sym(")"), "CParenExpr"));
1 ✔
391
  Index         = tagC("DotIndex", sym("." * -P".") * expect(V"StrId", "NameIndex"))
1 ✔
392
                + tagC("ArrayIndex", sym("[" * -P(S"=[")) * expect(V"Expr", "ExprIndex") * expect(sym("]"), "CBracketIndex"));
1 ✔
393
  Call          = tagC("Invoke", Cg(sym(":" * -P":") * expect(V"StrId", "NameMeth") * expect(V"FuncArgs", "MethArgs")))
1 ✔
394
                + tagC("Call", V"FuncArgs");
1 ✔
395

396
  FuncDef   = kw("function") * V"FuncBody";
1 ✔
397
  FuncArgs  = sym("(") * commaSep(V"Expr", "ArgList")^-1 * expect(sym(")"), "CParenArgs")
1 ✔
398
            + V"Table"
1 ✔
399
            + tagC("String", V"String");
1 ✔
400

401
  Table      = tagC("Table", sym("{") * V"FieldList"^-1 * expect(sym("}"), "CBraceTable"));
1 ✔
402
  FieldList  = sepBy(V"Field", V"FieldSep") * V"FieldSep"^-1;
1 ✔
403
  Field      = tagC("Pair", V"FieldKey" * expect(sym("="), "EqField") * expect(V"Expr", "ExprField"))
1 ✔
404
             + V"Expr";
1 ✔
405
  FieldKey   = sym("[" * -P(S"=[")) * expect(V"Expr", "ExprFKey") * expect(sym("]"), "CBracketFKey")
1 ✔
406
             + V"StrId" * #("=" * -P"=");
1 ✔
407
  FieldSep   = sym(",") + sym(";");
1 ✔
408

409
  Id     = tagC("Id", V"Name");
1 ✔
410
  StrId  = tagC("String", V"Name");
1 ✔
411

412
  -- lexer
413
  Skip     = (V"Space" + V"Comment")^0;
1 ✔
414
  Space    = space^1;
1 ✔
415
  Comment  = P"--" * V"LongStr" / function () return end
6 ✔
416
           + P"--" * (P(1) - P"\n")^0;
1 ✔
417

418
  Name      = token(-V"Reserved" * C(V"Ident"));
1 ✔
419
  Reserved  = V"Keywords" * -V"IdRest";
1 ✔
420
  Keywords  = P"and" + "break" + "do" + "elseif" + "else" + "end"
1 ✔
421
            + "false" + "for" + "function" + "goto" + "if" + "in"
1 ✔
422
            + "local" + "nil" + "not" + "or" + "repeat" + "return"
1 ✔
423
            + "then" + "true" + "until" + "while";
1 ✔
424
  Ident     = V"IdStart" * V"IdRest"^0;
1 ✔
425
  IdStart   = alpha + P"_";
1 ✔
426
  IdRest    = alnum + P"_";
1 ✔
427

428
  Number   = token((V"Hex" + V"Float" + V"Int") / tonumber);
1 ✔
429
  Hex      = (P"0x" + "0X") * expect(xdigit^1, "DigitHex");
1 ✔
430
  Float    = V"Decimal" * V"Expo"^-1
1 ✔
431
           + V"Int" * V"Expo";
1 ✔
432
  Decimal  = digit^1 * "." * digit^0
1 ✔
433
           + P"." * -P"." * expect(digit^1, "DigitDeci");
1 ✔
434
  Expo     = S"eE" * S"+-"^-1 * expect(digit^1, "DigitExpo");
1 ✔
435
  Int      = digit^1;
1 ✔
436

437
  String    = token(V"ShortStr" + V"LongStr");
1 ✔
438
  ShortStr  = P'"' * Cs((V"EscSeq" + (P(1)-S'"\n'))^0) * expect(P'"', "Quote")
1 ✔
439
            + P"'" * Cs((V"EscSeq" + (P(1)-S"'\n"))^0) * expect(P"'", "Quote");
1 ✔
440

441
  EscSeq = P"\\" / ""  -- remove backslash
1 ✔
442
         * ( P"a" / "\a"
2 ✔
443
           + P"b" / "\b"
1 ✔
444
           + P"f" / "\f"
1 ✔
445
           + P"n" / "\n"
1 ✔
446
           + P"r" / "\r"
1 ✔
447
           + P"t" / "\t"
1 ✔
448
           + P"v" / "\v"
1 ✔
449
 
450
           + P"\n" / "\n"
1 ✔
451
           + P"\r" / "\n"
1 ✔
452
 
453
           + P"\\" / "\\"
1 ✔
454
           + P"\"" / "\""
1 ✔
455
           + P"\'" / "\'"
1 ✔
456

457
           + P"z" * space^0  / ""
1 ✔
458

459
           + digit * digit^-2 / tonumber / string.char
1 ✔
460
           + P"x" * expect(C(xdigit * xdigit), "HexEsc") * Cc(16) / tonumber / string.char
1 ✔
461
           + P"u" * expect("{", "OBraceUEsc")
2 ✔
462
                  * expect(C(xdigit^1), "DigitUEsc") * Cc(16)
1 ✔
463
                  * expect("}", "CBraceUEsc")
1 ✔
464
                  / tonumber 
1 ✔
465
                  / utf8_char
1 ✔
466
           + throw("EscSeq")
1 ✔
467
           );
1 ✔
468

469
  LongStr  = V"Open" * C((P(1) - V"CloseEq")^0) * expect(V"Close", "CloseLStr") / function (s, eqs) return s end;
8 ✔
470
  Open     = "[" * Cg(V"Equals", "openEq") * "[" * P"\n"^-1;
1 ✔
471
  Close    = "]" * C(V"Equals") * "]";
1 ✔
472
  Equals   = P"="^0;
1 ✔
473
  CloseEq  = Cmt(V"Close" * Cb("openEq"), function (s, i, closeEq, openEq) return #openEq == #closeEq end);
19 ✔
474

475
  OrOp      = kw("or")   / "or";
1 ✔
476
  AndOp     = kw("and")  / "and";
1 ✔
477
  RelOp     = sym("~=")  / "ne"
1 ✔
478
            + sym("==")  / "eq"
1 ✔
479
            + sym("<=")  / "le"
1 ✔
480
            + sym(">=")  / "ge"
1 ✔
481
            + sym("<")   / "lt"
1 ✔
482
            + sym(">")   / "gt";
1 ✔
483
  BOrOp     = sym("|")   / "bor";
1 ✔
484
  BXorOp    = sym("~" * -P"=") / "bxor";
1 ✔
485
  BAndOp    = sym("&")   / "band";
1 ✔
486
  ShiftOp   = sym("<<")  / "shl"
1 ✔
487
            + sym(">>")  / "shr";
1 ✔
488
  ConcatOp  = sym("..")  / "concat";
1 ✔
489
  AddOp     = sym("+")   / "add"
1 ✔
490
            + sym("-")   / "sub";
1 ✔
491
  MulOp     = sym("*")   / "mul"
1 ✔
492
            + sym("//")  / "idiv"
1 ✔
493
            + sym("/")   / "div"
1 ✔
494
            + sym("%")   / "mod";
1 ✔
495
  UnaryOp   = kw("not")  / "not"
1 ✔
496
            + sym("-")   / "unm"
1 ✔
497
            + sym("#")   / "len"
1 ✔
498
            + sym("~")   / "bnot";
1 ✔
499
  PowOp     = sym("^")   / "pow";
1 ✔
500
}
1 ✔
501

502
local parser = { detailed_errors = false }
1 ✔
503

504
local validator = require("lua-parser.validator")
1 ✔
505
local validate = validator.validate
1 ✔
506
local syntaxerror = validator.syntaxerror
1 ✔
507

508
function parser.parse (subject, filename)
2 ✔
509
  local errorinfo = { subject = subject, filename = filename }
323 ✔
510
  lpeg.setmaxstack(1000)
323 ✔
511
  local ast, label, errorpos = lpeg.match(G, subject, nil, errorinfo)
323 ✔
512
  if not ast then
323 ✔
513
    if parser.detailed_errors then
214 ✔
514
      local re = require "relabel"
×
515
      local line, col = re.calcline(subject, errorpos)
×
516
      return ast, {
×
517
        line = line;
518
        column = col;
519
        id = labels[label][1];
520
        message = labels[label][2];
521
        position = errorpos;
522
      }
523
    else
524
      local errmsg = labels[label][2]
214 ✔
525
      return ast, syntaxerror(errorinfo, errorpos, errmsg)
214 ✔
526
    end
527
  end
528
  return validate(ast, errorinfo)
109 ✔
529
end
530

531
return parser
1 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc