Debian Codegraph @

texmf-dist/tex/luatex/lparse/lparse.lua

raw
1 -- lparse.lua
2 -- Copyright 2023-2025 Josef Friedrich
3 --
4 -- This work may be distributed and/or modified under the
5 -- conditions of the LaTeX Project Public License, either version 1.3c
6 -- of this license or (at your option) any later version.
7 -- The latest version of this license is in
8 -- http://www.latex-project.org/lppl.txt
9 -- and version 1.3c or later is part of all distributions of LaTeX
10 -- version 2008/05/04 or later.
11 --
12 -- This work has the LPPL maintenance status `maintained'.
13 --
14 -- The Current Maintainer of this work is Josef Friedrich.
15 --
16 -- This work consists of the files lparse.lua, lparse.tex,
17 -- and lparse.sty.
18 ---
19 if lpeg == nil then
20 lpeg = require('lpeg')
21 end
22
23 ---
24 ---@param spec string An argument specifier, for example `o m`
25 ---
26 ---Required arguments:
27 ---
28 ---* `m`: A standard mandatory argument, which can either be a single
29 --- token alone or multiple tokens surrounded by curly braces `{}`.
30 --- Regardless of the input, the argument will be passed to the
31 --- internal code without the outer braces. This is the `lparse`
32 --- type specifier for a normal TeX argument.
33 ---* `r`: Given as `r` `token1` `token2`, this denotes a
34 --- required delimited argument, where the delimiters are
35 --- `token1` and `token2`. If the opening delimiter
36 --- `token1` is missing, `nil` will be
37 --- returned after a suitable error.
38 ---* `R` Given as `R` `token1` `token2` `default`,
39 --- this is a required delimited argument as for `r`,
40 --- but it has a user-definable recovery `default` instead of
41 --- `nil`.
42 ---* `v`: Reads an argument `verbatim`, between the following
43 --- character and its next occurrence.
44 ---
45 ---Optional arguments:
46 ---
47 ---* `o`: A standard LaTeX optional argument, surrounded with square
48 --- brackets, which will supply
49 --- `nil` if not given (as described later).
50 ---* `d`: Given as `d` `token1` `token2`, an optional
51 --- argument which is delimited by `token1` and `token1`.
52 --- As with `o`, if no
53 --- value is given `nil` is returned.
54 ---* `O`: Given as `O{default}`, is like `o`, but
55 --- returns `default` if no value is given.
56 ---* `D`: Given as `D` `token1` `token2` `{default}`,
57 --- it is as for `d`, but returns `default` if no value is given.
58 --- Internally, the `o`, `d` and `O` types are
59 --- short-cuts to an appropriated-constructed `D` type argument.
60 ---* `s`: An optional star, which will result in a value
61 --- `true` if a star is present and `false`
62 --- otherwise (as described later).
63 ---* `t`: An optional `token`, which will result in a value
64 --- `true` if `token` is present and `false`
65 --- otherwise. Given as `t` `token`.
66 ---
67 ---@return Argument[]
68 local function parse_spec(spec)
69 local V = lpeg.V
70 local P = lpeg.P
71 local Set = lpeg.S
72 local Range = lpeg.R
73 local CaptureFolding = lpeg.Cf
74 local CaptureTable = lpeg.Ct
75 local Cc = lpeg.Cc
76 local CaptureSimple = lpeg.C
77
78 local function add_result(result, value)
79 if not result then
80 result = {}
81 end
82 table.insert(result, value)
83 return result
84 end
85
86 local function collect_delims(a, b)
87 return { init_delim = a, end_delim = b }
88 end
89
90 local function collect_token(a)
91 return { token = a }
92 end
93
94 local function set_default(a)
95 return { default = a }
96 end
97
98 local function combine(...)
99 local args = { ... }
100
101 local output = {}
102
103 for _, arg in ipairs(args) do
104 if type(arg) ~= 'table' then
105 arg = {}
106 end
107
108 for key, value in pairs(arg) do
109 output[key] = value
110 end
111
112 end
113
114 return output
115 end
116
117 local function ArgumentType(letter)
118 local function get_type(l)
119 return { argument_type = l }
120 end
121 return CaptureSimple(P(letter)) / get_type
122 end
123
124 local T = ArgumentType
125
126 local pattern = P({
127 'init',
128 init = V('whitespace') ^ 0 *
129 CaptureFolding(CaptureTable('') * V('list'), add_result),
130
131 list = (V('arg') * V('whitespace') ^ 1) ^ 0 * V('arg') ^ -1,
132
133 arg = V('m') + V('r') + V('R') + V('v') + V('o') + V('d') + V('O') +
134 V('D') + V('s') + V('t'),
135
136 m = T('m') / combine,
137
138 r = T('r') * V('delimiters') / combine,
139
140 R = T('R') * V('delimiters') * V('default') / combine,
141
142 v = T('v') * Cc({ verbatim = true }) / combine,
143
144 o = T('o') * Cc({ optional = true }) / combine,
145
146 d = T('d') * V('delimiters') * Cc({ optional = true }) / combine,
147
148 O = T('O') * V('default') * Cc({ optional = true }) / combine,
149
150 D = T('D') * V('delimiters') * V('default') *
151 Cc({ optional = true }) / combine,
152
153 s = T('s') * Cc({ star = true }) / combine,
154
155 t = T('t') * V('token') / combine,
156
157 token = V('delimiter') / collect_token,
158
159 delimiter = CaptureSimple(Range('!~')),
160
161 delimiters = V('delimiter') * V('delimiter') / collect_delims,
162
163 whitespace = Set(' \t\n\r'),
164
165 default = P('{') * CaptureSimple((1 - P('}')) ^ 0) * P('}') /
166 set_default,
167 })
168
169 return pattern:match(spec)
170
171 end
172
173 ---
174 ---@param t Token
175 local function debug_token(t)
176 print(t)
177 print('command', t.command)
178 print('cmdname', t.cmdname)
179 print('csname', t.csname)
180 print('id', t.id)
181 print('tok', t.tok)
182 print('active', t.active)
183 print('expandable', t.expandable)
184 print('protected', t.protected)
185 print('mode', t.mode)
186 print('index', t.index)
187 end
188
189 ---
190 ---Scan for an optional delimited argument.
191 ---
192 ---@param init_delim? string # The character that marks the beginning of an optional argument (by default `[`).
193 ---@param end_delim? string # The character that marks the end of an optional argument (by default `]`).
194 ---
195 ---@return string|nil # The string that was enclosed by the delimiters. The delimiters themselves are not returned.
196 local function scan_oarg(init_delim, end_delim)
197 if init_delim == nil then
198 init_delim = '['
199 end
200 if end_delim == nil then
201 end_delim = ']'
202 end
203
204 ---
205 ---Convert a token object to a string. If the token is a control sequence
206 ---it is converted to `\\csname`.
207 ---
208 ---@param t Token The token object.
209 ---
210 ---@return string token_string A string representing the token.
211 local function convert_token_to_string(t)
212 if t.csname ~= nil then
213 return '\\' .. t.csname
214 else
215 return utf8.char(t.index)
216 end
217 end
218
219 local delimiter_stack = 0
220
221 local function get_next_char()
222 local t = token.get_next()
223 local char = convert_token_to_string(t)
224 if char == init_delim then
225 delimiter_stack = delimiter_stack + 1
226 end
227
228 if char == end_delim then
229 delimiter_stack = delimiter_stack - 1
230 end
231 return char, t
232 end
233
234 local char, t = get_next_char()
235
236 if t.cmdname == 'spacer' then
237 char, t = get_next_char()
238 end
239
240 if char == init_delim then
241 local output = {}
242
243 char, t = get_next_char()
244
245 -- “while” better than “repeat ... until”: The end_delimiter is
246 -- included in the result output.
247 while not (char == end_delim and delimiter_stack == 0) do
248 table.insert(output, char)
249 char, t = get_next_char()
250 end
251 return table.concat(output, '')
252 else
253 token.put_next(t)
254 end
255 end
256
257 ---
258 ---Represents an argument of a command.
259 ---
260 ---The basic form of the argument specifier is a list of letters, where
261 ---each letter defines a `Argument`.
262 ---
263 ---## `m`:
264 ---
265 ---```lua
266 ---{ argument_type = 'm' }
267 ---```
268 ---
269 ---## `r`:
270 ---
271 ---```lua
272 ---{ argument_type = 'r', end_delim = '>', init_delim = '<' }
273 ---```
274 ---
275 ---## `R`:
276 ---
277 ---(`R<>{default}`)
278 ---
279 ---```lua
280 ---{
281 --- argument_type = 'R',
282 --- end_delim = '>',
283 --- init_delim = '<',
284 --- default = 'default',
285 ---}
286 ---```
287 ---
288 ---## `v`:
289 ---
290 ---```lua
291 ---{
292 --- argument_type = 'v',
293 --- verbatim = true,
294 ---}
295 ---```
296 ---
297 ---## `o`:
298 ---
299 ---```lua
300 ---{ argument_type = 'o', optional = true }
301 ---```
302 ---
303 ---## `d`:
304 ---
305 ---(`d<>`)
306 ---
307 ---```lua
308 ---{
309 --- argument_type = 'd',
310 --- optional = true,
311 --- end_delim = '>',
312 --- init_delim = '<',
313 ---}
314 ---```
315 ---
316 ---## `O`:
317 ---
318 ---(`O{default}`)
319 ---
320 ---```lua
321 ---{ argument_type = 'O', optional = true, default = 'default' }
322 ---```
323 ---
324 ---## `D`:
325 ---
326 ---(`D<>{default}`)
327 ---
328 ---```lua
329 ---{
330 --- argument_type = 'D',
331 --- optional = true,
332 --- default = ' default ',
333 --- end_delim = '>',
334 --- init_delim = '<',
335 ---}
336 ---```
337 ---
338 ---
339 ---## `s`:
340 ---
341 ---```lua
342 ---{ argument_type = 's', star = true }
343 ---```
344 ---
345 ---
346 ---## `t`:
347 ---
348 ---```lua
349 ---{ argument_type = 't', token = '+' }
350 ---```
351 ---
352 ---@class Argument
353 ---@field argument_type? 'm' | 'r' | 'R' | 'v' | 'o' | 'd' | 'O' | 'D' | 's' | 't' A single letter representing the argument type in the list of letters.
354 ---@field optional? boolean Indicates whether the argument is optional.
355 ---@field init_delim? string The character that marks the beginning of an argument.
356 ---@field end_delim? string The character that marks the end of an argument.
357 ---@field star? boolean `true` if it is a star argument type (`s`).
358 ---@field default? string The default value if no value is given.
359 ---@field verbatim? boolean `true` if it is a verbatim argument type (`v`).
360 ---@field token? string The optional token for the argument type `t`.
361
362 ---A parser that parses the argument specification (list of letters).
363 ---@class Scanner
364 ---@field spec string An argument specifier
365 ---@field args Argument[]
366 ---@field result any[]
367 local Scanner = {}
368 ---@private
369 Scanner.__index = Scanner
370
371 ---
372 ---@param spec string An argument specifier, for example `o m`
373 ---
374 ---Required arguments:
375 ---
376 ---* `m`: A standard mandatory argument, which can either be a single
377 --- token alone or multiple tokens surrounded by curly braces `{}`.
378 --- Regardless of the input, the argument will be passed to the
379 --- internal code without the outer braces. This is the `lparse`
380 --- type specifier for a normal TeX argument.
381 ---* `r`: Given as `r` `token1` `token2`, this denotes a
382 --- required delimited argument, where the delimiters are
383 --- `token1` and `token2`. If the opening delimiter
384 --- `token1` is missing, `nil` will be
385 --- returned after a suitable error.
386 ---* `R` Given as `R` `token1` `token2` `default`,
387 --- this is a required delimited argument as for `r`,
388 --- but it has a user-definable recovery `default` instead of
389 --- `nil`.
390 ---* `v`: Reads an argument `verbatim`, between the following
391 --- character and its next occurrence.
392 ---
393 ---Optional arguments:
394 ---
395 ---* `o`: A standard LaTeX optional argument, surrounded with square
396 --- brackets, which will supply
397 --- `nil` if not given (as described later).
398 ---* `d`: Given as `d` `token1` `token2`, an optional
399 --- argument which is delimited by `token1` and `token1`.
400 --- As with `o`, if no
401 --- value is given `nil` is returned.
402 ---* `O`: Given as `O{default}`, is like `o`, but
403 --- returns `default` if no value is given.
404 ---* `D`: Given as `D` `token1` `token2` `{default}`,
405 --- it is as for `d`, but returns `default` if no value is given.
406 --- Internally, the `o`, `d` and `O` types are
407 --- short-cuts to an appropriated-constructed `D` type argument.
408 ---* `s`: An optional star, which will result in a value
409 --- `true` if a star is present and `false`
410 --- otherwise (as described later).
411 ---* `t`: An optional `token`, which will result in a value
412 --- `true` if `token` is present and `false`
413 --- otherwise. Given as `t` `token`.
414 function Scanner:new(spec)
415 local parser = {}
416 setmetatable(parser, Scanner)
417 parser.spec = spec
418 parser.args = parse_spec(spec)
419 parser.result = parser:scan()
420 return parser
421 end
422
423 ---
424 ---Scan for arguments in the token input stream.
425 ---
426 ---@return any[]
427 function Scanner:scan()
428 local result = {}
429 local index = 1
430 for _, arg in pairs(self.args) do
431 if arg.star then
432 -- s
433 result[index] = token.scan_keyword('*')
434 elseif arg.token then
435 -- t
436 result[index] = token.scan_keyword(arg.token)
437 elseif arg.optional then
438 -- o d O D
439 local oarg = scan_oarg(arg.init_delim, arg.end_delim)
440 if arg.default and oarg == nil then
441 oarg = arg.default
442 end
443 result[index] = oarg
444 elseif arg.init_delim and arg.end_delim then
445 -- r R
446 local oarg = scan_oarg(arg.init_delim, arg.end_delim)
447 if arg.default and oarg == nil then
448 oarg = arg.default
449 end
450 if oarg == nil then
451 tex.error('Missing required argument')
452 end
453 result[index] = oarg
454 else
455 -- m v
456 local marg = token.scan_argument(arg.verbatim ~= true)
457 if marg == nil then
458 tex.error('Missing required argument')
459 end
460 result[index] = marg
461 end
462 index = index + 1
463 end
464 return result
465 end
466
467 ---@private
468 function Scanner:set_result(...)
469 self.result = { ... }
470 end
471
472 ---
473 ---@return string|boolean|nil ...
474 function Scanner:export()
475 -- #self.arg: to get all elements of the result table, also elements
476 -- with nil values.
477 return table.unpack(self.result, 1, #self.args)
478 end
479
480 function Scanner:assert(...)
481 local arguments = { ... }
482 for index, arg in ipairs(arguments) do
483 assert(self.result[index] == arg, string.format(
484 'Argument at index %d doesn’t match: “%s” != “%s”',
485 index, self.result[index], arg))
486 end
487 end
488
489 function Scanner:debug()
490 for index = 1, #self.args do
491 print(index, self.result[index])
492 end
493 end
494
495 ---
496 ---@param spec string An argument specifier, for example `o m`
497 ---
498 ---Required arguments:
499 ---
500 ---* `m`: A standard mandatory argument, which can either be a single
501 --- token alone or multiple tokens surrounded by curly braces `{}`.
502 --- Regardless of the input, the argument will be passed to the
503 --- internal code without the outer braces. This is the `lparse`
504 --- type specifier for a normal TeX argument.
505 ---* `r`: Given as `r` `token1` `token2`, this denotes a
506 --- required delimited argument, where the delimiters are
507 --- `token1` and `token2`. If the opening delimiter
508 --- `token1` is missing, `nil` will be
509 --- returned after a suitable error.
510 ---* `R` Given as `R` `token1` `token2` `default`,
511 --- this is a required delimited argument as for `r`,
512 --- but it has a user-definable recovery `default` instead of
513 --- `nil`.
514 ---* `v`: Reads an argument `verbatim`, between the following
515 --- character and its next occurrence.
516 ---
517 ---Optional arguments:
518 ---
519 ---* `o`: A standard LaTeX optional argument, surrounded with square
520 --- brackets, which will supply
521 --- `nil` if not given (as described later).
522 ---* `d`: Given as `d` `token1` `token2`, an optional
523 --- argument which is delimited by `token1` and `token1`.
524 --- As with `o`, if no
525 --- value is given `nil` is returned.
526 ---* `O`: Given as `O{default}`, is like `o`, but
527 --- returns `default` if no value is given.
528 ---* `D`: Given as `D` `token1` `token2` `{default}`,
529 --- it is as for `d`, but returns `default` if no value is given.
530 --- Internally, the `o`, `d` and `O` types are
531 --- short-cuts to an appropriated-constructed `D` type argument.
532 ---* `s`: An optional star, which will result in a value
533 --- `true` if a star is present and `false`
534 --- otherwise (as described later).
535 ---* `t`: An optional `token`, which will result in a value
536 --- `true` if `token` is present and `false`
537 --- otherwise. Given as `t` `token`.
538 ---
539 ---@return Scanner
540 local function create_scanner(spec)
541 return Scanner:new(spec)
542 end
543
544 ---
545 ---Scan for arguments in the token input stream.
546 ---
547 ---@param spec string An argument specifier, for example `o m`
548 ---
549 ---Required arguments:
550 ---
551 ---* `m`: A standard mandatory argument, which can either be a single
552 --- token alone or multiple tokens surrounded by curly braces `{}`.
553 --- Regardless of the input, the argument will be passed to the
554 --- internal code without the outer braces. This is the `lparse`
555 --- type specifier for a normal TeX argument.
556 ---* `r`: Given as `r` `token1` `token2`, this denotes a
557 --- required delimited argument, where the delimiters are
558 --- `token1` and `token2`. If the opening delimiter
559 --- `token1` is missing, `nil` will be
560 --- returned after a suitable error.
561 ---* `R` Given as `R` `token1` `token2` `default`,
562 --- this is a required delimited argument as for `r`,
563 --- but it has a user-definable recovery `default` instead of
564 --- `nil`.
565 ---* `v`: Reads an argument `verbatim`, between the following
566 --- character and its next occurrence.
567 ---
568 ---Optional arguments:
569 ---
570 ---* `o`: A standard LaTeX optional argument, surrounded with square
571 --- brackets, which will supply
572 --- `nil` if not given (as described later).
573 ---* `d`: Given as `d` `token1` `token2`, an optional
574 --- argument which is delimited by `token1` and `token1`.
575 --- As with `o`, if no
576 --- value is given `nil` is returned.
577 ---* `O`: Given as `O{default}`, is like `o`, but
578 --- returns `default` if no value is given.
579 ---* `D`: Given as `D` `token1` `token2` `{default}`,
580 --- it is as for `d`, but returns `default` if no value is given.
581 --- Internally, the `o`, `d` and `O` types are
582 --- short-cuts to an appropriated-constructed `D` type argument.
583 ---* `s`: An optional star, which will result in a value
584 --- `true` if a star is present and `false`
585 --- otherwise (as described later).
586 ---* `t`: An optional `token`, which will result in a value
587 --- `true` if `token` is present and `false`
588 --- otherwise. Given as `t` `token`.
589 ---
590 ---@return boolean|string|nil ...
591 local function scan(spec)
592 local scanner = create_scanner(spec)
593 return scanner:export()
594 end
595
596 ---@class RegisterCsnameOptions
597 ---@field global? boolean
598 ---@field projected? boolean
599
600 ---
601 ---Register a Lua function under a control sequence name (`csname`).
602 ---
603 ---@param csname string # The control sequence name without the leading backslash.
604 ---@param fn function # The Lua function to be called when the command name is called in the TeX code.
605 ---@param opts? RegisterCsnameOptions
606 local function register_csname(csname, fn, opts)
607 if opts == nil then
608 opts = {}
609 end
610 local fns = lua.get_functions_table()
611 local index = 1
612 while fns[index] do
613 index = index + 1
614 end
615 fns[index] = fn
616 if opts.global and opts.projected then
617 token.set_lua(csname, index, 'global', 'protected')
618 elseif opts.global then
619 token.set_lua(csname, index, 'global')
620 elseif opts.projected then
621 token.set_lua(csname, index, 'protected')
622 else
623 token.set_lua(csname, index)
624 end
625 end
626
627 return {
628 scan = scan,
629 Scanner = create_scanner,
630 register_csname = register_csname,
631 utils = {
632 parse_spec = parse_spec,
633 scan_oarg = scan_oarg,
634 },
635 }