Debian Codegraph @

texmf-dist/tex/luatex/lualibs/lualibs-util-prs.lua

raw
1 if not modules then modules = { } end modules ['util-prs'] = {
2 version = 1.001,
3 comment = "companion to luat-lib.mkiv",
4 author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
5 copyright = "PRAGMA ADE / ConTeXt Development Team",
6 license = "see context related readme files"
7 }
8
9 local lpeg, table, string = lpeg, table, string
10 local P, R, V, S, C, Ct, Cs, Carg, Cc, Cg, Cf, Cp = lpeg.P, lpeg.R, lpeg.V, lpeg.S, lpeg.C, lpeg.Ct, lpeg.Cs, lpeg.Carg, lpeg.Cc, lpeg.Cg, lpeg.Cf, lpeg.Cp
11 local lpegmatch, lpegpatterns = lpeg.match, lpeg.patterns
12 local concat, gmatch, find = table.concat, string.gmatch, string.find
13 local tonumber, tostring, type, next, rawset = tonumber, tostring, type, next, rawset
14 local mod, div = math.mod, math.div
15
16 utilities = utilities or {}
17 local parsers = utilities.parsers or { }
18 utilities.parsers = parsers
19 local patterns = parsers.patterns or { }
20 parsers.patterns = patterns
21
22 local setmetatableindex = table.setmetatableindex
23 local sortedhash = table.sortedhash
24 local sortedkeys = table.sortedkeys
25 local tohash = table.tohash
26
27 local hashes = { }
28 parsers.hashes = hashes
29 -- we share some patterns
30
31 local digit = R("09")
32 local space = P(' ')
33 local equal = P("=")
34 local colon = P(":")
35 local comma = P(",")
36 local lbrace = P("{")
37 local rbrace = P("}")
38 local lparent = P("(")
39 local rparent = P(")")
40 local lbracket = P("[")
41 local rbracket = P("]")
42 local period = S(".")
43 local punctuation = S(".,:;")
44 local spacer = lpegpatterns.spacer
45 local whitespace = lpegpatterns.whitespace
46 local newline = lpegpatterns.newline
47 local anything = lpegpatterns.anything
48 local endofstring = lpegpatterns.endofstring
49
50 local nobrace = 1 - (lbrace + rbrace )
51 local noparent = 1 - (lparent + rparent)
52 local nobracket = 1 - (lbracket + rbracket)
53
54 -- we could use a Cf Cg construct
55
56 local escape, left, right = P("\\"), P('{'), P('}')
57
58 -- lpegpatterns.balanced = P {
59 -- [1] = ((escape * (left+right)) + (1 - (left+right)) + V(2))^0,
60 -- [2] = left * V(1) * right
61 -- }
62 lpegpatterns.balanced = P {
63 ((escape * (left+right)) + (1 - (left+right)) + V(2))^0,
64 left * V(1) * right
65 }
66
67 local nestedbraces = P { lbrace * (nobrace + V(1))^0 * rbrace }
68 local nestedparents = P { lparent * (noparent + V(1))^0 * rparent }
69 local nestedbrackets = P { lbracket * (nobracket + V(1))^0 * rbracket }
70 local spaces = space^0
71 local argument = Cs((lbrace/"") * ((nobrace + nestedbraces)^0) * (rbrace/""))
72 local content = (1-endofstring)^0
73
74 lpegpatterns.nestedbraces = nestedbraces -- no capture
75 lpegpatterns.nestedparents = nestedparents -- no capture
76 lpegpatterns.nestedbrackets = nestedbrackets -- no capture
77 lpegpatterns.nested = nestedbraces -- no capture
78 lpegpatterns.argument = argument -- argument after e.g. =
79 lpegpatterns.content = content -- rest after e.g =
80
81 local value = lbrace * C((nobrace + nestedbraces)^0) * rbrace
82 + C((nestedbraces + (1-comma))^0)
83
84 local key = C((1-equal-comma)^1)
85 local pattern_a = (space+comma)^0 * (key * equal * value + key * C(""))
86 local pattern_c = (space+comma)^0 * (key * equal * value)
87 local pattern_d = (space+comma)^0 * (key * (equal+colon) * value + key * C(""))
88
89 local key = C((1-space-equal-comma)^1)
90 local pattern_b = spaces * comma^0 * spaces * (key * ((spaces * equal * spaces * value) + C("")))
91
92 -- "a=1, b=2, c=3, d={a{b,c}d}, e=12345, f=xx{a{b,c}d}xx, g={}" : outer {} removes, leading spaces ignored
93
94 local hash = { }
95
96 local function set(key,value)
97 hash[key] = value
98 end
99
100 local pattern_a_s = (pattern_a/set)^1
101 local pattern_b_s = (pattern_b/set)^1
102 local pattern_c_s = (pattern_c/set)^1
103 local pattern_d_s = (pattern_d/set)^1
104
105 patterns.settings_to_hash_a = pattern_a_s
106 patterns.settings_to_hash_b = pattern_b_s
107 patterns.settings_to_hash_c = pattern_c_s
108 patterns.settings_to_hash_d = pattern_d_s
109
110 function parsers.make_settings_to_hash_pattern(set,how)
111 if how == "strict" then
112 return (pattern_c/set)^1
113 elseif how == "tolerant" then
114 return (pattern_b/set)^1
115 else
116 return (pattern_a/set)^1
117 end
118 end
119
120 function parsers.settings_to_hash(str,existing)
121 if not str or str == "" then
122 return { }
123 elseif type(str) == "table" then
124 if existing then
125 for k, v in next, str do
126 existing[k] = v
127 end
128 return exiting
129 else
130 return str
131 end
132 else
133 hash = existing or { }
134 lpegmatch(pattern_a_s,str)
135 return hash
136 end
137 end
138
139 function parsers.settings_to_hash_colon_too(str)
140 if not str or str == "" then
141 return { }
142 elseif type(str) == "table" then
143 return str
144 else
145 hash = { }
146 lpegmatch(pattern_d_s,str)
147 return hash
148 end
149 end
150
151 function parsers.settings_to_hash_tolerant(str,existing)
152 if not str or str == "" then
153 return { }
154 elseif type(str) == "table" then
155 if existing then
156 for k, v in next, str do
157 existing[k] = v
158 end
159 return exiting
160 else
161 return str
162 end
163 else
164 hash = existing or { }
165 lpegmatch(pattern_b_s,str)
166 return hash
167 end
168 end
169
170 function parsers.settings_to_hash_strict(str,existing)
171 if not str or str == "" then
172 return nil
173 elseif type(str) == "table" then
174 if existing then
175 for k, v in next, str do
176 existing[k] = v
177 end
178 return exiting
179 else
180 return str
181 end
182 elseif str and str ~= "" then
183 hash = existing or { }
184 lpegmatch(pattern_c_s,str)
185 return next(hash) and hash
186 end
187 end
188
189 local separator = comma * space^0
190 local value = lbrace * C((nobrace + nestedbraces)^0) * rbrace
191 + C((nestedbraces + (1-comma))^0)
192 local pattern = spaces * Ct(value*(separator*value)^0)
193
194 -- "aap, {noot}, mies" : outer {} removed, leading spaces ignored
195
196 patterns.settings_to_array = pattern
197
198 -- we could use a weak table as cache
199
200 function parsers.settings_to_array(str,strict)
201 if not str or str == "" then
202 return { }
203 elseif type(str) == "table" then
204 return str
205 elseif strict then
206 if find(str,"{",1,true) then
207 return lpegmatch(pattern,str)
208 else
209 return { str }
210 end
211 elseif find(str,",",1,true) then
212 return lpegmatch(pattern,str)
213 else
214 return { str }
215 end
216 end
217
218 function parsers.settings_to_numbers(str)
219 if not str or str == "" then
220 return { }
221 end
222 if type(str) == "table" then
223 -- fall through
224 elseif find(str,",",1,true) then
225 str = lpegmatch(pattern,str)
226 else
227 return { tonumber(str) }
228 end
229 for i=1,#str do
230 str[i] = tonumber(str[i])
231 end
232 return str
233 end
234
235 local value = lbrace * C((nobrace + nestedbraces)^0) * rbrace
236 + C((nestedbraces + nestedbrackets + nestedparents + (1-comma))^0)
237 local pattern = spaces * Ct(value*(separator*value)^0)
238
239 function parsers.settings_to_array_obey_fences(str)
240 return lpegmatch(pattern,str)
241 end
242
243 -- inspect(parsers.settings_to_array_obey_fences("url(http://a,b.c)"))
244
245 -- this one also strips end spaces before separators
246 --
247 -- "{123} , 456 " -> "123" "456"
248
249 -- local separator = space^0 * comma * space^0
250 -- local value = P(lbrace * C((nobrace + nestedbraces)^0) * rbrace)
251 -- + C((nestedbraces + (1-(space^0*(comma+P(-1)))))^0)
252 -- local withvalue = Carg(1) * value / function(f,s) return f(s) end
253 -- local pattern_a = spaces * Ct(value*(separator*value)^0)
254 -- local pattern_b = spaces * withvalue * (separator*withvalue)^0
255
256 local cache_a = { }
257 local cache_b = { }
258
259 function parsers.groupedsplitat(symbol,withaction)
260 if not symbol then
261 symbol = ","
262 end
263 local pattern = (withaction and cache_b or cache_a)[symbol]
264 if not pattern then
265 local symbols = S(symbol)
266 local separator = space^0 * symbols * space^0
267 local value =
268 lbrace
269 * C((nobrace + nestedbraces)^0)
270 -- * rbrace
271 * (rbrace * (#symbols + P(-1))) -- new per 2023-03-11
272 +
273 C((nestedbraces + (1-(space^0*(symbols+P(-1)))))^0)
274 if withaction then
275 local withvalue = Carg(1) * value / function(f,s) return f(s) end
276 pattern = spaces * withvalue * (separator*withvalue)^0
277 cache_b[symbol] = pattern
278 else
279 pattern = spaces * Ct(value*(separator*value)^0)
280 cache_a[symbol] = pattern
281 end
282 end
283 return pattern
284 end
285
286 local pattern_a = parsers.groupedsplitat(",",false)
287 local pattern_b = parsers.groupedsplitat(",",true)
288
289 function parsers.stripped_settings_to_array(str)
290 if not str or str == "" then
291 return { }
292 else
293 return lpegmatch(pattern_a,str)
294 end
295 end
296
297 function parsers.process_stripped_settings(str,action)
298 if not str or str == "" then
299 return { }
300 else
301 return lpegmatch(pattern_b,str,1,action)
302 end
303 end
304
305 -- parsers.process_stripped_settings("{123} , 456 ",function(s) print("["..s.."]") end)
306 -- parsers.process_stripped_settings("123 , 456 ",function(s) print("["..s.."]") end)
307
308 local function set(t,v)
309 t[#t+1] = v
310 end
311
312 local value = P(Carg(1)*value) / set
313 local pattern = value*(separator*value)^0 * Carg(1)
314
315 function parsers.add_settings_to_array(t,str)
316 return lpegmatch(pattern,str,nil,t)
317 end
318
319 function parsers.hash_to_string(h,separator,yes,no,strict,omit)
320 if h then
321 local t = { }
322 local tn = 0
323 local s = sortedkeys(h)
324 omit = omit and tohash(omit)
325 for i=1,#s do
326 local key = s[i]
327 if not omit or not omit[key] then
328 local value = h[key]
329 if type(value) == "boolean" then
330 if yes and no then
331 if value then
332 tn = tn + 1
333 t[tn] = key .. '=' .. yes
334 elseif not strict then
335 tn = tn + 1
336 t[tn] = key .. '=' .. no
337 end
338 elseif value or not strict then
339 tn = tn + 1
340 t[tn] = key .. '=' .. tostring(value)
341 end
342 else
343 tn = tn + 1
344 t[tn] = key .. '=' .. value
345 end
346 end
347 end
348 return concat(t,separator or ",")
349 else
350 return ""
351 end
352 end
353
354 function parsers.array_to_string(a,separator)
355 if a then
356 return concat(a,separator or ",")
357 else
358 return ""
359 end
360 end
361
362 -- function parsers.settings_to_set(str,t) -- tohash? -- todo: lpeg -- duplicate anyway
363 -- if str then
364 -- t = t or { }
365 -- for s in gmatch(str,"[^, ]+") do -- space added
366 -- t[s] = true
367 -- end
368 -- return t
369 -- else
370 -- return { }
371 -- end
372 -- end
373
374 local pattern = Cf(Ct("") * Cg(C((1-S(", "))^1) * S(", ")^0 * Cc(true))^1,rawset)
375
376 function parsers.settings_to_set(str)
377 return str and lpegmatch(pattern,str) or { }
378 end
379
380 hashes.settings_to_set = table.setmetatableindex(function(t,k) -- experiment, not public
381 local v = k and lpegmatch(pattern,k) or { }
382 t[k] = v
383 return v
384 end)
385
386 function parsers.settings_to_set(str)
387 return str and lpegmatch(pattern,str) or { }
388 end
389
390 local pattern = Ct((C((1-S(", "))^1) * S(", ")^0)^1)
391
392 hashes.settings_to_list = table.setmetatableindex(function(t,k) -- experiment, not public
393 local v = k and lpegmatch(pattern,k) or { }
394 t[k] = v
395 return v
396 end)
397
398 -- inspect(hashes.settings_to_set["a,b, c, d"])
399 -- inspect(hashes.settings_to_list["a,b, c, d"])
400
401 -- as we use a next, we are not sure when the gc kicks in
402
403 getmetatable(hashes.settings_to_set ).__mode = "kv" -- could be an option (maybe sharing makes sense)
404 getmetatable(hashes.settings_to_list).__mode = "kv" -- could be an option (maybe sharing makes sense)
405
406 function parsers.simple_hash_to_string(h, separator)
407 local t = { }
408 local tn = 0
409 for k, v in sortedhash(h) do
410 if v then
411 tn = tn + 1
412 t[tn] = k
413 end
414 end
415 return concat(t,separator or ",")
416 end
417
418 -- for mtx-context etc: aaaa bbbb cccc=dddd eeee=ffff
419
420 local str = Cs(lpegpatterns.unquoted) + C((1-whitespace-equal)^1)
421 local setting = Cf( Carg(1) * (whitespace^0 * Cg(str * whitespace^0 * (equal * whitespace^0 * str + Cc(""))))^1,rawset)
422 local splitter = setting^1
423
424 function parsers.options_to_hash(str,target)
425 return str and lpegmatch(splitter,str,1,target or { }) or { }
426 end
427
428 local splitter = lpeg.tsplitat(" ")
429
430 function parsers.options_to_array(str)
431 return str and lpegmatch(splitter,str) or { }
432 end
433
434 -- for chem (currently one level)
435
436 local value = P(lbrace * C((nobrace + nestedbraces)^0) * rbrace)
437 + C(digit^1 * lparent * (noparent + nestedparents)^1 * rparent)
438 + C((nestedbraces + (1-comma))^1)
439 local pattern_a = spaces * Ct(value*(separator*value)^0)
440
441 local function repeater(n,str)
442 if not n then
443 return str
444 else
445 local s = lpegmatch(pattern_a,str)
446 if n == 1 then
447 return unpack(s)
448 else
449 local t = { }
450 local tn = 0
451 for i=1,n do
452 for j=1,#s do
453 tn = tn + 1
454 t[tn] = s[j]
455 end
456 end
457 return unpack(t)
458 end
459 end
460 end
461
462 local value = P(lbrace * C((nobrace + nestedbraces)^0) * rbrace)
463 + (C(digit^1)/tonumber * lparent * Cs((noparent + nestedparents)^1) * rparent) / repeater
464 + C((nestedbraces + (1-comma))^1)
465 local pattern_b = spaces * Ct(value*(separator*value)^0)
466
467 function parsers.settings_to_array_with_repeat(str,expand) -- beware: "" => { }
468 if expand then
469 return lpegmatch(pattern_b,str) or { }
470 else
471 return lpegmatch(pattern_a,str) or { }
472 end
473 end
474
475 --
476
477 local value = lbrace * C((nobrace + nestedbraces)^0) * rbrace
478 local pattern = Ct((space + value)^0)
479
480 function parsers.arguments_to_table(str)
481 return lpegmatch(pattern,str)
482 end
483
484 -- temporary here (unoptimized)
485
486 function parsers.getparameters(self,class,parentclass,settings)
487 local sc = self[class]
488 if not sc then
489 sc = { }
490 self[class] = sc
491 if parentclass then
492 local sp = self[parentclass]
493 if not sp then
494 sp = { }
495 self[parentclass] = sp
496 end
497 setmetatableindex(sc,sp)
498 end
499 end
500 parsers.settings_to_hash(settings,sc)
501 end
502
503 function parsers.listitem(str)
504 return gmatch(str,"[^, ]+")
505 end
506
507 --
508
509 local pattern = Cs { "start",
510 start = V("one") + V("two") + V("three"),
511 rest = (Cc(",") * V("thousand"))^0 * (P(".") + endofstring) * anything^0,
512 thousand = digit * digit * digit,
513 one = digit * V("rest"),
514 two = digit * digit * V("rest"),
515 three = V("thousand") * V("rest"),
516 }
517
518 lpegpatterns.splitthousands = pattern -- maybe better in the parsers namespace ?
519
520 function parsers.splitthousands(str)
521 return lpegmatch(pattern,str) or str
522 end
523
524 -- print(parsers.splitthousands("11111111111.11"))
525
526 local optionalwhitespace = whitespace^0
527
528 lpegpatterns.words = Ct((Cs((1-punctuation-whitespace)^1) + anything)^1)
529 lpegpatterns.sentences = Ct((optionalwhitespace * Cs((1-period)^0 * period))^1)
530 lpegpatterns.paragraphs = Ct((optionalwhitespace * Cs((whitespace^1*endofstring/"" + 1 - (spacer^0*newline*newline))^1))^1)
531
532 -- local str = " Word1 word2. \n Word3 word4. \n\n Word5 word6.\n "
533 -- inspect(lpegmatch(lpegpatterns.paragraphs,str))
534 -- inspect(lpegmatch(lpegpatterns.sentences,str))
535 -- inspect(lpegmatch(lpegpatterns.words,str))
536
537 -- handy for k="v" [, ] k="v"
538
539 local dquote = P('"')
540 local equal = P('=')
541 local escape = P('\\')
542 local separator = S(' ,')
543
544 local key = C((1-equal)^1)
545 local value = dquote * C((1-dquote-escape*dquote)^0) * dquote
546
547 ----- pattern = Cf(Ct("") * Cg(key * equal * value) * separator^0,rawset)^0 * P(-1) -- was wrong
548 local pattern = Cf(Ct("") * (Cg(key * equal * value) * separator^0)^1,rawset)^0 * P(-1)
549
550 function parsers.keq_to_hash(str)
551 if str and str ~= "" then
552 return lpegmatch(pattern,str)
553 else
554 return { }
555 end
556 end
557
558 -- inspect(lpeg.match(pattern,[[key="value" foo="bar"]]))
559
560 local defaultspecification = { separator = ",", quote = '"' }
561
562 -- this version accepts multiple separators and quotes as used in the
563 -- database module
564
565 function parsers.csvsplitter(specification)
566 specification = specification and setmetatableindex(specification,defaultspecification) or defaultspecification
567 local separator = specification.separator
568 local quotechar = specification.quote
569 local numbers = specification.numbers
570 local separator = S(separator ~= "" and separator or ",")
571 local whatever = C((1 - separator - newline)^0)
572 if quotechar and quotechar ~= "" then
573 local quotedata = nil
574 for chr in gmatch(quotechar,".") do
575 local quotechar = P(chr)
576 local quoteitem = (1 - quotechar)^0
577 local quoteword = quotechar * (numbers and (quoteitem/tonumber) or C(quoteitem)) * quotechar
578 if quotedata then
579 quotedata = quotedata + quoteword
580 else
581 quotedata = quoteword
582 end
583 end
584 whatever = quotedata + whatever
585 end
586 local parser = Ct((Ct(whatever * (separator * whatever)^0) * S("\n\r")^1)^0 )
587 return function(data)
588 return lpegmatch(parser,data)
589 end
590 end
591
592 -- local crap = [[
593 -- first,second,third,fourth
594 -- "1","2","3","4"
595 -- "5","6","7","8"
596 -- ]]
597
598 -- local mycsvsplitter = parsers.csvsplitter { numbers = true }
599
600 -- local list = mycsvsplitter(crap) inspect(list)
601
602 -- and this is a slightly patched version of a version posted by Philipp Gesang
603
604 function parsers.rfc4180splitter(specification)
605 specification = specification and setmetatableindex(specification,defaultspecification) or defaultspecification
606 local numbers = specification.numbers
607 local separator = specification.separator --> rfc: COMMA
608 local quotechar = P(specification.quote) --> DQUOTE
609 local dquotechar = quotechar * quotechar --> 2DQUOTE
610 / specification.quote
611 local separator = S(separator ~= "" and separator or ",")
612 local whatever = (dquotechar + (1 - quotechar))^0
613 local escaped = quotechar
614 * (numbers and (whatever/tonumber) or Cs(whatever))
615 * quotechar
616 local non_escaped = C((1 - quotechar - newline - separator)^1)
617 local field = escaped + non_escaped + Cc("")
618 local record = Ct(field * (separator * field)^1)
619 local headerline = record * Cp()
620 local morerecords = (newline^(specification.strict and -1 or 1) * record)^0
621 local headeryes = Ct(morerecords)
622 local headernop = Ct(record * morerecords)
623 return function(data,getheader)
624 if getheader then
625 local header, position = lpegmatch(headerline,data)
626 local data = lpegmatch(headeryes,data,position)
627 return data, header
628 else
629 return lpegmatch(headernop,data)
630 end
631 end
632 end
633
634 -- local mycsvsplitter = parsers.rfc4180splitter { numbers = true }
635 --
636 -- local crap = [[
637 -- first,second,third,fourth
638 -- "1","2","3","4"
639 -- "a","b","c","d"
640 -- "foo","bar""baz","boogie","xyzzy"
641 -- ]]
642 --
643 -- local list, names = mycsvsplitter(crap,true) inspect(list) inspect(names)
644 -- local list, names = mycsvsplitter(crap) inspect(list) inspect(names)
645
646 local function ranger(first,last,n,action)
647 if not first then
648 -- forget about it
649 elseif last == true then
650 for i=first,n or first do
651 action(i)
652 end
653 elseif last then
654 for i=first,last do
655 action(i)
656 end
657 else
658 action(first)
659 end
660 end
661
662 local cardinal = (lpegpatterns.hexadecimal + lpegpatterns.cardinal) / tonumber
663 local spacers = lpegpatterns.spacer^0
664 local endofstring = lpegpatterns.endofstring
665
666 local stepper = spacers * ( cardinal * ( spacers * S(":-") * spacers * ( cardinal + Cc(true) ) + Cc(false) )
667 * Carg(1) * Carg(2) / ranger * S(", ")^0 )^1
668
669 local stepper = spacers * ( cardinal * ( spacers * S(":-") * spacers * ( cardinal + (P("*") + endofstring) * Cc(true) ) + Cc(false) )
670 * Carg(1) * Carg(2) / ranger * S(", ")^0 )^1 * endofstring -- we're sort of strict (could do without endofstring)
671
672 function parsers.stepper(str,n,action)
673 local ts = type(str)
674 if type(n) == "function" then
675 if ts == "number" then
676 n(str)
677 elseif ts == "table" then
678 for i=1,#str do
679 n(str[i])
680 end
681 else
682 lpegmatch(stepper,str,1,false,n or print)
683 end
684 elseif ts == "string" then
685 lpegmatch(stepper,str,1,n,action or print)
686 end
687 end
688
689 -- parsers.stepper("1,7-",9,function(i) print(">>>",i) end)
690 -- parsers.stepper("1-3,7,8,9")
691 -- parsers.stepper("1-3,6,7",function(i) print(">>>",i) end)
692 -- parsers.stepper(" 1 : 3, ,7 ")
693 -- parsers.stepper("1:4,9:13,24:*",30)
694 -- parsers.stepper(1,print)
695 -- parsers.stepper({1,3,4},print)
696
697 local pattern_math = Cs((P("%")/"\\percent " + P("^") * Cc("{") * lpegpatterns.integer * Cc("}") + anything)^0)
698 local pattern_text = Cs((P("%")/"\\percent " + (P("^")/"\\high") * Cc("{") * lpegpatterns.integer * Cc("}") + anything)^0)
699
700 patterns.unittotex = pattern
701
702 function parsers.unittotex(str,textmode)
703 return lpegmatch(textmode and pattern_text or pattern_math,str)
704 end
705
706 local pattern = Cs((P("^") / "<sup>" * lpegpatterns.integer * Cc("</sup>") + anything)^0)
707
708 function parsers.unittoxml(str)
709 return lpegmatch(pattern,str)
710 end
711
712 -- print(parsers.unittotex("10^-32 %"),utilities.parsers.unittoxml("10^32 %"))
713
714 local cache = { }
715 local spaces = lpegpatterns.space^0
716 local dummy = function() end
717
718 setmetatableindex(cache,function(t,k)
719 local separator = S(k) -- was P
720 local value = (1-separator)^0
721 local pattern = spaces * C(value) * separator^0 * Cp()
722 t[k] = pattern
723 return pattern
724 end)
725
726 local commalistiterator = cache[","]
727
728 function parsers.iterator(str,separator)
729 local n = #str
730 if n == 0 then
731 return dummy
732 else
733 local pattern = separator and cache[separator] or commalistiterator
734 local p = 1
735 return function()
736 if p <= n then
737 local s, e = lpegmatch(pattern,str,p)
738 if e then
739 p = e
740 return s
741 end
742 end
743 end
744 end
745 end
746
747 -- for s in parsers.iterator("a b c,b,c") do
748 -- print(s)
749 -- end
750
751 local function initialize(t,name)
752 local source = t[name]
753 if source then
754 local result = { }
755 for k, v in next, t[name] do
756 result[k] = v
757 end
758 return result
759 else
760 return { }
761 end
762 end
763
764 local function fetch(t,name)
765 return t[name] or { }
766 end
767
768 local function process(result,more)
769 for k, v in next, more do
770 result[k] = v
771 end
772 return result
773 end
774
775 local name = C((1-S(", "))^1)
776 local parser = (Carg(1) * name / initialize) * (S(", ")^1 * (Carg(1) * name / fetch))^0
777 local merge = Cf(parser,process)
778
779 function parsers.mergehashes(hash,list)
780 return lpegmatch(merge,list,1,hash)
781 end
782
783 -- local t = {
784 -- aa = { alpha = 1, beta = 2, gamma = 3, },
785 -- bb = { alpha = 4, beta = 5, delta = 6, },
786 -- cc = { epsilon = 3 },
787 -- }
788 --
789 -- inspect(parsers.mergehashes(t,"aa, bb, cc"))
790
791 function parsers.runtime(time)
792 if not time then
793 time = os.runtime()
794 end
795 local days = div(time,24*60*60)
796 time = mod(time,24*60*60)
797 local hours = div(time,60*60)
798 time = mod(time,60*60)
799 local minutes = div(time,60)
800 local seconds = mod(time,60)
801 return days, hours, minutes, seconds
802 end
803
804 --
805
806 local spacing = whitespace^0
807 local apply = P("->")
808 local method = C((1-apply)^1)
809 local token = lbrace * C((1-rbrace)^1) * rbrace + C(anything^1)
810
811 local pattern = spacing * (method * spacing * apply + Carg(1)) * spacing * token
812
813 function parsers.splitmethod(str,default)
814 if str then
815 return lpegmatch(pattern,str,1,default or false)
816 else
817 return default or false, ""
818 end
819 end
820
821 -- print(parsers.splitmethod(" foo -> {bar} "))
822 -- print(parsers.splitmethod("foo->{bar}"))
823 -- print(parsers.splitmethod("foo->bar"))
824 -- print(parsers.splitmethod("foo"))
825 -- print(parsers.splitmethod("{foo}"))
826 -- print(parsers.splitmethod())
827
828 local p_year = lpegpatterns.digit^4 / tonumber
829
830 local pattern = Cf( Ct("") *
831 (
832 ( Cg(Cc("year") * p_year)
833 * S("-/") * Cg(Cc("month") * cardinal)
834 * S("-/") * Cg(Cc("day") * cardinal)
835 ) +
836 ( Cg(Cc("day") * cardinal)
837 * S("-/") * Cg(Cc("month") * cardinal)
838 * S("-/") * Cg(Cc("year") * p_year)
839 ) +
840 ( Cg(Cc("year") * p_year)
841 * S("-/") * Cg(Cc("month") * cardinal)
842 ) +
843 ( Cg(Cc("month") * cardinal)
844 * S("-/") * Cg(Cc("year") * p_year)
845 )
846 )
847 * (
848 P(" ") * Cg(Cc("hour") * cardinal)
849 * P(":") * Cg(Cc("min") * cardinal)
850 * (P(":") * Cg(Cc("sec") * cardinal))^-1
851 + P(-1) )
852
853 , rawset)
854
855 lpegpatterns.splittime = pattern
856
857 function parsers.totime(str)
858 return lpegmatch(pattern,str)
859 end
860
861 -- inspect(parsers.totime("2019-03-05"))
862 -- inspect(parsers.totime("2019-03-05 12:12:12"))
863 -- print(os.time(parsers.totime("2019-03-05 12:12:12")))
864 -- print(os.time(parsers.totime("2019/03/05 12:12:12")))
865 -- print(os.time(parsers.totime("05-03-2019 12:12:12")))
866 -- print(os.time(parsers.totime("05/03/2019 12:12:12")))