Debian Codegraph @

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

raw
1
2 ---------------------------------------------------------
3 ----------------Auto generated code block----------------
4 ---------------------------------------------------------
5
6 do
7 local searchers = package.searchers or package.loaders
8 local origin_seacher = searchers[2]
9 searchers[2] = function(path)
10 local files =
11 {
12 ------------------------
13 -- Modules part begin --
14 ------------------------
15
16 ["pl.xml"] = function()
17 --------------------
18 -- Module: 'pl.xml'
19 --------------------
20 --- XML LOM Utilities.
21 --
22 -- This implements some useful things on [LOM](http://matthewwild.co.uk/projects/luaexpat/lom.html) documents, such as returned by `lxp.lom.parse`.
23 -- In particular, it can convert LOM back into XML text, with optional pretty-printing control.
24 -- It is based on stanza.lua from [Prosody](http://hg.prosody.im/trunk/file/4621c92d2368/util/stanza.lua)
25 --
26 -- > d = xml.parse "<nodes><node id='1'>alice</node></nodes>"
27 -- > = d
28 -- <nodes><node id='1'>alice</node></nodes>
29 -- > = xml.tostring(d,'',' ')
30 -- <nodes>
31 -- <node id='1'>alice</node>
32 -- </nodes>
33 --
34 -- Can be used as a lightweight one-stop-shop for simple XML processing; a simple XML parser is included
35 -- but the default is to use `lxp.lom` if it can be found.
36 -- <pre>
37 -- Prosody IM
38 -- Copyright (C) 2008-2010 Matthew Wild
39 -- Copyright (C) 2008-2010 Waqas Hussain--
40 -- classic Lua XML parser by Roberto Ierusalimschy.
41 -- modified to output LOM format.
42 -- http://lua-users.org/wiki/LuaXml
43 -- </pre>
44 -- See @{06-data.md.XML|the Guide}
45 --
46 -- Dependencies: `pl.utils`
47 --
48 -- Soft Dependencies: `lxp.lom` (fallback is to use basic Lua parser)
49 -- @module pl.xml
50
51 local utils = require 'pl.utils'
52 local split = utils.split
53 local t_insert = table.insert
54 local t_concat = table.concat
55 local t_remove = table.remove
56 local s_match = string.match
57 local tostring = tostring
58 local setmetatable = setmetatable
59 local getmetatable = getmetatable
60 local pairs = pairs
61 local ipairs = ipairs
62 local type = type
63 local next = next
64 local print = print
65 local unpack = utils.unpack
66 local s_gsub = string.gsub
67 local s_sub = string.sub
68 local s_find = string.find
69 local pcall = pcall
70 local require = require
71
72
73 utils.raise_deprecation {
74 source = "Penlight " .. utils._VERSION,
75 message = "the contents of module 'pl.xml' has been deprecated, please use a more specialized library instead",
76 version_removed = "2.0.0",
77 deprecated_after = "1.11.0",
78 no_trace = true,
79 }
80
81
82
83 local _M = {}
84 local Doc = { __type = "doc" };
85 Doc.__index = Doc;
86
87
88 local function is_text(s) return type(s) == 'string' end
89 local function is_tag(d) return type(d) == 'table' and is_text(d.tag) end
90
91
92
93 --- create a new document node.
94 -- @tparam string tag the tag name
95 -- @tparam[opt={}] table attr attributes (table of name-value pairs)
96 -- @return the Node object
97 -- @see xml.elem
98 -- @usage
99 -- local doc = xml.new("main", { hello = "world", answer = "42" })
100 -- print(doc) --> <main hello='world' answer='42'/>
101 function _M.new(tag, attr)
102 if type(tag) ~= "string" then
103 error("expected 'tag' to be a string value, got: " .. type(tag), 2)
104 end
105 attr = attr or {}
106 if type(attr) ~= "table" then
107 error("expected 'attr' to be a table value, got: " .. type(attr), 2)
108 end
109
110 local doc = { tag = tag, attr = attr, last_add = {}};
111 return setmetatable(doc, Doc);
112 end
113
114
115 --- parse an XML document. By default, this uses lxp.lom.parse, but
116 -- falls back to basic_parse, or if `use_basic` is truthy
117 -- @param text_or_filename file or string representation
118 -- @param is_file whether text_or_file is a file name or not
119 -- @param use_basic do a basic parse
120 -- @return a parsed LOM document with the document metatatables set
121 -- @return nil, error the error can either be a file error or a parse error
122 function _M.parse(text_or_filename, is_file, use_basic)
123 local parser,status,lom
124 if use_basic then
125 parser = _M.basic_parse
126 else
127 status,lom = pcall(require,'lxp.lom')
128 if not status then
129 parser = _M.basic_parse
130 else
131 parser = lom.parse
132 end
133 end
134
135 if is_file then
136 local text, err = utils.readfile(text_or_filename)
137 if not text then
138 return nil, err
139 end
140 text_or_filename = text
141 end
142
143 local doc, err = parser(text_or_filename)
144 if not doc then
145 return nil, err
146 end
147
148 if lom then
149 _M.walk(doc, false, function(_, d)
150 setmetatable(d, Doc)
151 end)
152 end
153 return doc
154 end
155
156
157 --- Create a Node with a set of children (text or Nodes) and attributes.
158 -- @tparam string tag a tag name
159 -- @tparam table|string items either a single child (text or Node), or a table where the hash
160 -- part is the attributes and the list part is the children (text or Nodes).
161 -- @return the new Node
162 -- @see xml.new
163 -- @see xml.tags
164 -- @usage
165 -- local doc = xml.elem("top", "hello world") -- <top>hello world</top>
166 -- local doc = xml.elem("main", xml.new("child")) -- <main><child/></main>
167 -- local doc = xml.elem("main", { "this ", "is ", "nice" }) -- <main>this is nice</main>
168 -- local doc = xml.elem("main", { xml.new "this",
169 -- xml.new "is",
170 -- xml.new "nice" }) -- <main><this/><is/><nice/></main>
171 -- local doc = xml.elem("main", { hello = "world" }) -- <main hello='world'/>
172 -- local doc = xml.elem("main", {
173 -- "prefix",
174 -- xml.elem("child", { "this ", "is ", "nice"}),
175 -- "postfix",
176 -- attrib = "value"
177 -- }) -- <main attrib='value'>prefix<child>this is nice</child>postfix</main>"
178 function _M.elem(tag, items)
179 local s = _M.new(tag)
180 if is_text(items) then items = {items} end
181 if is_tag(items) then
182 t_insert(s,items)
183 elseif type(items) == 'table' then
184 for k,v in pairs(items) do
185 if is_text(k) then
186 s.attr[k] = v
187 t_insert(s.attr,k)
188 else
189 s[k] = v
190 end
191 end
192 end
193 return s
194 end
195
196
197 --- given a list of names, return a number of element constructors.
198 -- If passing a comma-separated string, then whitespace surrounding the values
199 -- will be stripped.
200 --
201 -- The returned constructor functions are a shortcut to `xml.elem` where you
202 -- no longer provide the tag-name, but only the `items` table.
203 -- @tparam string|table list a list of names, or a comma-separated string.
204 -- @return (multiple) constructor functions; `function(items)`. For the `items`
205 -- parameter see `xml.elem`.
206 -- @see xml.elem
207 -- @usage
208 -- local new_parent, new_child = xml.tags 'mom, kid'
209 -- doc = new_parent {new_child 'Bob', new_child 'Annie'}
210 -- -- <mom><kid>Bob</kid><kid>Annie</kid></mom>
211 function _M.tags(list)
212 local ctors = {}
213 if is_text(list) then
214 list = split(list:match("^%s*(.-)%s*$"),'%s*,%s*')
215 end
216 for i,tag in ipairs(list) do
217 local function ctor(items)
218 return _M.elem(tag,items)
219 end
220 ctors[i] = ctor
221 end
222 return unpack(ctors)
223 end
224
225
226 --- Adds a document Node, at current position.
227 -- This updates the last inserted position to the new Node.
228 -- @tparam string tag the tag name
229 -- @tparam[opt={}] table attrs attributes (table of name-value pairs)
230 -- @return the current node (`self`)
231 -- @usage
232 -- local doc = xml.new("main")
233 -- doc:addtag("penlight", { hello = "world"})
234 -- doc:addtag("expat") -- added to 'penlight' since position moved
235 -- print(doc) --> <main><penlight hello='world'><expat/></penlight></main>
236 function Doc:addtag(tag, attrs)
237 local s = _M.new(tag, attrs)
238 self:add_child(s)
239 t_insert(self.last_add, s)
240 return self
241 end
242
243
244 --- Adds a text node, at current position.
245 -- @tparam string text a string
246 -- @return the current node (`self`)
247 -- @usage
248 -- local doc = xml.new("main")
249 -- doc:text("penlight")
250 -- doc:text("expat")
251 -- print(doc) --> <main><penlightexpat</main>
252 function Doc:text(text)
253 self:add_child(text)
254 return self
255 end
256
257
258 --- Moves current position up one level.
259 -- @return the current node (`self`)
260 function Doc:up()
261 t_remove(self.last_add)
262 return self
263 end
264
265
266 --- Resets current position to top level.
267 -- Resets to the `self` node.
268 -- @return the current node (`self`)
269 function Doc:reset()
270 local last_add = self.last_add
271 for i = 1,#last_add do
272 last_add[i] = nil
273 end
274 return self
275 end
276
277
278 --- Append a child to the current Node (ignoring current position).
279 -- @param child a child node (either text or a document)
280 -- @return the current node (`self`)
281 -- @usage
282 -- local doc = xml.new("main")
283 -- doc:add_direct_child("dog")
284 -- doc:add_direct_child(xml.new("child"))
285 -- doc:add_direct_child("cat")
286 -- print(doc) --> <main>dog<child/>cat</main>
287 function Doc:add_direct_child(child)
288 t_insert(self, child)
289 return self
290 end
291
292
293 --- Append a child at the current position (without changing position).
294 -- @param child a child node (either text or a document)
295 -- @return the current node (`self`)
296 -- @usage
297 -- local doc = xml.new("main")
298 -- doc:addtag("one")
299 -- doc:add_child(xml.new("item1"))
300 -- doc:add_child(xml.new("item2"))
301 -- doc:add_child(xml.new("item3"))
302 -- print(doc) --> <main><one><item1/><item2/><item3/></one></main>
303 function Doc:add_child(child)
304 (self.last_add[#self.last_add] or self):add_direct_child(child)
305 return self
306 end
307
308
309 --accessing attributes: useful not to have to expose implementation (attr)
310 --but also can allow attr to be nil in any future optimizations
311
312
313 --- Set attributes of a document node.
314 -- Will add/overwrite values, but will not remove existing ones.
315 -- Operates on the Node itself, will not take position into account.
316 -- @tparam table t a table containing attribute/value pairs
317 -- @return the current node (`self`)
318 function Doc:set_attribs(t)
319 -- TODO: keep array part in sync
320 for k,v in pairs(t) do
321 self.attr[k] = v
322 end
323 return self
324 end
325
326
327 --- Set a single attribute of a document node.
328 -- Operates on the Node itself, will not take position into account.
329 -- @param a attribute
330 -- @param v its value, pass in `nil` to delete the attribute
331 -- @return the current node (`self`)
332 function Doc:set_attrib(a,v)
333 -- TODO: keep array part in sync
334 self.attr[a] = v
335 return self
336 end
337
338
339 --- Gets the attributes of a document node.
340 -- Operates on the Node itself, will not take position into account.
341 -- @return table with attributes (attribute/value pairs)
342 function Doc:get_attribs()
343 return self.attr
344 end
345
346
347
348 local template_cache do
349 local templ_cache = {}
350
351 -- @param templ a template, a string being valid xml to be parsed, or a Node object
352 function template_cache(templ)
353 if is_text(templ) then
354 if templ_cache[templ] then
355 -- cache hit
356 return templ_cache[templ]
357
358 else
359 -- parse and cache
360 local ptempl, err = _M.parse(templ,false,true)
361 if not ptempl then
362 return nil, err
363 end
364 templ_cache[templ] = ptempl
365 return ptempl
366 end
367 end
368
369 if is_tag(templ) then
370 return templ
371 end
372
373 return nil, "template is not a document"
374 end
375 end
376
377
378 do
379 local function is_data(data)
380 return #data == 0 or type(data[1]) ~= 'table'
381 end
382
383
384 local function prepare_data(data)
385 -- a hack for ensuring that $1 maps to first element of data, etc.
386 -- Either this or could change the gsub call just below.
387 for i,v in ipairs(data) do
388 data[tostring(i)] = v
389 end
390 end
391
392 --- create a substituted copy of a document,
393 -- @param template may be a document or a string representation which will be parsed and cached
394 -- @param data a table of name-value pairs or a list of such tables
395 -- @return an XML document
396 function Doc.subst(template, data)
397 if type(data) ~= 'table' or not next(data) then
398 return nil, "data must be a non-empty table"
399 end
400
401 if is_data(data) then
402 prepare_data(data)
403 end
404
405 local templ, err = template_cache(template)
406 if err then
407 return nil, err
408 end
409
410 local function _subst(item)
411 return _M.clone(templ, function(s)
412 return s:gsub('%$(%w+)', item)
413 end)
414 end
415
416 if is_data(data) then
417 return _subst(data)
418 end
419
420 local list = {}
421 for _, item in ipairs(data) do
422 prepare_data(item)
423 t_insert(list, _subst(item))
424 end
425
426 if data.tag then
427 list = _M.elem(data.tag,list)
428 end
429 return list
430 end
431 end
432
433
434 --- Return the first child with a given tag name (non-recursive).
435 -- @param tag the tag name
436 -- @return the child Node found or `nil` if not found
437 function Doc:child_with_name(tag)
438 for _, child in ipairs(self) do
439 if child.tag == tag then
440 return child
441 end
442 end
443 end
444
445
446 do
447 -- @param self document node to traverse
448 -- @param tag tag-name to look for
449 -- @param list array table to add the matching ones to
450 -- @param recurse if truthy, recursively search the node
451 local function _children_with_name(self, tag, list, recurse)
452 -- TODO: protect against recursion
453 for _, child in ipairs(self) do
454 if type(child) == 'table' then
455 if child.tag == tag then
456 t_insert(list, child)
457 end
458 if recurse then
459 _children_with_name(child, tag, list, recurse)
460 end
461 end
462 end
463 end
464
465 --- Returns all elements in a document that have a given tag.
466 -- @tparam string tag a tag name
467 -- @tparam[opt=false] boolean dont_recurse optionally only return the immediate children with this tag name
468 -- @return a list of elements found, list will be empty if none was found.
469 function Doc:get_elements_with_name(tag, dont_recurse)
470 local res = {}
471 _children_with_name(self, tag, res, not dont_recurse)
472 return res
473 end
474 end
475
476
477
478 --- Iterator over all children of a document node, including text nodes.
479 -- This function is not recursive, so returns only direct child nodes.
480 -- @return iterator that returns a single Node per iteration.
481 function Doc:children()
482 local i = 0;
483 return function (a)
484 i = i + 1
485 return a[i];
486 end, self, i;
487 end
488
489
490 --- Return the first child element of a node, if it exists.
491 -- This will skip text nodes.
492 -- @return first child Node or `nil` if there is none.
493 function Doc:first_childtag()
494 if #self == 0 then
495 return
496 end
497 for _, t in ipairs(self) do
498 if is_tag(t) then
499 return t
500 end
501 end
502 end
503
504
505 --- Iterator that matches tag names, and a namespace (non-recursive).
506 -- @tparam[opt=nil] string tag tag names to return. Returns all tags if not provided.
507 -- @tparam[opt=nil] string xmlns the namespace value ('xmlns' attribute) to return. If not
508 -- provided will match all namespaces.
509 -- @return iterator that returns a single Node per iteration.
510 function Doc:matching_tags(tag, xmlns)
511 -- TODO: this doesn't make sense??? namespaces are not "xmnls", as matched below
512 -- but "xmlns:name"... so should be a string-prefix match if anything...
513 xmlns = xmlns or self.attr.xmlns;
514 local tags = self
515 local next_i = 1
516 local max_i = #tags
517 local node
518 return function ()
519 for i = next_i, max_i do
520 node = tags[i];
521 if (not tag or node.tag == tag) and
522 (not xmlns or xmlns == node.attr.xmlns) then
523 next_i = i + 1
524 return node
525 end
526 end
527 end, tags, next_i
528 end
529
530
531 --- Iterator over all child tags of a document node. This will skip over
532 -- text nodes.
533 -- @return iterator that returns a single Node per iteration.
534 function Doc:childtags()
535 local i = 0;
536 return function (a)
537 local v
538 repeat
539 i = i + 1
540 v = self[i]
541 if v and type(v) == 'table' then
542 return v
543 end
544 until not v
545 end, self[1], i;
546 end
547
548
549 --- Visit child Nodes of a node and call a function, possibly modifying the document.
550 -- Text elements will be skipped.
551 -- This is not recursive, so only direct children will be passed.
552 -- @tparam function callback a function with signature `function(node)`, passed the node.
553 -- The element will be updated with the returned value, or deleted if it returns `nil`.
554 function Doc:maptags(callback)
555 local i = 1;
556
557 while i <= #self do
558 if is_tag(self[i]) then
559 local ret = callback(self[i]);
560 if ret == nil then
561 -- remove it
562 t_remove(self, i);
563
564 else
565 -- update it
566 self[i] = ret;
567 i = i + 1;
568 end
569 else
570 i = i + 1
571 end
572 end
573
574 return self;
575 end
576
577
578 do
579 local escape_table = {
580 ["'"] = "&apos;",
581 ['"'] = "&quot;",
582 ["<"] = "&lt;",
583 [">"] = "&gt;",
584 ["&"] = "&amp;",
585 }
586
587 --- Escapes a string for safe use in xml.
588 -- Handles quotes(single+double), less-than, greater-than, and ampersand.
589 -- @tparam string str string value to escape
590 -- @return escaped string
591 -- @usage
592 -- local esc = xml.xml_escape([["'<>&]]) --> "&quot;&apos;&lt;&gt;&amp;"
593 function _M.xml_escape(str)
594 return (s_gsub(str, "['&<>\"]", escape_table))
595 end
596 end
597 local xml_escape = _M.xml_escape
598
599 do
600 local escape_table = {
601 quot = '"',
602 apos = "'",
603 lt = "<",
604 gt = ">",
605 amp = "&",
606 }
607
608 --- Unescapes a string from xml.
609 -- Handles quotes(single+double), less-than, greater-than, and ampersand.
610 -- @tparam string str string value to unescape
611 -- @return unescaped string
612 -- @usage
613 -- local unesc = xml.xml_escape("&quot;&apos;&lt;&gt;&amp;") --> [["'<>&]]
614 function _M.xml_unescape(str)
615 return (str:gsub( "&(%a+);", escape_table))
616 end
617 end
618 local xml_unescape = _M.xml_unescape
619
620 -- pretty printing
621 -- if indent, then put each new tag on its own line
622 -- if attr_indent, put each new attribute on its own line
623 local function _dostring(t, buf, parentns, block_indent, tag_indent, attr_indent)
624 local nsid = 0
625 local tag = t.tag
626
627 local lf = ""
628 if tag_indent then
629 lf = '\n'..block_indent
630 end
631
632 local alf = " "
633 if attr_indent then
634 alf = '\n'..block_indent..attr_indent
635 end
636
637 t_insert(buf, lf.."<"..tag)
638
639 local function write_attr(k,v)
640 if s_find(k, "\1", 1, true) then
641 nsid = nsid + 1
642 local ns, attrk = s_match(k, "^([^\1]*)\1?(.*)$")
643 t_insert(buf, " xmlns:ns"..nsid.."='"..xml_escape(ns).."' ".."ns"..nsid..":"..attrk.."='"..xml_escape(v).."'")
644
645 elseif not (k == "xmlns" and v == parentns) then
646 t_insert(buf, alf..k.."='"..xml_escape(v).."'");
647 end
648 end
649
650 -- it's useful for testing to have predictable attribute ordering, if available
651 if #t.attr > 0 then
652 -- TODO: the key-value list is leading, what if they are not in-sync
653 for _,k in ipairs(t.attr) do
654 write_attr(k,t.attr[k])
655 end
656 else
657 for k, v in pairs(t.attr) do
658 write_attr(k,v)
659 end
660 end
661
662 local len = #t
663 local has_children
664
665 if len == 0 then
666 t_insert(buf, attr_indent and '\n'..block_indent.."/>" or "/>")
667
668 else
669 t_insert(buf, ">");
670
671 for n = 1, len do
672 local child = t[n]
673
674 if child.tag then
675 has_children = true
676 _dostring(child, buf, t.attr.xmlns, block_indent and block_indent..tag_indent, tag_indent, attr_indent)
677
678 else
679 -- text element
680 t_insert(buf, xml_escape(child))
681 end
682 end
683
684 t_insert(buf, (has_children and lf or '').."</"..tag..">");
685 end
686 end
687
688 --- Function to pretty-print an XML document.
689 -- @param doc an XML document
690 -- @tparam[opt] string|int b_ind an initial block-indent (required when `t_ind` is set)
691 -- @tparam[opt] string|int t_ind an tag-indent for each level (required when `a_ind` is set)
692 -- @tparam[opt] string|int a_ind if given, indent each attribute pair and put on a separate line
693 -- @tparam[opt] string|bool xml_preface force prefacing with default or custom <?xml...>, if truthy then `&lt;?xml version='1.0'?&gt;` will be used as default.
694 -- @return a string representation
695 -- @see Doc:tostring
696 function _M.tostring(doc, b_ind, t_ind, a_ind, xml_preface)
697 local buf = {}
698
699 if type(b_ind) == "number" then b_ind = (" "):rep(b_ind) end
700 if type(t_ind) == "number" then t_ind = (" "):rep(t_ind) end
701 if type(a_ind) == "number" then a_ind = (" "):rep(a_ind) end
702
703 if xml_preface then
704 if type(xml_preface) == "string" then
705 buf[1] = xml_preface
706 else
707 buf[1] = "<?xml version='1.0'?>"
708 end
709 end
710
711 _dostring(doc, buf, nil, b_ind, t_ind, a_ind, xml_preface)
712
713 return t_concat(buf)
714 end
715
716
717 Doc.__tostring = _M.tostring
718
719
720 --- Method to pretty-print an XML document.
721 -- Invokes `xml.tostring`.
722 -- @tparam[opt] string|int b_ind an initial indent (required when `t_ind` is set)
723 -- @tparam[opt] string|int t_ind an indent for each level (required when `a_ind` is set)
724 -- @tparam[opt] string|int a_ind if given, indent each attribute pair and put on a separate line
725 -- @tparam[opt="&lt;?xml version='1.0'?&gt;"] string xml_preface force prefacing with default or custom <?xml...>
726 -- @return a string representation
727 -- @see xml.tostring
728 function Doc:tostring(b_ind, t_ind, a_ind, xml_preface)
729 return _M.tostring(self, b_ind, t_ind, a_ind, xml_preface)
730 end
731
732
733 --- get the full text value of an element.
734 -- @return a single string with all text elements concatenated
735 -- @usage
736 -- local doc = xml.new("main")
737 -- doc:text("one")
738 -- doc:add_child(xml.elem "two")
739 -- doc:text("three")
740 --
741 -- local t = doc:get_text() --> "onethree"
742 function Doc:get_text()
743 local res = {}
744 for i,el in ipairs(self) do
745 if is_text(el) then t_insert(res,el) end
746 end
747 return t_concat(res);
748 end
749
750
751 do
752 local function _copy(object, kind, parent, strsubst, lookup_table)
753 if type(object) ~= "table" then
754 if strsubst and is_text(object) then
755 return strsubst(object, kind, parent)
756 else
757 return object
758 end
759 end
760
761 if lookup_table[object] then
762 error("recursion detected")
763 end
764 lookup_table[object] = true
765
766 local new_table = {}
767 lookup_table[object] = new_table
768
769 local tag = object.tag
770 new_table.tag = _copy(tag, '*TAG', parent, strsubst, lookup_table)
771
772 if object.attr then
773 local res = {}
774 for attr, value in pairs(object.attr) do
775 if type(attr) == "string" then
776 res[attr] = _copy(value, attr, object, strsubst, lookup_table)
777 end
778 end
779 new_table.attr = res
780 end
781
782 for index = 1, #object do
783 local v = _copy(object[index], '*TEXT', object, strsubst, lookup_table)
784 t_insert(new_table,v)
785 end
786
787 return setmetatable(new_table, getmetatable(object))
788 end
789
790 --- Returns a copy of a document.
791 -- The `strsubst` parameter is a callback with signature `function(object, kind, parent)`.
792 --
793 -- Param `kind` has the following values, and parameters:
794 --
795 -- - `"*TAG"`: `object` is the tag-name, `parent` is the Node object. Returns the new tag name.
796 --
797 -- - `"*TEXT"`: `object` is the text-element, `parent` is the Node object. Returns the new text value.
798 --
799 -- - other strings not prefixed with `*`: `kind` is the attribute name, `object` is the
800 -- attribute value, `parent` is the Node object. Returns the new attribute value.
801 --
802 -- @tparam Node|string doc a Node object or string (text node)
803 -- @tparam[opt] function strsubst an optional function for handling string copying
804 -- which could do substitution, etc.
805 -- @return copy of the document
806 -- @see Doc:filter
807 function _M.clone(doc, strsubst)
808 return _copy(doc, nil, nil, strsubst, {})
809 end
810 end
811
812
813 --- Returns a copy of a document.
814 -- This is the method version of `xml.clone`.
815 -- @see xml.clone
816 -- @name Doc:filter
817 -- @tparam[opt] function strsubst an optional function for handling string copying
818 Doc.filter = _M.clone -- also available as method
819
820 do
821 local function _compare(t1, t2, recurse_check)
822
823 local ty1 = type(t1)
824 local ty2 = type(t2)
825
826 if ty1 ~= ty2 then
827 return false, 'type mismatch'
828 end
829
830 if ty1 == 'string' then
831 if t1 == t2 then
832 return true
833 else
834 return false, 'text '..t1..' ~= text '..t2
835 end
836 end
837
838 if ty1 ~= 'table' or ty2 ~= 'table' then
839 return false, 'not a document'
840 end
841
842 if recurse_check[t1] then
843 return false, "recursive document"
844 end
845 recurse_check[t1] = true
846
847 if t1.tag ~= t2.tag then
848 return false, 'tag '..t1.tag..' ~= tag '..t2.tag
849 end
850
851 if #t1 ~= #t2 then
852 return false, 'size '..#t1..' ~= size '..#t2..' for tag '..t1.tag
853 end
854
855 -- compare attributes
856 for k,v in pairs(t1.attr) do
857 local t2_value = t2.attr[k]
858 if type(k) == "string" then
859 if t2_value ~= v then return false, 'mismatch attrib' end
860 else
861 if t2_value ~= nil and t2_value ~= v then return false, "mismatch attrib order" end
862 end
863 end
864 for k,v in pairs(t2.attr) do
865 local t1_value = t1.attr[k]
866 if type(k) == "string" then
867 if t1_value ~= v then return false, 'mismatch attrib' end
868 else
869 if t1_value ~= nil and t1_value ~= v then return false, "mismatch attrib order" end
870 end
871 end
872
873 -- compare children
874 for i = 1, #t1 do
875 local ok, err = _compare(t1[i], t2[i], recurse_check)
876 if not ok then
877 return ok, err
878 end
879 end
880 return true
881 end
882
883 --- Compare two documents or elements.
884 -- Equality is based on tag, child nodes (text and tags), attributes and order
885 -- of those (order only fails if both are given, and not equal).
886 -- @tparam Node|string t1 a Node object or string (text node)
887 -- @tparam Node|string t2 a Node object or string (text node)
888 -- @treturn boolean `true` when the Nodes are equal.
889 function _M.compare(t1,t2)
890 return _compare(t1, t2, {})
891 end
892 end
893
894
895 --- is this value a document element?
896 -- @param d any value
897 -- @treturn boolean `true` if it is a `table` with property `tag` being a string value.
898 -- @name is_tag
899 _M.is_tag = is_tag
900
901
902 do
903 local function _walk(doc, depth_first, operation, recurse_check)
904 if not depth_first then operation(doc.tag, doc) end
905 for _,d in ipairs(doc) do
906 if is_tag(d) then
907 assert(not recurse_check[d], "recursion detected")
908 recurse_check[d] = true
909 _walk(d, depth_first, operation, recurse_check)
910 end
911 end
912 if depth_first then operation(doc.tag, doc) end
913 end
914
915 --- Calls a function recursively over Nodes in the document.
916 -- Will only call on tags, it will skip text nodes.
917 -- The function signature for `operation` is `function(tag_name, Node)`.
918 -- @tparam Node|string doc a Node object or string (text node)
919 -- @tparam boolean depth_first visit child nodes first, then the current node
920 -- @tparam function operation a function which will receive the current tag name and current node.
921 function _M.walk(doc, depth_first, operation)
922 return _walk(doc, depth_first, operation, {})
923 end
924 end
925
926
927 local html_empty_elements = { --lists all HTML empty (void) elements
928 br = true,
929 img = true,
930 meta = true,
931 frame = true,
932 area = true,
933 hr = true,
934 base = true,
935 col = true,
936 link = true,
937 input = true,
938 option = true,
939 param = true,
940 isindex = true,
941 embed = true,
942 }
943
944 --- Parse a well-formed HTML file as a string.
945 -- Tags are case-insensitive, DOCTYPE is ignored, and empty elements can be .. empty.
946 -- @param s the HTML
947 function _M.parsehtml(s)
948 return _M.basic_parse(s,false,true)
949 end
950
951 --- Parse a simple XML document using a pure Lua parser based on Robero Ierusalimschy's original version.
952 -- @param s the XML document to be parsed.
953 -- @param all_text if true, preserves all whitespace. Otherwise only text containing non-whitespace is included.
954 -- @param html if true, uses relaxed HTML rules for parsing
955 function _M.basic_parse(s, all_text, html)
956 local stack = {}
957 local top = {}
958
959 local function parseargs(s)
960 local arg = {}
961 s:gsub("([%w:%-_]+)%s*=%s*([\"'])(.-)%2", function (w, _, a)
962 if html then w = w:lower() end
963 arg[w] = xml_unescape(a)
964 end)
965 if html then
966 s:gsub("([%w:%-_]+)%s*=%s*([^\"']+)%s*", function (w, a)
967 w = w:lower()
968 arg[w] = xml_unescape(a)
969 end)
970 end
971 return arg
972 end
973
974 t_insert(stack, top)
975 local ni,c,label,xarg, empty, _, istart
976 local i = 1
977 local j
978 -- we're not interested in <?xml version="1.0"?>
979 _,istart = s_find(s,'^%s*<%?[^%?]+%?>%s*')
980 if not istart then -- or <!DOCTYPE ...>
981 _,istart = s_find(s,'^%s*<!DOCTYPE.->%s*')
982 end
983 if istart then i = istart+1 end
984 while true do
985 ni,j,c,label,xarg, empty = s_find(s, "<([%/!]?)([%w:%-_]+)(.-)(%/?)>", i)
986 if not ni then break end
987 if c == "!" then -- comment
988 -- case where there's no space inside comment
989 if not (label:match '%-%-$' and xarg == '') then
990 if xarg:match '%-%-$' then -- we've grabbed it all
991 j = j - 2
992 end
993 -- match end of comment
994 _,j = s_find(s, "-->", j, true)
995 end
996 else
997 local text = s_sub(s, i, ni-1)
998 if html then
999 label = label:lower()
1000 if html_empty_elements[label] then empty = "/" end
1001 end
1002 if all_text or not s_find(text, "^%s*$") then
1003 t_insert(top, xml_unescape(text))
1004 end
1005 if empty == "/" then -- empty element tag
1006 t_insert(top, setmetatable({tag=label, attr=parseargs(xarg), empty=1},Doc))
1007 elseif c == "" then -- start tag
1008 top = setmetatable({tag=label, attr=parseargs(xarg)},Doc)
1009 t_insert(stack, top) -- new level
1010 else -- end tag
1011 local toclose = t_remove(stack) -- remove top
1012 top = stack[#stack]
1013 if #stack < 1 then
1014 error("nothing to close with "..label..':'..text)
1015 end
1016 if toclose.tag ~= label then
1017 error("trying to close "..toclose.tag.." with "..label.." "..text)
1018 end
1019 t_insert(top, toclose)
1020 end
1021 end
1022 i = j+1
1023 end
1024 local text = s_sub(s, i)
1025 if all_text or not s_find(text, "^%s*$") then
1026 t_insert(stack[#stack], xml_unescape(text))
1027 end
1028 if #stack > 1 then
1029 error("unclosed "..stack[#stack].tag)
1030 end
1031 local res = stack[1]
1032 return is_text(res[1]) and res[2] or res[1]
1033 end
1034
1035 do
1036 local match do
1037
1038 local function empty(attr) return not attr or not next(attr) end
1039
1040 local append_capture do
1041 -- returns the key,value pair from a table if it has exactly one entry
1042 local function has_one_element(t)
1043 local key,value = next(t)
1044 if next(t,key) ~= nil then return false end
1045 return key,value
1046 end
1047
1048 function append_capture(res,tbl)
1049 if not empty(tbl) then -- no point in capturing empty tables...
1050 local key
1051 if tbl._ then -- if $_ was set then it is meant as the top-level key for the captured table
1052 key = tbl._
1053 tbl._ = nil
1054 if empty(tbl) then return end
1055 end
1056 -- a table with only one pair {[0]=value} shall be reduced to that value
1057 local numkey,val = has_one_element(tbl)
1058 if numkey == 0 then tbl = val end
1059 if key then
1060 res[key] = tbl
1061 else -- otherwise, we append the captured table
1062 t_insert(res,tbl)
1063 end
1064 end
1065 end
1066 end
1067
1068 local function make_number(pat)
1069 if pat:find '^%d+$' then -- $1 etc means use this as an array location
1070 pat = tonumber(pat)
1071 end
1072 return pat
1073 end
1074
1075 local function capture_attrib(res,pat,value)
1076 pat = make_number(pat:sub(2))
1077 res[pat] = value
1078 return true
1079 end
1080
1081 function match(d,pat,res,keep_going)
1082 local ret = true
1083 if d == nil then d = '' end --return false end
1084 -- attribute string matching is straight equality, except if the pattern is a $ capture,
1085 -- which always succeeds.
1086 if is_text(d) then
1087 if not is_text(pat) then return false end
1088 if _M.debug then print(d,pat) end
1089 if pat:find '^%$' then
1090 return capture_attrib(res,pat,d)
1091 else
1092 return d == pat
1093 end
1094 else
1095 if _M.debug then print(d.tag,pat.tag) end
1096 -- this is an element node. For a match to succeed, the attributes must
1097 -- match as well.
1098 -- a tagname in the pattern ending with '-' is a wildcard and matches like an attribute
1099 local tagpat = pat.tag:match '^(.-)%-$'
1100 if tagpat then
1101 tagpat = make_number(tagpat)
1102 res[tagpat] = d.tag
1103 end
1104 if d.tag == pat.tag or tagpat then
1105
1106 if not empty(pat.attr) then
1107 if empty(d.attr) then ret = false
1108 else
1109 for prop,pval in pairs(pat.attr) do
1110 local dval = d.attr[prop]
1111 if not match(dval,pval,res) then ret = false; break end
1112 end
1113 end
1114 end
1115 -- the pattern may have child nodes. We match partially, so that {P1,P2} shall match {X,P1,X,X,P2,..}
1116 if ret and #pat > 0 then
1117 local i,j = 1,1
1118 local function next_elem()
1119 j = j + 1 -- next child element of data
1120 if is_text(d[j]) then j = j + 1 end
1121 return j <= #d
1122 end
1123 repeat
1124 local p = pat[i]
1125 -- repeated {{<...>}} patterns shall match one or more elements
1126 -- so e.g. {P+} will match {X,X,P,P,X,P,X,X,X}
1127 if is_tag(p) and p.repeated then
1128 local found
1129 repeat
1130 local tbl = {}
1131 ret = match(d[j],p,tbl,false)
1132 if ret then
1133 found = false --true
1134 append_capture(res,tbl)
1135 end
1136 until not next_elem() or (found and not ret)
1137 i = i + 1
1138 else
1139 ret = match(d[j],p,res,false)
1140 if ret then i = i + 1 end
1141 end
1142 until not next_elem() or i > #pat -- run out of elements or patterns to match
1143 -- if every element in our pattern matched ok, then it's been a successful match
1144 if i > #pat then return true end
1145 end
1146 if ret then return true end
1147 else
1148 ret = false
1149 end
1150 -- keep going anyway - look at the children!
1151 if keep_going then
1152 for child in d:childtags() do
1153 ret = match(child,pat,res,keep_going)
1154 if ret then break end
1155 end
1156 end
1157 end
1158 return ret
1159 end
1160 end
1161
1162 --- does something...
1163 function Doc:match(pat)
1164 local err
1165 pat,err = template_cache(pat)
1166 if not pat then return nil, err end
1167 _M.walk(pat,false,function(_,d)
1168 if is_text(d[1]) and is_tag(d[2]) and is_text(d[3]) and
1169 d[1]:find '%s*{{' and d[3]:find '}}%s*' then
1170 t_remove(d,1)
1171 t_remove(d,2)
1172 d[1].repeated = true
1173 end
1174 end)
1175
1176 local res = {}
1177 local ret = match(self,pat,res,true)
1178 return res,ret
1179 end
1180 end
1181
1182
1183 return _M
1184
1185
1186 end,
1187
1188 ["pl.app"] = function()
1189 --------------------
1190 -- Module: 'pl.app'
1191 --------------------
1192 --- Application support functions.
1193 -- See @{01-introduction.md.Application_Support|the Guide}
1194 --
1195 -- Dependencies: `pl.utils`, `pl.path`
1196 -- @module pl.app
1197
1198 local io,package,require = _G.io, _G.package, _G.require
1199 local utils = require 'pl.utils'
1200 local path = require 'pl.path'
1201
1202 local app = {}
1203
1204 --- return the name of the current script running.
1205 -- The name will be the name as passed on the command line
1206 -- @return string filename
1207 function app.script_name()
1208 if _G.arg and _G.arg[0] then
1209 return _G.arg[0]
1210 end
1211 return utils.raise("No script name found")
1212 end
1213
1214 --- prefixes the current script's path to the Lua module path.
1215 -- Applies to both the source and the binary module paths. It makes it easy for
1216 -- the main file of a multi-file program to access its modules in the same directory.
1217 -- `base` allows these modules to be put in a specified subdirectory, to allow for
1218 -- cleaner deployment and resolve potential conflicts between a script name and its
1219 -- library directory.
1220 --
1221 -- Note: the path is prefixed, so it is searched first when requiring modules.
1222 -- @string base optional base directory (absolute, or relative path).
1223 -- @bool nofollow always use the invocation's directory, even if the invoked file is a symlink
1224 -- @treturn string the current script's path with a trailing slash
1225 function app.require_here (base, nofollow)
1226 local p = app.script_name()
1227 if not path.isabs(p) then
1228 p = path.join(path.currentdir(),p)
1229 end
1230 if not nofollow then
1231 local t = path.link_attrib(p)
1232 if t and t.mode == 'link' then
1233 t = t.target
1234 if not path.isabs(t) then
1235 t = path.join(path.dirname(p), t)
1236 end
1237 p = t
1238 end
1239 end
1240 p = path.normpath(path.dirname(p))
1241 if p:sub(-1,-1) ~= path.sep then
1242 p = p..path.sep
1243 end
1244 if base then
1245 if path.is_windows then
1246 base = base:gsub('/','\\')
1247 end
1248 if path.isabs(base) then
1249 p = base .. path.sep
1250 else
1251 p = p..base..path.sep
1252 end
1253 end
1254 local so_ext = path.is_windows and 'dll' or 'so'
1255 local lsep = package.path:find '^;' and '' or ';'
1256 local csep = package.cpath:find '^;' and '' or ';'
1257 package.path = ('%s?.lua;%s?%sinit.lua%s%s'):format(p,p,path.sep,lsep,package.path)
1258 package.cpath = ('%s?.%s%s%s'):format(p,so_ext,csep,package.cpath)
1259 return p
1260 end
1261
1262 --- return a suitable path for files private to this application.
1263 -- These will look like '~/.SNAME/file', with '~' as with expanduser and
1264 -- SNAME is the name of the script without .lua extension.
1265 -- If the directory does not exist, it will be created.
1266 -- @string file a filename (w/out path)
1267 -- @return a full pathname, or nil
1268 -- @return cannot create directory error
1269 -- @usage
1270 -- -- when run from a script called 'testapp' (on Windows):
1271 -- local app = require 'pl.app'
1272 -- print(app.appfile 'test.txt')
1273 -- -- C:\Documents and Settings\steve\.testapp\test.txt
1274 function app.appfile(file)
1275 local sfullname, err = app.script_name()
1276 if not sfullname then return utils.raise(err) end
1277 local sname = path.basename(sfullname)
1278 local name = path.splitext(sname)
1279 local dir = path.join(path.expanduser('~'),'.'..name)
1280 if not path.isdir(dir) then
1281 local ret = path.mkdir(dir)
1282 if not ret then return utils.raise('cannot create '..dir) end
1283 end
1284 return path.join(dir,file)
1285 end
1286
1287 --- return string indicating operating system.
1288 -- @return 'Windows','OSX' or whatever uname returns (e.g. 'Linux')
1289 function app.platform()
1290 if path.is_windows then
1291 return 'Windows'
1292 else
1293 local f = io.popen('uname')
1294 local res = f:read()
1295 if res == 'Darwin' then res = 'OSX' end
1296 f:close()
1297 return res
1298 end
1299 end
1300
1301 --- return the full command-line used to invoke this script.
1302 -- It will not include the scriptname itself, see `app.script_name`.
1303 -- @return command-line
1304 -- @return name of Lua program used
1305 -- @usage
1306 -- -- execute: lua -lluacov -e 'print(_VERSION)' myscript.lua
1307 --
1308 -- -- myscript.lua
1309 -- print(require("pl.app").lua()) --> "lua -lluacov -e 'print(_VERSION)'", "lua"
1310 function app.lua()
1311 local args = _G.arg
1312 if not args then
1313 return utils.raise "not in a main program"
1314 end
1315
1316 local cmd = {}
1317 local i = -1
1318 while true do
1319 table.insert(cmd, 1, args[i])
1320 if not args[i-1] then
1321 return utils.quote_arg(cmd), args[i]
1322 end
1323 i = i - 1
1324 end
1325 end
1326
1327 --- parse command-line arguments into flags and parameters.
1328 -- Understands GNU-style command-line flags; short (`-f`) and long (`--flag`).
1329 --
1330 -- These may be given a value with either '=' or ':' (`-k:2`,`--alpha=3.2`,`-n2`),
1331 -- a number value can be given without a space. If the flag is marked
1332 -- as having a value, then a space-separated value is also accepted (`-i hello`),
1333 -- see the `flags_with_values` argument).
1334 --
1335 -- Multiple short args can be combined like so: ( `-abcd`).
1336 --
1337 -- When specifying the `flags_valid` parameter, its contents can also contain
1338 -- aliases, to convert short/long flags to the same output name. See the
1339 -- example below.
1340 --
1341 -- Note: if a flag is repeated, the last value wins.
1342 -- @tparam {string} args an array of strings (default is the global `arg`)
1343 -- @tab flags_with_values any flags that take values, either list or hash
1344 -- table e.g. `{ out=true }` or `{ "out" }`.
1345 -- @tab flags_valid (optional) flags that are valid, either list or hashtable.
1346 -- If not given, everything
1347 -- will be accepted(everything in `flags_with_values` will automatically be allowed)
1348 -- @return a table of flags (flag=value pairs)
1349 -- @return an array of parameters
1350 -- @raise if args is nil, then the global `args` must be available!
1351 -- @usage
1352 -- -- Simple form:
1353 -- local flags, params = app.parse_args(nil,
1354 -- { "hello", "world" }, -- list of flags taking values
1355 -- { "l", "a", "b"}) -- list of allowed flags (value ones will be added)
1356 --
1357 -- -- More complex example using aliases:
1358 -- local valid = {
1359 -- long = "l", -- if 'l' is specified, it is reported as 'long'
1360 -- new = { "n", "old" }, -- here both 'n' and 'old' will go into 'new'
1361 -- }
1362 -- local values = {
1363 -- "value", -- will automatically be added to the allowed set of flags
1364 -- "new", -- will mark 'n' and 'old' as requiring a value as well
1365 -- }
1366 -- local flags, params = app.parse_args(nil, values, valid)
1367 --
1368 -- -- command: myapp.lua -l --old:hello --value world param1 param2
1369 -- -- will yield:
1370 -- flags = {
1371 -- long = true, -- input from 'l'
1372 -- new = "hello", -- input from 'old'
1373 -- value = "world", -- allowed because it was in 'values', note: space separated!
1374 -- }
1375 -- params = {
1376 -- [1] = "param1"
1377 -- [2] = "param2"
1378 -- }
1379 function app.parse_args (args,flags_with_values, flags_valid)
1380 if not args then
1381 args = _G.arg
1382 if not args then utils.raise "Not in a main program: 'arg' not found" end
1383 end
1384
1385 local with_values = {}
1386 for k,v in pairs(flags_with_values or {}) do
1387 if type(k) == "number" then
1388 k = v
1389 end
1390 with_values[k] = true
1391 end
1392
1393 local valid
1394 if not flags_valid then
1395 -- if no allowed flags provided, we create a table that always returns
1396 -- the keyname, no matter what you look up
1397 valid = setmetatable({},{ __index = function(_, key) return key end })
1398 else
1399 valid = {}
1400 for k,aliases in pairs(flags_valid) do
1401 if type(k) == "number" then -- array/list entry
1402 k = aliases
1403 end
1404 if type(aliases) == "string" then -- single alias
1405 aliases = { aliases }
1406 end
1407 if type(aliases) == "table" then -- list of aliases
1408 -- it's the alternate name, so add the proper mappings
1409 for i, alias in ipairs(aliases) do
1410 valid[alias] = k
1411 end
1412 end
1413 valid[k] = k
1414 end
1415 do
1416 local new_with_values = {} -- needed to prevent "invalid key to 'next'" error
1417 for k,v in pairs(with_values) do
1418 if not valid[k] then
1419 valid[k] = k -- add the with_value entry as a valid one
1420 new_with_values[k] = true
1421 else
1422 new_with_values[valid[k]] = true --set, but by its alias
1423 end
1424 end
1425 with_values = new_with_values
1426 end
1427 end
1428
1429 -- now check that all flags with values are reported as such under all
1430 -- of their aliases
1431 for k, main_alias in pairs(valid) do
1432 if with_values[main_alias] then
1433 with_values[k] = true
1434 end
1435 end
1436
1437 local _args = {}
1438 local flags = {}
1439 local i = 1
1440 while i <= #args do
1441 local a = args[i]
1442 local v = a:match('^-(.+)')
1443 local is_long
1444 if not v then
1445 -- we have a parameter
1446 _args[#_args+1] = a
1447 else
1448 -- it's a flag
1449 if v:find '^-' then
1450 is_long = true
1451 v = v:sub(2)
1452 end
1453 if with_values[v] then
1454 if i == #args or args[i+1]:find '^-' then
1455 return utils.raise ("no value for '"..v.."'")
1456 end
1457 flags[valid[v]] = args[i+1]
1458 i = i + 1
1459 else
1460 -- a value can also be indicated with = or :
1461 local var,val = utils.splitv (v,'[=:]', false, 2)
1462 var = var or v
1463 val = val or true
1464 if not is_long then
1465 if #var > 1 then
1466 if var:find '.%d+' then -- short flag, number value
1467 val = var:sub(2)
1468 var = var:sub(1,1)
1469 else -- multiple short flags
1470 for i = 1,#var do
1471 local f = var:sub(i,i)
1472 if not valid[f] then
1473 return utils.raise("unknown flag '"..f.."'")
1474 else
1475 f = valid[f]
1476 end
1477 flags[f] = true
1478 end
1479 val = nil -- prevents use of var as a flag below
1480 end
1481 else -- single short flag (can have value, defaults to true)
1482 val = val or true
1483 end
1484 end
1485 if val then
1486 if not valid[var] then
1487 return utils.raise("unknown flag '"..var.."'")
1488 else
1489 var = valid[var]
1490 end
1491 flags[var] = val
1492 end
1493 end
1494 end
1495 i = i + 1
1496 end
1497 return flags,_args
1498 end
1499
1500 return app
1501
1502 end,
1503
1504 ["pl.array2d"] = function()
1505 --------------------
1506 -- Module: 'pl.array2d'
1507 --------------------
1508 --- Operations on two-dimensional arrays.
1509 -- See @{02-arrays.md.Operations_on_two_dimensional_tables|The Guide}
1510 --
1511 -- The size of the arrays is determined by using the length operator `#` hence
1512 -- the module is not `nil` safe, and the usual precautions apply.
1513 --
1514 -- Note: all functions taking `i1,j1,i2,j2` as arguments will normalize the
1515 -- arguments using `default_range`.
1516 --
1517 -- Dependencies: `pl.utils`, `pl.tablex`, `pl.types`
1518 -- @module pl.array2d
1519
1520 local tonumber,tostring,io,ipairs,string,table =
1521 _G.tonumber,_G.tostring,_G.io,_G.ipairs,_G.string,_G.table
1522 local setmetatable,getmetatable = setmetatable,getmetatable
1523
1524 local tablex = require 'pl.tablex'
1525 local utils = require 'pl.utils'
1526 local types = require 'pl.types'
1527 local imap,tmap,reduce,keys,tmap2,tset,index_by = tablex.imap,tablex.map,tablex.reduce,tablex.keys,tablex.map2,tablex.set,tablex.index_by
1528 local remove = table.remove
1529 local splitv,fprintf,assert_arg = utils.splitv,utils.fprintf,utils.assert_arg
1530 local byte = string.byte
1531 local stdout = io.stdout
1532 local min = math.min
1533
1534
1535 local array2d = {}
1536
1537 local function obj (int,out)
1538 local mt = getmetatable(int)
1539 if mt then
1540 setmetatable(out,mt)
1541 end
1542 return out
1543 end
1544
1545 local function makelist (res)
1546 return setmetatable(res, require('pl.List'))
1547 end
1548
1549 --- return the row and column size.
1550 -- Size is calculated using the Lua length operator #, so usual precautions
1551 -- regarding `nil` values apply.
1552 -- @array2d a a 2d array
1553 -- @treturn int number of rows (`#a`)
1554 -- @treturn int number of cols (`#a[1]`)
1555 function array2d.size (a)
1556 assert_arg(1,a,'table')
1557 return #a,#a[1]
1558 end
1559
1560 do
1561 local function index (t,k)
1562 return t[k]
1563 end
1564
1565 --- extract a column from the 2D array.
1566 -- @array2d a 2d array
1567 -- @param j column index
1568 -- @return 1d array
1569 function array2d.column (a,j)
1570 assert_arg(1,a,'table')
1571 return makelist(imap(index,a,j))
1572 end
1573 end
1574 local column = array2d.column
1575
1576 --- extract a row from the 2D array.
1577 -- Added in line with `column`, for read-only purposes directly
1578 -- accessing a[i] is more performant.
1579 -- @array2d a 2d array
1580 -- @param i row index
1581 -- @return 1d array (copy of the row)
1582 function array2d.row(a,i)
1583 assert_arg(1,a,'table')
1584 local row = a[i]
1585 local r = {}
1586 for n,v in ipairs(row) do
1587 r[n] = v
1588 end
1589 return makelist(r)
1590 end
1591
1592 --- map a function over a 2D array
1593 -- @func f a function of at least one argument
1594 -- @array2d a 2d array
1595 -- @param arg an optional extra argument to be passed to the function.
1596 -- @return 2d array
1597 function array2d.map (f,a,arg)
1598 assert_arg(2,a,'table')
1599 f = utils.function_arg(1,f)
1600 return obj(a,imap(function(row) return imap(f,row,arg) end, a))
1601 end
1602
1603 --- reduce the rows using a function.
1604 -- @func f a binary function
1605 -- @array2d a 2d array
1606 -- @return 1d array
1607 -- @see pl.tablex.reduce
1608 function array2d.reduce_rows (f,a)
1609 assert_arg(1,a,'table')
1610 return tmap(function(row) return reduce(f,row) end, a)
1611 end
1612
1613 --- reduce the columns using a function.
1614 -- @func f a binary function
1615 -- @array2d a 2d array
1616 -- @return 1d array
1617 -- @see pl.tablex.reduce
1618 function array2d.reduce_cols (f,a)
1619 assert_arg(1,a,'table')
1620 return tmap(function(c) return reduce(f,column(a,c)) end, keys(a[1]))
1621 end
1622
1623 --- reduce a 2D array into a scalar, using two operations.
1624 -- @func opc operation to reduce the final result
1625 -- @func opr operation to reduce the rows
1626 -- @param a 2D array
1627 function array2d.reduce2 (opc,opr,a)
1628 assert_arg(3,a,'table')
1629 local tmp = array2d.reduce_rows(opr,a)
1630 return reduce(opc,tmp)
1631 end
1632
1633 --- map a function over two arrays.
1634 -- They can be both or either 2D arrays
1635 -- @func f function of at least two arguments
1636 -- @int ad order of first array (`1` if `a` is a list/array, `2` if it is a 2d array)
1637 -- @int bd order of second array (`1` if `b` is a list/array, `2` if it is a 2d array)
1638 -- @tab a 1d or 2d array
1639 -- @tab b 1d or 2d array
1640 -- @param arg optional extra argument to pass to function
1641 -- @return 2D array, unless both arrays are 1D
1642 function array2d.map2 (f,ad,bd,a,b,arg)
1643 assert_arg(1,a,'table')
1644 assert_arg(2,b,'table')
1645 f = utils.function_arg(1,f)
1646 if ad == 1 and bd == 2 then
1647 return imap(function(row)
1648 return tmap2(f,a,row,arg)
1649 end, b)
1650 elseif ad == 2 and bd == 1 then
1651 return imap(function(row)
1652 return tmap2(f,row,b,arg)
1653 end, a)
1654 elseif ad == 1 and bd == 1 then
1655 return tmap2(f,a,b)
1656 elseif ad == 2 and bd == 2 then
1657 return tmap2(function(rowa,rowb)
1658 return tmap2(f,rowa,rowb,arg)
1659 end, a,b)
1660 end
1661 end
1662
1663 --- cartesian product of two 1d arrays.
1664 -- @func f a function of 2 arguments
1665 -- @array t1 a 1d table
1666 -- @array t2 a 1d table
1667 -- @return 2d table
1668 -- @usage product('..',{1,2},{'a','b'}) == {{'1a','2a'},{'1b','2b'}}
1669 function array2d.product (f,t1,t2)
1670 f = utils.function_arg(1,f)
1671 assert_arg(2,t1,'table')
1672 assert_arg(3,t2,'table')
1673 local res = {}
1674 for i,v in ipairs(t2) do
1675 res[i] = tmap(f,t1,v)
1676 end
1677 return res
1678 end
1679
1680 --- flatten a 2D array.
1681 -- (this goes over columns first.)
1682 -- @array2d t 2d table
1683 -- @return a 1d table
1684 -- @usage flatten {{1,2},{3,4},{5,6}} == {1,2,3,4,5,6}
1685 function array2d.flatten (t)
1686 local res = {}
1687 local k = 1
1688 local rows, cols = array2d.size(t)
1689 for r = 1, rows do
1690 local row = t[r]
1691 for c = 1, cols do
1692 res[k] = row[c]
1693 k = k + 1
1694 end
1695 end
1696 return makelist(res)
1697 end
1698
1699 --- reshape a 2D array. Reshape the array by specifying a new nr of rows.
1700 -- @array2d t 2d array
1701 -- @int nrows new number of rows
1702 -- @bool co use column-order (Fortran-style) (default false)
1703 -- @return a new 2d array
1704 function array2d.reshape (t,nrows,co)
1705 local nr,nc = array2d.size(t)
1706 local ncols = nr*nc / nrows
1707 local res = {}
1708 local ir,ic = 1,1
1709 for i = 1,nrows do
1710 local row = {}
1711 for j = 1,ncols do
1712 row[j] = t[ir][ic]
1713 if not co then
1714 ic = ic + 1
1715 if ic > nc then
1716 ir = ir + 1
1717 ic = 1
1718 end
1719 else
1720 ir = ir + 1
1721 if ir > nr then
1722 ic = ic + 1
1723 ir = 1
1724 end
1725 end
1726 end
1727 res[i] = row
1728 end
1729 return obj(t,res)
1730 end
1731
1732 --- transpose a 2D array.
1733 -- @array2d t 2d array
1734 -- @return a new 2d array
1735 function array2d.transpose(t)
1736 assert_arg(1,t,'table')
1737 local _, c = array2d.size(t)
1738 return array2d.reshape(t,c,true)
1739 end
1740
1741 --- swap two rows of an array.
1742 -- @array2d t a 2d array
1743 -- @int i1 a row index
1744 -- @int i2 a row index
1745 -- @return t (same, modified 2d array)
1746 function array2d.swap_rows (t,i1,i2)
1747 assert_arg(1,t,'table')
1748 t[i1],t[i2] = t[i2],t[i1]
1749 return t
1750 end
1751
1752 --- swap two columns of an array.
1753 -- @array2d t a 2d array
1754 -- @int j1 a column index
1755 -- @int j2 a column index
1756 -- @return t (same, modified 2d array)
1757 function array2d.swap_cols (t,j1,j2)
1758 assert_arg(1,t,'table')
1759 for _, row in ipairs(t) do
1760 row[j1],row[j2] = row[j2],row[j1]
1761 end
1762 return t
1763 end
1764
1765 --- extract the specified rows.
1766 -- @array2d t 2d array
1767 -- @tparam {int} ridx a table of row indices
1768 -- @return a new 2d array with the extracted rows
1769 function array2d.extract_rows (t,ridx)
1770 return obj(t,index_by(t,ridx))
1771 end
1772
1773 --- extract the specified columns.
1774 -- @array2d t 2d array
1775 -- @tparam {int} cidx a table of column indices
1776 -- @return a new 2d array with the extracted columns
1777 function array2d.extract_cols (t,cidx)
1778 assert_arg(1,t,'table')
1779 local res = {}
1780 for i = 1,#t do
1781 res[i] = index_by(t[i],cidx)
1782 end
1783 return obj(t,res)
1784 end
1785
1786 --- remove a row from an array.
1787 -- @function array2d.remove_row
1788 -- @array2d t a 2d array
1789 -- @int i a row index
1790 array2d.remove_row = remove
1791
1792 --- remove a column from an array.
1793 -- @array2d t a 2d array
1794 -- @int j a column index
1795 function array2d.remove_col (t,j)
1796 assert_arg(1,t,'table')
1797 for i = 1,#t do
1798 remove(t[i],j)
1799 end
1800 end
1801
1802 do
1803 local function _parse (s)
1804 local r, c = s:match 'R(%d+)C(%d+)'
1805 if r then
1806 r,c = tonumber(r),tonumber(c)
1807 return r,c
1808 end
1809 c,r = s:match '(%a+)(%d+)'
1810 if c then
1811 local cv = 0
1812 for i = 1, #c do
1813 cv = cv * 26 + byte(c:sub(i,i)) - byte 'A' + 1
1814 end
1815 return tonumber(r), cv
1816 end
1817 error('bad cell specifier: '..s)
1818 end
1819
1820 --- parse a spreadsheet range or cell.
1821 -- The range/cell can be specified either as 'A1:B2' or 'R1C1:R2C2' or for
1822 -- single cells as 'A1' or 'R1C1'.
1823 -- @string s a range (case insensitive).
1824 -- @treturn int start row
1825 -- @treturn int start col
1826 -- @treturn int end row (or `nil` if the range was a single cell)
1827 -- @treturn int end col (or `nil` if the range was a single cell)
1828 function array2d.parse_range (s)
1829 assert_arg(1,s,'string')
1830 s = s:upper()
1831 if s:find ':' then
1832 local start,finish = splitv(s,':')
1833 local i1,j1 = _parse(start)
1834 local i2,j2 = _parse(finish)
1835 return i1,j1,i2,j2
1836 else -- single value
1837 local i,j = _parse(s)
1838 return i,j
1839 end
1840 end
1841 end
1842
1843 --- get a slice of a 2D array.
1844 -- Same as `slice`.
1845 -- @see slice
1846 function array2d.range (...)
1847 return array2d.slice(...)
1848 end
1849
1850 local default_range do
1851 local function norm_value(v, max)
1852 if not v then return v end
1853 if v < 0 then
1854 v = max + v + 1
1855 end
1856 if v < 1 then v = 1 end
1857 if v > max then v = max end
1858 return v
1859 end
1860
1861 --- normalizes coordinates to valid positive entries and defaults.
1862 -- Negative indices will be counted from the end, too low, or too high
1863 -- will be limited by the array sizes.
1864 -- @array2d t a 2D array
1865 -- @tparam[opt=1] int|string i1 start row or spreadsheet range passed to `parse_range`
1866 -- @tparam[opt=1] int j1 start col
1867 -- @tparam[opt=N] int i2 end row
1868 -- @tparam[opt=M] int j2 end col
1869 -- @see parse_range
1870 -- @return i1, j1, i2, j2
1871 function array2d.default_range (t,i1,j1,i2,j2)
1872 if (type(i1) == 'string') and not (j1 or i2 or j2) then
1873 i1, j1, i2, j2 = array2d.parse_range(i1)
1874 end
1875 local nr, nc = array2d.size(t)
1876 i1 = norm_value(i1 or 1, nr)
1877 j1 = norm_value(j1 or 1, nc)
1878 i2 = norm_value(i2 or nr, nr)
1879 j2 = norm_value(j2 or nc, nc)
1880 return i1,j1,i2,j2
1881 end
1882 default_range = array2d.default_range
1883 end
1884
1885 --- get a slice of a 2D array. Note that if the specified range has
1886 -- a 1D result, the rank of the result will be 1.
1887 -- @array2d t a 2D array
1888 -- @tparam[opt=1] int|string i1 start row or spreadsheet range passed to `parse_range`
1889 -- @tparam[opt=1] int j1 start col
1890 -- @tparam[opt=N] int i2 end row
1891 -- @tparam[opt=M] int j2 end col
1892 -- @see parse_range
1893 -- @return an array, 2D in general but 1D in special cases.
1894 function array2d.slice (t,i1,j1,i2,j2)
1895 assert_arg(1,t,'table')
1896 i1,j1,i2,j2 = default_range(t,i1,j1,i2,j2)
1897 local res = {}
1898 for i = i1,i2 do
1899 local val
1900 local row = t[i]
1901 if j1 == j2 then
1902 val = row[j1]
1903 else
1904 val = {}
1905 for j = j1,j2 do
1906 val[#val+1] = row[j]
1907 end
1908 end
1909 res[#res+1] = val
1910 end
1911 if i1 == i2 then res = res[1] end
1912 return obj(t,res)
1913 end
1914
1915 --- set a specified range of an array to a value.
1916 -- @array2d t a 2D array
1917 -- @param value the value (may be a function, called as `val(i,j)`)
1918 -- @tparam[opt=1] int|string i1 start row or spreadsheet range passed to `parse_range`
1919 -- @tparam[opt=1] int j1 start col
1920 -- @tparam[opt=N] int i2 end row
1921 -- @tparam[opt=M] int j2 end col
1922 -- @see parse_range
1923 -- @see tablex.set
1924 function array2d.set (t,value,i1,j1,i2,j2)
1925 i1,j1,i2,j2 = default_range(t,i1,j1,i2,j2)
1926 local i = i1
1927 if types.is_callable(value) then
1928 local old_f = value
1929 value = function(j)
1930 return old_f(i,j)
1931 end
1932 end
1933 while i <= i2 do
1934 tset(t[i],value,j1,j2)
1935 i = i + 1
1936 end
1937 end
1938
1939 --- write a 2D array to a file.
1940 -- @array2d t a 2D array
1941 -- @param f a file object (default stdout)
1942 -- @string fmt a format string (default is just to use tostring)
1943 -- @tparam[opt=1] int|string i1 start row or spreadsheet range passed to `parse_range`
1944 -- @tparam[opt=1] int j1 start col
1945 -- @tparam[opt=N] int i2 end row
1946 -- @tparam[opt=M] int j2 end col
1947 -- @see parse_range
1948 function array2d.write (t,f,fmt,i1,j1,i2,j2)
1949 assert_arg(1,t,'table')
1950 f = f or stdout
1951 local rowop
1952 if fmt then
1953 rowop = function(row,j) fprintf(f,fmt,row[j]) end
1954 else
1955 rowop = function(row,j) f:write(tostring(row[j]),' ') end
1956 end
1957 local function newline()
1958 f:write '\n'
1959 end
1960 array2d.forall(t,rowop,newline,i1,j1,i2,j2)
1961 end
1962
1963 --- perform an operation for all values in a 2D array.
1964 -- @array2d t 2D array
1965 -- @func row_op function to call on each value; `row_op(row,j)`
1966 -- @func end_row_op function to call at end of each row; `end_row_op(i)`
1967 -- @tparam[opt=1] int|string i1 start row or spreadsheet range passed to `parse_range`
1968 -- @tparam[opt=1] int j1 start col
1969 -- @tparam[opt=N] int i2 end row
1970 -- @tparam[opt=M] int j2 end col
1971 -- @see parse_range
1972 function array2d.forall (t,row_op,end_row_op,i1,j1,i2,j2)
1973 assert_arg(1,t,'table')
1974 i1,j1,i2,j2 = default_range(t,i1,j1,i2,j2)
1975 for i = i1,i2 do
1976 local row = t[i]
1977 for j = j1,j2 do
1978 row_op(row,j)
1979 end
1980 if end_row_op then end_row_op(i) end
1981 end
1982 end
1983
1984 ---- move a block from the destination to the source.
1985 -- @array2d dest a 2D array
1986 -- @int di start row in dest
1987 -- @int dj start col in dest
1988 -- @array2d src a 2D array
1989 -- @tparam[opt=1] int|string i1 start row or spreadsheet range passed to `parse_range`
1990 -- @tparam[opt=1] int j1 start col
1991 -- @tparam[opt=N] int i2 end row
1992 -- @tparam[opt=M] int j2 end col
1993 -- @see parse_range
1994 function array2d.move (dest,di,dj,src,i1,j1,i2,j2)
1995 assert_arg(1,dest,'table')
1996 assert_arg(4,src,'table')
1997 i1,j1,i2,j2 = default_range(src,i1,j1,i2,j2)
1998 local nr,nc = array2d.size(dest)
1999 i2, j2 = min(nr,i2), min(nc,j2)
2000 --i1, j1 = max(1,i1), max(1,j1)
2001 dj = dj - 1
2002 for i = i1,i2 do
2003 local drow, srow = dest[i+di-1], src[i]
2004 for j = j1,j2 do
2005 drow[j+dj] = srow[j]
2006 end
2007 end
2008 end
2009
2010 --- iterate over all elements in a 2D array, with optional indices.
2011 -- @array2d a 2D array
2012 -- @bool indices with indices (default false)
2013 -- @tparam[opt=1] int|string i1 start row or spreadsheet range passed to `parse_range`
2014 -- @tparam[opt=1] int j1 start col
2015 -- @tparam[opt=N] int i2 end row
2016 -- @tparam[opt=M] int j2 end col
2017 -- @see parse_range
2018 -- @return either `value` or `i,j,value` depending on the value of `indices`
2019 function array2d.iter(a,indices,i1,j1,i2,j2)
2020 assert_arg(1,a,'table')
2021 i1,j1,i2,j2 = default_range(a,i1,j1,i2,j2)
2022 local i,j = i1,j1-1
2023 local row = a[i]
2024 return function()
2025 j = j + 1
2026 if j > j2 then
2027 j = j1
2028 i = i + 1
2029 row = a[i]
2030 if i > i2 then
2031 return nil
2032 end
2033 end
2034 if indices then
2035 return i,j,row[j]
2036 else
2037 return row[j]
2038 end
2039 end
2040 end
2041
2042 --- iterate over all columns.
2043 -- @array2d a a 2D array
2044 -- @return column, column-index
2045 function array2d.columns(a)
2046 assert_arg(1,a,'table')
2047 local n = #a[1]
2048 local i = 0
2049 return function()
2050 i = i + 1
2051 if i > n then return nil end
2052 return column(a,i), i
2053 end
2054 end
2055
2056 --- iterate over all rows.
2057 -- Returns a copy of the row, for read-only purposes directly iterating
2058 -- is more performant; `ipairs(a)`
2059 -- @array2d a a 2D array
2060 -- @return row, row-index
2061 function array2d.rows(a)
2062 assert_arg(1,a,'table')
2063 local n = #a
2064 local i = 0
2065 return function()
2066 i = i + 1
2067 if i > n then return nil end
2068 return array2d.row(a,i), i
2069 end
2070 end
2071
2072 --- new array of specified dimensions
2073 -- @int rows number of rows
2074 -- @int cols number of cols
2075 -- @param val initial value; if it's a function then use `val(i,j)`
2076 -- @return new 2d array
2077 function array2d.new(rows,cols,val)
2078 local res = {}
2079 local fun = types.is_callable(val)
2080 for i = 1,rows do
2081 local row = {}
2082 if fun then
2083 for j = 1,cols do row[j] = val(i,j) end
2084 else
2085 for j = 1,cols do row[j] = val end
2086 end
2087 res[i] = row
2088 end
2089 return res
2090 end
2091
2092 return array2d
2093
2094 end,
2095
2096 ["pl.class"] = function()
2097 --------------------
2098 -- Module: 'pl.class'
2099 --------------------
2100 --- Provides a reusable and convenient framework for creating classes in Lua.
2101 -- Two possible notations:
2102 --
2103 -- B = class(A)
2104 -- class.B(A)
2105 --
2106 -- The latter form creates a named class within the current environment. Note
2107 -- that this implicitly brings in `pl.utils` as a dependency.
2108 --
2109 -- See the Guide for further @{01-introduction.md.Simplifying_Object_Oriented_Programming_in_Lua|discussion}
2110 -- @module pl.class
2111
2112 local error, getmetatable, io, pairs, rawget, rawset, setmetatable, tostring, type =
2113 _G.error, _G.getmetatable, _G.io, _G.pairs, _G.rawget, _G.rawset, _G.setmetatable, _G.tostring, _G.type
2114 local compat
2115
2116 -- this trickery is necessary to prevent the inheritance of 'super' and
2117 -- the resulting recursive call problems.
2118 local function call_ctor (c,obj,...)
2119 local init = rawget(c,'_init')
2120 local parent_with_init = rawget(c,'_parent_with_init')
2121
2122 if parent_with_init then
2123 if not init then -- inheriting an init
2124 init = rawget(parent_with_init, '_init')
2125 parent_with_init = rawget(parent_with_init, '_parent_with_init')
2126 end
2127 if parent_with_init then -- super() points to one above wherever _init came from
2128 rawset(obj,'super',function(obj,...)
2129 call_ctor(parent_with_init,obj,...)
2130 end)
2131 end
2132 else
2133 -- Without this, calling super() where none exists will sometimes loop and stack overflow
2134 rawset(obj,'super',nil)
2135 end
2136
2137 local res = init(obj,...)
2138 if parent_with_init then -- If this execution of call_ctor set a super, unset it
2139 rawset(obj,'super',nil)
2140 end
2141
2142 return res
2143 end
2144
2145 --- initializes an __instance__ upon creation.
2146 -- @function class:_init
2147 -- @param ... parameters passed to the constructor
2148 -- @usage local Cat = class()
2149 -- function Cat:_init(name)
2150 -- --self:super(name) -- call the ancestor initializer if needed
2151 -- self.name = name
2152 -- end
2153 --
2154 -- local pussycat = Cat("pussycat")
2155 -- print(pussycat.name) --> pussycat
2156
2157 --- checks whether an __instance__ is derived from some class.
2158 -- Works the other way around as `class_of`. It has two ways of using;
2159 -- 1) call with a class to check against, 2) call without params.
2160 -- @function instance:is_a
2161 -- @param some_class class to check against, or `nil` to return the class
2162 -- @return `true` if `instance` is derived from `some_class`, or if `some_class == nil` then
2163 -- it returns the class table of the instance
2164 -- @usage local pussycat = Lion() -- assuming Lion derives from Cat
2165 -- if pussycat:is_a(Cat) then
2166 -- -- it's true, it is a Lion, but also a Cat
2167 -- end
2168 --
2169 -- if pussycat:is_a() == Lion then
2170 -- -- It's true
2171 -- end
2172 local function is_a(self,klass)
2173 if klass == nil then
2174 -- no class provided, so return the class this instance is derived from
2175 return getmetatable(self)
2176 end
2177 local m = getmetatable(self)
2178 if not m then return false end --*can't be an object!
2179 while m do
2180 if m == klass then return true end
2181 m = rawget(m,'_base')
2182 end
2183 return false
2184 end
2185
2186 --- checks whether an __instance__ is derived from some class.
2187 -- Works the other way around as `is_a`.
2188 -- @function some_class:class_of
2189 -- @param some_instance instance to check against
2190 -- @return `true` if `some_instance` is derived from `some_class`
2191 -- @usage local pussycat = Lion() -- assuming Lion derives from Cat
2192 -- if Cat:class_of(pussycat) then
2193 -- -- it's true
2194 -- end
2195 local function class_of(klass,obj)
2196 if type(klass) ~= 'table' or not rawget(klass,'is_a') then return false end
2197 return klass.is_a(obj,klass)
2198 end
2199
2200 --- cast an object to another class.
2201 -- It is not clever (or safe!) so use carefully.
2202 -- @param some_instance the object to be changed
2203 -- @function some_class:cast
2204 local function cast (klass, obj)
2205 return setmetatable(obj,klass)
2206 end
2207
2208
2209 local function _class_tostring (obj)
2210 local mt = obj._class
2211 local name = rawget(mt,'_name')
2212 setmetatable(obj,nil)
2213 local str = tostring(obj)
2214 setmetatable(obj,mt)
2215 if name then str = name ..str:gsub('table','') end
2216 return str
2217 end
2218
2219 local function tupdate(td,ts,dont_override)
2220 for k,v in pairs(ts) do
2221 if not dont_override or td[k] == nil then
2222 td[k] = v
2223 end
2224 end
2225 end
2226
2227 local function _class(base,c_arg,c)
2228 -- the class `c` will be the metatable for all its objects,
2229 -- and they will look up their methods in it.
2230 local mt = {} -- a metatable for the class to support __call and _handler
2231 -- can define class by passing it a plain table of methods
2232 local plain = type(base) == 'table' and not getmetatable(base)
2233 if plain then
2234 c = base
2235 base = c._base
2236 else
2237 c = c or {}
2238 end
2239
2240 if type(base) == 'table' then
2241 -- our new class is a shallow copy of the base class!
2242 -- but be careful not to wipe out any methods we have been given at this point!
2243 tupdate(c,base,plain)
2244 c._base = base
2245 -- inherit the 'not found' handler, if present
2246 if rawget(c,'_handler') then mt.__index = c._handler end
2247 elseif base ~= nil then
2248 error("must derive from a table type",3)
2249 end
2250
2251 c.__index = c
2252 setmetatable(c,mt)
2253 if not plain then
2254 if base and rawget(base,'_init') then c._parent_with_init = base end -- For super and inherited init
2255 c._init = nil
2256 end
2257
2258 if base and rawget(base,'_class_init') then
2259 base._class_init(c,c_arg)
2260 end
2261
2262 -- expose a ctor which can be called by <classname>(<args>)
2263 mt.__call = function(class_tbl,...)
2264 local obj
2265 if rawget(c,'_create') then obj = c._create(...) end
2266 if not obj then obj = {} end
2267 setmetatable(obj,c)
2268
2269 if rawget(c,'_init') or rawget(c,'_parent_with_init') then -- constructor exists
2270 local res = call_ctor(c,obj,...)
2271 if res then -- _if_ a ctor returns a value, it becomes the object...
2272 obj = res
2273 setmetatable(obj,c)
2274 end
2275 end
2276
2277 if base and rawget(base,'_post_init') then
2278 base._post_init(obj)
2279 end
2280
2281 return obj
2282 end
2283 -- Call Class.catch to set a handler for methods/properties not found in the class!
2284 c.catch = function(self, handler)
2285 if type(self) == "function" then
2286 -- called using . instead of :
2287 handler = self
2288 end
2289 c._handler = handler
2290 mt.__index = handler
2291 end
2292 c.is_a = is_a
2293 c.class_of = class_of
2294 c.cast = cast
2295 c._class = c
2296
2297 if not rawget(c,'__tostring') then
2298 c.__tostring = _class_tostring
2299 end
2300
2301 return c
2302 end
2303
2304 --- create a new class, derived from a given base class.
2305 -- Supporting two class creation syntaxes:
2306 -- either `Name = class(base)` or `class.Name(base)`.
2307 -- The first form returns the class directly and does not set its `_name`.
2308 -- The second form creates a variable `Name` in the current environment set
2309 -- to the class, and also sets `_name`.
2310 -- @function class
2311 -- @param base optional base class
2312 -- @param c_arg optional parameter to class constructor
2313 -- @param c optional table to be used as class
2314 local class
2315 class = setmetatable({},{
2316 __call = function(fun,...)
2317 return _class(...)
2318 end,
2319 __index = function(tbl,key)
2320 if key == 'class' then
2321 io.stderr:write('require("pl.class").class is deprecated. Use require("pl.class")\n')
2322 return class
2323 end
2324 compat = compat or require 'pl.compat'
2325 local env = compat.getfenv(2)
2326 return function(...)
2327 local c = _class(...)
2328 c._name = key
2329 rawset(env,key,c)
2330 return c
2331 end
2332 end
2333 })
2334
2335 class.properties = class()
2336
2337 function class.properties._class_init(klass)
2338 klass.__index = function(t,key)
2339 -- normal class lookup!
2340 local v = klass[key]
2341 if v then return v end
2342 -- is it a getter?
2343 v = rawget(klass,'get_'..key)
2344 if v then
2345 return v(t)
2346 end
2347 -- is it a field?
2348 return rawget(t,'_'..key)
2349 end
2350 klass.__newindex = function (t,key,value)
2351 -- if there's a setter, use that, otherwise directly set table
2352 local p = 'set_'..key
2353 local setter = klass[p]
2354 if setter then
2355 setter(t,value)
2356 else
2357 rawset(t,key,value)
2358 end
2359 end
2360 end
2361
2362
2363 return class
2364
2365
2366 end,
2367
2368 ["pl.compat"] = function()
2369 --------------------
2370 -- Module: 'pl.compat'
2371 --------------------
2372 ----------------
2373 --- Lua 5.1/5.2/5.3 compatibility.
2374 -- Injects `table.pack`, `table.unpack`, and `package.searchpath` in the global
2375 -- environment, to make sure they are available for Lua 5.1 and LuaJIT.
2376 --
2377 -- All other functions are exported as usual in the returned module table.
2378 --
2379 -- NOTE: everything in this module is also available in `pl.utils`.
2380 -- @module pl.compat
2381 local compat = {}
2382
2383 --- boolean flag this is Lua 5.1 (or LuaJIT).
2384 -- @field lua51
2385 compat.lua51 = _VERSION == 'Lua 5.1'
2386
2387 --- boolean flag this is LuaJIT.
2388 -- @field jit
2389 compat.jit = (tostring(assert):match('builtin') ~= nil)
2390
2391 --- boolean flag this is LuaJIT with 5.2 compatibility compiled in.
2392 -- @field jit52
2393 if compat.jit then
2394 -- 'goto' is a keyword when 52 compatibility is enabled in LuaJit
2395 compat.jit52 = not loadstring("local goto = 1")
2396 end
2397
2398 --- the directory separator character for the current platform.
2399 -- @field dir_separator
2400 compat.dir_separator = _G.package.config:sub(1,1)
2401
2402 --- boolean flag this is a Windows platform.
2403 -- @field is_windows
2404 compat.is_windows = compat.dir_separator == '\\'
2405
2406 --- execute a shell command, in a compatible and platform independent way.
2407 -- This is a compatibility function that returns the same for Lua 5.1 and
2408 -- Lua 5.2+.
2409 --
2410 -- NOTE: Windows systems can use signed 32bit integer exitcodes. Posix systems
2411 -- only use exitcodes 0-255, anything else is undefined.
2412 --
2413 -- NOTE2: In Lua 5.2 and 5.3 a Windows exitcode of -1 would not properly be
2414 -- returned, this function will return it properly for all versions.
2415 -- @param cmd a shell command
2416 -- @return true if successful
2417 -- @return actual return code
2418 function compat.execute(cmd)
2419 local res1,res2,res3 = os.execute(cmd)
2420 if res2 == "No error" and res3 == 0 and compat.is_windows then
2421 -- os.execute bug in Lua 5.2/5.3 not reporting -1 properly on Windows
2422 -- this was fixed in 5.4
2423 res3 = -1
2424 end
2425 if compat.lua51 and not compat.jit52 then
2426 if compat.is_windows then
2427 return res1==0,res1
2428 else
2429 res1 = res1 > 255 and res1 / 256 or res1
2430 return res1==0,res1
2431 end
2432 else
2433 if compat.is_windows then
2434 return res3==0,res3
2435 else
2436 return not not res1,res3
2437 end
2438 end
2439 end
2440
2441 ----------------
2442 -- Load Lua code as a text or binary chunk (in a Lua 5.2 compatible way).
2443 -- @param ld code string or loader
2444 -- @param[opt] source name of chunk for errors
2445 -- @param[opt] mode 'b', 't' or 'bt'
2446 -- @param[opt] env environment to load the chunk in
2447 -- @function compat.load
2448
2449 ---------------
2450 -- Get environment of a function (in a Lua 5.1 compatible way).
2451 -- Not 100% compatible, so with Lua 5.2 it may return nil for a function with no
2452 -- global references!
2453 -- Based on code by [Sergey Rozhenko](http://lua-users.org/lists/lua-l/2010-06/msg00313.html)
2454 -- @param f a function or a call stack reference
2455 -- @function compat.getfenv
2456
2457 ---------------
2458 -- Set environment of a function (in a Lua 5.1 compatible way).
2459 -- @param f a function or a call stack reference
2460 -- @param env a table that becomes the new environment of `f`
2461 -- @function compat.setfenv
2462
2463 if compat.lua51 then -- define Lua 5.2 style load()
2464 if not compat.jit then -- but LuaJIT's load _is_ compatible
2465 local lua51_load = load
2466 function compat.load(str,src,mode,env)
2467 local chunk,err
2468 if type(str) == 'string' then
2469 if str:byte(1) == 27 and not (mode or 'bt'):find 'b' then
2470 return nil,"attempt to load a binary chunk"
2471 end
2472 chunk,err = loadstring(str,src)
2473 else
2474 chunk,err = lua51_load(str,src)
2475 end
2476 if chunk and env then setfenv(chunk,env) end
2477 return chunk,err
2478 end
2479 else
2480 compat.load = load
2481 end
2482 compat.setfenv, compat.getfenv = setfenv, getfenv
2483 else
2484 compat.load = load
2485 -- setfenv/getfenv replacements for Lua 5.2
2486 -- by Sergey Rozhenko
2487 -- http://lua-users.org/lists/lua-l/2010-06/msg00313.html
2488 -- Roberto Ierusalimschy notes that it is possible for getfenv to return nil
2489 -- in the case of a function with no globals:
2490 -- http://lua-users.org/lists/lua-l/2010-06/msg00315.html
2491 function compat.setfenv(f, t)
2492 f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
2493 local name
2494 local up = 0
2495 repeat
2496 up = up + 1
2497 name = debug.getupvalue(f, up)
2498 until name == '_ENV' or name == nil
2499 if name then
2500 debug.upvaluejoin(f, up, function() return name end, 1) -- use unique upvalue
2501 debug.setupvalue(f, up, t)
2502 end
2503 if f ~= 0 then return f end
2504 end
2505
2506 function compat.getfenv(f)
2507 local f = f or 0
2508 f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
2509 local name, val
2510 local up = 0
2511 repeat
2512 up = up + 1
2513 name, val = debug.getupvalue(f, up)
2514 until name == '_ENV' or name == nil
2515 return val
2516 end
2517 end
2518
2519
2520 --- Global exported functions (for Lua 5.1 & LuaJIT)
2521 -- @section lua52
2522
2523 --- pack an argument list into a table.
2524 -- @param ... any arguments
2525 -- @return a table with field n set to the length
2526 -- @function table.pack
2527 if not table.pack then
2528 function table.pack (...) -- luacheck: ignore
2529 return {n=select('#',...); ...}
2530 end
2531 end
2532
2533 --- unpack a table and return the elements.
2534 --
2535 -- NOTE: this version does NOT honor the n field, and hence it is not nil-safe.
2536 -- See `utils.unpack` for a version that is nil-safe.
2537 -- @param t table to unpack
2538 -- @param[opt] i index from which to start unpacking, defaults to 1
2539 -- @param[opt] j index of the last element to unpack, defaults to #t
2540 -- @return multiple return values from the table
2541 -- @function table.unpack
2542 -- @see utils.unpack
2543 if not table.unpack then
2544 table.unpack = unpack -- luacheck: ignore
2545 end
2546
2547 --- return the full path where a file name would be matched.
2548 -- This function was introduced in Lua 5.2, so this compatibility version
2549 -- will be injected in Lua 5.1 engines.
2550 -- @string name file name, possibly dotted
2551 -- @string path a path-template in the same form as package.path or package.cpath
2552 -- @string[opt] sep template separate character to be replaced by path separator. Default: "."
2553 -- @string[opt] rep the path separator to use, defaults to system separator. Default; "/" on Unixes, "\" on Windows.
2554 -- @see path.package_path
2555 -- @function package.searchpath
2556 -- @return on success: path of the file
2557 -- @return on failure: nil, error string listing paths tried
2558 if not package.searchpath then
2559 function package.searchpath (name,path,sep,rep) -- luacheck: ignore
2560 if type(name) ~= "string" then
2561 error(("bad argument #1 to 'searchpath' (string expected, got %s)"):format(type(path)), 2)
2562 end
2563 if type(path) ~= "string" then
2564 error(("bad argument #2 to 'searchpath' (string expected, got %s)"):format(type(path)), 2)
2565 end
2566 if sep ~= nil and type(sep) ~= "string" then
2567 error(("bad argument #3 to 'searchpath' (string expected, got %s)"):format(type(path)), 2)
2568 end
2569 if rep ~= nil and type(rep) ~= "string" then
2570 error(("bad argument #4 to 'searchpath' (string expected, got %s)"):format(type(path)), 2)
2571 end
2572 sep = sep or "."
2573 rep = rep or compat.dir_separator
2574 do
2575 local s, e = name:find(sep, nil, true)
2576 while s do
2577 name = name:sub(1, s-1) .. rep .. name:sub(e+1, -1)
2578 s, e = name:find(sep, s + #rep + 1, true)
2579 end
2580 end
2581 local tried = {}
2582 for m in path:gmatch('[^;]+') do
2583 local nm = m:gsub('?', name)
2584 tried[#tried+1] = nm
2585 local f = io.open(nm,'r')
2586 if f then f:close(); return nm end
2587 end
2588 return nil, "\tno file '" .. table.concat(tried, "'\n\tno file '") .. "'"
2589 end
2590 end
2591
2592 --- Global exported functions (for Lua < 5.4)
2593 -- @section lua54
2594
2595 --- raise a warning message.
2596 -- This functions mimics the `warn` function added in Lua 5.4.
2597 -- @function warn
2598 -- @param ... any arguments
2599 if not rawget(_G, "warn") then
2600 local enabled = false
2601 local function warn(arg1, ...)
2602 if type(arg1) == "string" and arg1:sub(1, 1) == "@" then
2603 -- control message
2604 if arg1 == "@on" then
2605 enabled = true
2606 return
2607 end
2608 if arg1 == "@off" then
2609 enabled = false
2610 return
2611 end
2612 return -- ignore unknown control messages
2613 end
2614 if enabled then
2615 io.stderr:write("Lua warning: ", arg1, ...)
2616 io.stderr:write("\n")
2617 end
2618 end
2619 -- use rawset to bypass OpenResty's protection of global scope
2620 rawset(_G, "warn", warn)
2621 end
2622
2623 return compat
2624
2625 end,
2626
2627 ["pl.comprehension"] = function()
2628 --------------------
2629 -- Module: 'pl.comprehension'
2630 --------------------
2631 --- List comprehensions implemented in Lua.
2632 --
2633 -- See the [wiki page](http://lua-users.org/wiki/ListComprehensions)
2634 --
2635 -- local C= require 'pl.comprehension' . new()
2636 --
2637 -- C ('x for x=1,10') ()
2638 -- ==> {1,2,3,4,5,6,7,8,9,10}
2639 -- C 'x^2 for x=1,4' ()
2640 -- ==> {1,4,9,16}
2641 -- C '{x,x^2} for x=1,4' ()
2642 -- ==> {{1,1},{2,4},{3,9},{4,16}}
2643 -- C '2*x for x' {1,2,3}
2644 -- ==> {2,4,6}
2645 -- dbl = C '2*x for x'
2646 -- dbl {10,20,30}
2647 -- ==> {20,40,60}
2648 -- C 'x for x if x % 2 == 0' {1,2,3,4,5}
2649 -- ==> {2,4}
2650 -- C '{x,y} for x = 1,2 for y = 1,2' ()
2651 -- ==> {{1,1},{1,2},{2,1},{2,2}}
2652 -- C '{x,y} for x for y' ({1,2},{10,20})
2653 -- ==> {{1,10},{1,20},{2,10},{2,20}}
2654 -- assert(C 'sum(x^2 for x)' {2,3,4} == 2^2+3^2+4^2)
2655 --
2656 -- (c) 2008 David Manura. Licensed under the same terms as Lua (MIT license).
2657 --
2658 -- Dependencies: `pl.utils`, `pl.luabalanced`
2659 --
2660 -- See @{07-functional.md.List_Comprehensions|the Guide}
2661 -- @module pl.comprehension
2662
2663 local utils = require 'pl.utils'
2664
2665 local status,lb = pcall(require, "pl.luabalanced")
2666 if not status then
2667 lb = require 'luabalanced'
2668 end
2669
2670 local math_max = math.max
2671 local table_concat = table.concat
2672
2673 -- fold operations
2674 -- http://en.wikipedia.org/wiki/Fold_(higher-order_function)
2675 local ops = {
2676 list = {init=' {} ', accum=' __result[#__result+1] = (%s) '},
2677 table = {init=' {} ', accum=' local __k, __v = %s __result[__k] = __v '},
2678 sum = {init=' 0 ', accum=' __result = __result + (%s) '},
2679 min = {init=' nil ', accum=' local __tmp = %s ' ..
2680 ' if __result then if __tmp < __result then ' ..
2681 '__result = __tmp end else __result = __tmp end '},
2682 max = {init=' nil ', accum=' local __tmp = %s ' ..
2683 ' if __result then if __tmp > __result then ' ..
2684 '__result = __tmp end else __result = __tmp end '},
2685 }
2686
2687
2688 -- Parses comprehension string expr.
2689 -- Returns output expression list <out> string, array of for types
2690 -- ('=', 'in' or nil) <fortypes>, array of input variable name
2691 -- strings <invarlists>, array of input variable value strings
2692 -- <invallists>, array of predicate expression strings <preds>,
2693 -- operation name string <opname>, and number of placeholder
2694 -- parameters <max_param>.
2695 --
2696 -- The is equivalent to the mathematical set-builder notation:
2697 --
2698 -- <opname> { <out> | <invarlist> in <invallist> , <preds> }
2699 --
2700 -- @usage "x^2 for x" -- array values
2701 -- @usage "x^2 for x=1,10,2" -- numeric for
2702 -- @usage "k^v for k,v in pairs(_1)" -- iterator for
2703 -- @usage "(x+y)^2 for x for y if x > y" -- nested
2704 --
2705 local function parse_comprehension(expr)
2706 local pos = 1
2707
2708 -- extract opname (if exists)
2709 local opname
2710 local tok, post = expr:match('^%s*([%a_][%w_]*)%s*%(()', pos)
2711 local pose = #expr + 1
2712 if tok then
2713 local tok2, posb = lb.match_bracketed(expr, post-1)
2714 assert(tok2, 'syntax error')
2715 if expr:match('^%s*$', posb) then
2716 opname = tok
2717 pose = posb - 1
2718 pos = post
2719 end
2720 end
2721 opname = opname or "list"
2722
2723 -- extract out expression list
2724 local out; out, pos = lb.match_explist(expr, pos)
2725 assert(out, "syntax error: missing expression list")
2726 out = table_concat(out, ', ')
2727
2728 -- extract "for" clauses
2729 local fortypes = {}
2730 local invarlists = {}
2731 local invallists = {}
2732 while 1 do
2733 local post = expr:match('^%s*for%s+()', pos)
2734 if not post then break end
2735 pos = post
2736
2737 -- extract input vars
2738 local iv; iv, pos = lb.match_namelist(expr, pos)
2739 assert(#iv > 0, 'syntax error: zero variables')
2740 for _,ident in ipairs(iv) do
2741 assert(not ident:match'^__',
2742 "identifier " .. ident .. " may not contain __ prefix")
2743 end
2744 invarlists[#invarlists+1] = iv
2745
2746 -- extract '=' or 'in' (optional)
2747 local fortype, post = expr:match('^(=)%s*()', pos)
2748 if not fortype then fortype, post = expr:match('^(in)%s+()', pos) end
2749 if fortype then
2750 pos = post
2751 -- extract input value range
2752 local il; il, pos = lb.match_explist(expr, pos)
2753 assert(#il > 0, 'syntax error: zero expressions')
2754 assert(fortype ~= '=' or #il == 2 or #il == 3,
2755 'syntax error: numeric for requires 2 or three expressions')
2756 fortypes[#invarlists] = fortype
2757 invallists[#invarlists] = il
2758 else
2759 fortypes[#invarlists] = false
2760 invallists[#invarlists] = false
2761 end
2762 end
2763 assert(#invarlists > 0, 'syntax error: missing "for" clause')
2764
2765 -- extract "if" clauses
2766 local preds = {}
2767 while 1 do
2768 local post = expr:match('^%s*if%s+()', pos)
2769 if not post then break end
2770 pos = post
2771 local pred; pred, pos = lb.match_expression(expr, pos)
2772 assert(pred, 'syntax error: predicated expression not found')
2773 preds[#preds+1] = pred
2774 end
2775
2776 -- extract number of parameter variables (name matching "_%d+")
2777 local stmp = ''; lb.gsub(expr, function(u, sin) -- strip comments/strings
2778 if u == 'e' then stmp = stmp .. ' ' .. sin .. ' ' end
2779 end)
2780 local max_param = 0; stmp:gsub('[%a_][%w_]*', function(s)
2781 local s = s:match('^_(%d+)$')
2782 if s then max_param = math_max(max_param, tonumber(s)) end
2783 end)
2784
2785 if pos ~= pose then
2786 assert(false, "syntax error: unrecognized " .. expr:sub(pos))
2787 end
2788
2789 --DEBUG:
2790 --print('----\n', string.format("%q", expr), string.format("%q", out), opname)
2791 --for k,v in ipairs(invarlists) do print(k,v, invallists[k]) end
2792 --for k,v in ipairs(preds) do print(k,v) end
2793
2794 return out, fortypes, invarlists, invallists, preds, opname, max_param
2795 end
2796
2797
2798 -- Create Lua code string representing comprehension.
2799 -- Arguments are in the form returned by parse_comprehension.
2800 local function code_comprehension(
2801 out, fortypes, invarlists, invallists, preds, opname, max_param
2802 )
2803 local op = assert(ops[opname])
2804 local code = op.accum:gsub('%%s', out)
2805
2806 for i=#preds,1,-1 do local pred = preds[i]
2807 code = ' if ' .. pred .. ' then ' .. code .. ' end '
2808 end
2809 for i=#invarlists,1,-1 do
2810 if not fortypes[i] then
2811 local arrayname = '__in' .. i
2812 local idx = '__idx' .. i
2813 code =
2814 ' for ' .. idx .. ' = 1, #' .. arrayname .. ' do ' ..
2815 ' local ' .. invarlists[i][1] .. ' = ' .. arrayname .. '['..idx..'] ' ..
2816 code .. ' end '
2817 else
2818 code =
2819 ' for ' ..
2820 table_concat(invarlists[i], ', ') ..
2821 ' ' .. fortypes[i] .. ' ' ..
2822 table_concat(invallists[i], ', ') ..
2823 ' do ' .. code .. ' end '
2824 end
2825 end
2826 code = ' local __result = ( ' .. op.init .. ' ) ' .. code
2827 return code
2828 end
2829
2830
2831 -- Convert code string represented by code_comprehension
2832 -- into Lua function. Also must pass ninputs = #invarlists,
2833 -- max_param, and invallists (from parse_comprehension).
2834 -- Uses environment env.
2835 local function wrap_comprehension(code, ninputs, max_param, invallists, env)
2836 assert(ninputs > 0)
2837 local ts = {}
2838 for i=1,max_param do
2839 ts[#ts+1] = '_' .. i
2840 end
2841 for i=1,ninputs do
2842 if not invallists[i] then
2843 local name = '__in' .. i
2844 ts[#ts+1] = name
2845 end
2846 end
2847 if #ts > 0 then
2848 code = ' local ' .. table_concat(ts, ', ') .. ' = ... ' .. code
2849 end
2850 code = code .. ' return __result '
2851 --print('DEBUG:', code)
2852 local f, err = utils.load(code,'tmp','t',env)
2853 if not f then assert(false, err .. ' with generated code ' .. code) end
2854 return f
2855 end
2856
2857
2858 -- Build Lua function from comprehension string.
2859 -- Uses environment env.
2860 local function build_comprehension(expr, env)
2861 local out, fortypes, invarlists, invallists, preds, opname, max_param
2862 = parse_comprehension(expr)
2863 local code = code_comprehension(
2864 out, fortypes, invarlists, invallists, preds, opname, max_param)
2865 local f = wrap_comprehension(code, #invarlists, max_param, invallists, env)
2866 return f
2867 end
2868
2869
2870 -- Creates new comprehension cache.
2871 -- Any list comprehension function created are set to the environment
2872 -- env (defaults to caller of new).
2873 local function new(env)
2874 -- Note: using a single global comprehension cache would have had
2875 -- security implications (e.g. retrieving cached functions created
2876 -- in other environments).
2877 -- The cache lookup function could have instead been written to retrieve
2878 -- the caller's environment, lookup up the cache private to that
2879 -- environment, and then looked up the function in that cache.
2880 -- That would avoid the need for this <new> call to
2881 -- explicitly manage caches; however, that might also have an undue
2882 -- performance penalty.
2883
2884 if not env then
2885 env = utils.getfenv(2)
2886 end
2887
2888 local mt = {}
2889 local cache = setmetatable({}, mt)
2890
2891 -- Index operator builds, caches, and returns Lua function
2892 -- corresponding to comprehension expression string.
2893 --
2894 -- Example: f = comprehension['x^2 for x']
2895 --
2896 function mt:__index(expr)
2897 local f = build_comprehension(expr, env)
2898 self[expr] = f -- cache
2899 return f
2900 end
2901
2902 -- Convenience syntax.
2903 -- Allows comprehension 'x^2 for x' instead of comprehension['x^2 for x'].
2904 mt.__call = mt.__index
2905
2906 cache.new = new
2907
2908 return cache
2909 end
2910
2911
2912 local comprehension = {}
2913 comprehension.new = new
2914
2915 return comprehension
2916
2917 end,
2918
2919 ["pl.config"] = function()
2920 --------------------
2921 -- Module: 'pl.config'
2922 --------------------
2923 --- Reads configuration files into a Lua table.
2924 -- Understands INI files, classic Unix config files, and simple
2925 -- delimited columns of values. See @{06-data.md.Reading_Configuration_Files|the Guide}
2926 --
2927 -- # test.config
2928 -- # Read timeout in seconds
2929 -- read.timeout=10
2930 -- # Write timeout in seconds
2931 -- write.timeout=5
2932 -- #acceptable ports
2933 -- ports = 1002,1003,1004
2934 --
2935 -- -- readconfig.lua
2936 -- local config = require 'config'
2937 -- local t = config.read 'test.config'
2938 -- print(pretty.write(t))
2939 --
2940 -- ### output #####
2941 -- {
2942 -- ports = {
2943 -- 1002,
2944 -- 1003,
2945 -- 1004
2946 -- },
2947 -- write_timeout = 5,
2948 -- read_timeout = 10
2949 -- }
2950 --
2951 -- @module pl.config
2952
2953 local type,tonumber,ipairs,io, table = _G.type,_G.tonumber,_G.ipairs,_G.io,_G.table
2954
2955 local function split(s,re)
2956 local res = {}
2957 local t_insert = table.insert
2958 re = '[^'..re..']+'
2959 for k in s:gmatch(re) do t_insert(res,k) end
2960 return res
2961 end
2962
2963 local function strip(s)
2964 return s:gsub('^%s+',''):gsub('%s+$','')
2965 end
2966
2967 local function strip_quotes (s)
2968 return s:gsub("['\"](.*)['\"]",'%1')
2969 end
2970
2971 local config = {}
2972
2973 --- like `io.lines`, but allows for lines to be continued with '`\\`'.
2974 -- @param file a file-like object (anything where read() returns the next line) or a filename.
2975 -- Defaults to standard input.
2976 -- @return an iterator over the lines, or nil
2977 -- @return error 'not a file-like object' or 'file is nil'
2978 function config.lines(file)
2979 local f,openf,err
2980 local line = ''
2981 if type(file) == 'string' then
2982 f,err = io.open(file,'r')
2983 if not f then return nil,err end
2984 openf = true
2985 else
2986 f = file or io.stdin
2987 if not file.read then return nil, 'not a file-like object' end
2988 end
2989 if not f then return nil, 'file is nil' end
2990 return function()
2991 local l = f:read()
2992 while l do
2993 -- only for non-blank lines that don't begin with either ';' or '#'
2994 if l:match '%S' and not l:match '^%s*[;#]' then
2995 -- does the line end with '\'?
2996 local i = l:find '\\%s*$'
2997 if i then -- if so,
2998 line = line..l:sub(1,i-1)
2999 elseif line == '' then
3000 return l
3001 else
3002 l = line..l
3003 line = ''
3004 return l
3005 end
3006 end
3007 l = f:read()
3008 end
3009 if openf then f:close() end
3010 end
3011 end
3012
3013 --- read a configuration file into a table
3014 -- @param file either a file-like object or a string, which must be a filename
3015 -- @tab[opt] cnfg a configuration table that may contain these fields:
3016 --
3017 -- * `smart` try to deduce what kind of config file we have (default false)
3018 -- * `variabilize` make names into valid Lua identifiers (default true)
3019 -- * `convert_numbers` try to convert values into numbers (default true)
3020 -- * `trim_space` ensure that there is no starting or trailing whitespace with values (default true)
3021 -- * `trim_quotes` remove quotes from strings (default false)
3022 -- * `list_delim` delimiter to use when separating columns (default ',')
3023 -- * `keysep` separator between key and value pairs (default '=')
3024 --
3025 -- @return a table containing items, or `nil`
3026 -- @return error message (same as @{config.lines}
3027 function config.read(file,cnfg)
3028 local auto
3029
3030 local iter,err = config.lines(file)
3031 if not iter then return nil,err end
3032 local line = iter()
3033 cnfg = cnfg or {}
3034 if cnfg.smart then
3035 auto = true
3036 if line:match '^[^=]+=' then
3037 cnfg.keysep = '='
3038 elseif line:match '^[^:]+:' then
3039 cnfg.keysep = ':'
3040 cnfg.list_delim = ':'
3041 elseif line:match '^%S+%s+' then
3042 cnfg.keysep = ' '
3043 -- more than two columns assume that it's a space-delimited list
3044 -- cf /etc/fstab with /etc/ssh/ssh_config
3045 if line:match '^%S+%s+%S+%s+%S+' then
3046 cnfg.list_delim = ' '
3047 end
3048 cnfg.variabilize = false
3049 end
3050 end
3051
3052
3053 local function check_cnfg (var,def)
3054 local val = cnfg[var]
3055 if val == nil then return def else return val end
3056 end
3057
3058 local initial_digits = '^[%d%+%-]'
3059 local t = {}
3060 local top_t = t
3061 local variabilize = check_cnfg ('variabilize',true)
3062 local list_delim = check_cnfg('list_delim',',')
3063 local convert_numbers = check_cnfg('convert_numbers',true)
3064 local convert_boolean = check_cnfg('convert_boolean',false)
3065 local trim_space = check_cnfg('trim_space',true)
3066 local trim_quotes = check_cnfg('trim_quotes',false)
3067 local ignore_assign = check_cnfg('ignore_assign',false)
3068 local keysep = check_cnfg('keysep','=')
3069 local keypat = keysep == ' ' and '%s+' or '%s*'..keysep..'%s*'
3070 if list_delim == ' ' then list_delim = '%s+' end
3071
3072 local function process_name(key)
3073 if variabilize then
3074 key = key:gsub('[^%w]','_')
3075 end
3076 return key
3077 end
3078
3079 local function process_value(value)
3080 if list_delim and value:find(list_delim) then
3081 value = split(value,list_delim)
3082 for i,v in ipairs(value) do
3083 value[i] = process_value(v)
3084 end
3085 elseif convert_numbers and value:find(initial_digits) then
3086 local val = tonumber(value)
3087 if not val and value:match ' kB$' then
3088 value = value:gsub(' kB','')
3089 val = tonumber(value)
3090 end
3091 if val then value = val end
3092 elseif convert_boolean and value == 'true' then
3093 return true
3094 elseif convert_boolean and value == 'false' then
3095 return false
3096 end
3097 if type(value) == 'string' then
3098 if trim_space then value = strip(value) end
3099 if not trim_quotes and auto and value:match '^"' then
3100 trim_quotes = true
3101 end
3102 if trim_quotes then value = strip_quotes(value) end
3103 end
3104 return value
3105 end
3106
3107 while line do
3108 if line:find('^%[') then -- section!
3109 local section = process_name(line:match('%[([^%]]+)%]'))
3110 t = top_t
3111 t[section] = {}
3112 t = t[section]
3113 else
3114 line = line:gsub('^%s*','')
3115 local i1,i2 = line:find(keypat)
3116 if i1 and not ignore_assign then -- key,value assignment
3117 local key = process_name(line:sub(1,i1-1))
3118 local value = process_value(line:sub(i2+1))
3119 t[key] = value
3120 else -- a plain list of values...
3121 t[#t+1] = process_value(line)
3122 end
3123 end
3124 line = iter()
3125 end
3126 return top_t
3127 end
3128
3129 return config
3130
3131 end,
3132
3133 ["pl.data"] = function()
3134 --------------------
3135 -- Module: 'pl.data'
3136 --------------------
3137 --- Reading and querying simple tabular data.
3138 --
3139 -- data.read 'test.txt'
3140 -- ==> {{10,20},{2,5},{40,50},fieldnames={'x','y'},delim=','}
3141 --
3142 -- Provides a way of creating basic SQL-like queries.
3143 --
3144 -- require 'pl'
3145 -- local d = data.read('xyz.txt')
3146 -- local q = d:select('x,y,z where x > 3 and z < 2 sort by y')
3147 -- for x,y,z in q do
3148 -- print(x,y,z)
3149 -- end
3150 --
3151 -- See @{06-data.md.Reading_Columnar_Data|the Guide}
3152 --
3153 -- Dependencies: `pl.utils`, `pl.array2d` (fallback methods)
3154 -- @module pl.data
3155
3156 local utils = require 'pl.utils'
3157 local _DEBUG = rawget(_G,'_DEBUG')
3158
3159 local patterns,function_arg,usplit,array_tostring = utils.patterns,utils.function_arg,utils.split,utils.array_tostring
3160 local append,concat = table.insert,table.concat
3161 local gsub = string.gsub
3162 local io = io
3163 local _G,print,type,tonumber,ipairs,setmetatable = _G,print,type,tonumber,ipairs,setmetatable
3164
3165
3166 local data = {}
3167
3168 local parse_select
3169
3170 local function rstrip(s)
3171 return (s:gsub('%s+$',''))
3172 end
3173
3174 local function strip (s)
3175 return (rstrip(s):gsub('^%s*',''))
3176 end
3177
3178 -- This gives `l` the standard List metatable,
3179 -- pulling in the List module.
3180 local function makelist(l)
3181 return setmetatable(l, require('pl.List'))
3182 end
3183
3184 local function map(fun,t)
3185 local res = {}
3186 for i = 1,#t do
3187 res[i] = fun(t[i])
3188 end
3189 return res
3190 end
3191
3192 local function split(line,delim,csv,n)
3193 local massage
3194 -- CSV fields may be double-quoted and may contain commas!
3195 if csv and line:match '"' then
3196 line = line:gsub('"([^"]+)"',function(str)
3197 local s,cnt = str:gsub(',','\001')
3198 if cnt > 0 then massage = true end
3199 return s
3200 end)
3201 if massage then
3202 massage = function(s) return (s:gsub('\001',',')) end
3203 end
3204 end
3205 local res = (usplit(line,delim,false,n))
3206 if csv then
3207 -- restore CSV commas-in-fields
3208 if massage then res = map(massage,res) end
3209 -- in CSV mode trailiing commas are significant!
3210 if line:match ',$' then append(res,'') end
3211 end
3212 return makelist(res)
3213 end
3214
3215 local function find(t,v)
3216 for i = 1,#t do
3217 if v == t[i] then return i end
3218 end
3219 end
3220
3221 local DataMT = {
3222 column_by_name = function(self,name)
3223 if type(name) == 'number' then
3224 name = '$'..name
3225 end
3226 local arr = {}
3227 for res in data.query(self,name) do
3228 append(arr,res)
3229 end
3230 return makelist(arr)
3231 end,
3232
3233 copy_select = function(self,condn)
3234 condn = parse_select(condn,self)
3235 local iter = data.query(self,condn)
3236 local res = {}
3237 local row = makelist{iter()}
3238 while #row > 0 do
3239 append(res,row)
3240 row = makelist{iter()}
3241 end
3242 res.delim = self.delim
3243 return data.new(res,split(condn.fields,','))
3244 end,
3245
3246 column_names = function(self)
3247 return self.fieldnames
3248 end,
3249 }
3250
3251 local array2d
3252
3253 DataMT.__index = function(self,name)
3254 local f = DataMT[name]
3255 if f then return f end
3256 if not array2d then
3257 array2d = require 'pl.array2d'
3258 end
3259 return array2d[name]
3260 end
3261
3262 --- return a particular column as a list of values (method).
3263 -- @param name either name of column, or numerical index.
3264 -- @function Data.column_by_name
3265
3266 --- return a query iterator on this data (method).
3267 -- @string condn the query expression
3268 -- @function Data.select
3269 -- @see data.query
3270
3271 --- return a row iterator on this data (method).
3272 -- @string condn the query expression
3273 -- @function Data.select_row
3274
3275 --- return a new data object based on this query (method).
3276 -- @string condn the query expression
3277 -- @function Data.copy_select
3278
3279 --- return the field names of this data object (method).
3280 -- @function Data.column_names
3281
3282 --- write out a row (method).
3283 -- @param f file-like object
3284 -- @function Data.write_row
3285
3286 --- write data out to file (method).
3287 -- @param f file-like object
3288 -- @function Data.write
3289
3290
3291 -- [guessing delimiter] We check for comma, tab and spaces in that order.
3292 -- [issue] any other delimiters to be checked?
3293 local delims = {',', '\t', ' ', ';'}
3294
3295 local function guess_delim (line)
3296 if line=='' then return ' ' end
3297 for _,delim in ipairs(delims) do
3298 if line:find(delim) then
3299 return delim == ' ' and '%s+' or delim
3300 end
3301 end
3302 return ' '
3303 end
3304
3305 -- [file parameter] If it's a string, we try open as a filename. If nil, then
3306 -- either stdin or stdout depending on the mode. Otherwise, check if this is
3307 -- a file-like object (implements read or write depending)
3308 local function open_file (f,mode)
3309 local opened, err
3310 local reading = mode == 'r'
3311 if type(f) == 'string' then
3312 if f == 'stdin' then
3313 f = io.stdin
3314 elseif f == 'stdout' then
3315 f = io.stdout
3316 else
3317 f,err = io.open(f,mode)
3318 if not f then return nil,err end
3319 opened = true
3320 end
3321 end
3322 if f and ((reading and not f.read) or (not reading and not f.write)) then
3323 return nil, "not a file-like object"
3324 end
3325 return f,nil,opened
3326 end
3327
3328 --- read a delimited file in a Lua table.
3329 -- By default, attempts to treat first line as separated list of fieldnames.
3330 -- @param file a filename or a file-like object
3331 -- @tab cnfg parsing options
3332 -- @string cnfg.delim a string pattern to split fields
3333 -- @array cnfg.fieldnames (i.e. don't read from first line)
3334 -- @bool cnfg.no_convert (default is to try conversion on first data line)
3335 -- @tab cnfg.convert table of custom conversion functions with column keys
3336 -- @int cnfg.numfields indices of columns known to be numbers
3337 -- @bool cnfg.last_field_collect only split as many fields as fieldnames.
3338 -- @int cnfg.thousands_dot thousands separator in Excel CSV is '.'
3339 -- @bool cnfg.csv fields may be double-quoted and contain commas;
3340 -- Also, empty fields are considered to be equivalent to zero.
3341 -- @return `data` object, or `nil`
3342 -- @return error message. May be a file error, 'not a file-like object'
3343 -- or a conversion error
3344 function data.read(file,cnfg)
3345 local count,line
3346 local D = {}
3347 if not cnfg then cnfg = {} end
3348 local f,err,opened = open_file(file,'r')
3349 if not f then return nil, err end
3350 local thousands_dot = cnfg.thousands_dot
3351 local csv = cnfg.csv
3352 if csv then cnfg.delim = ',' end
3353
3354 -- note that using dot as the thousands separator (@thousands_dot)
3355 -- requires a special conversion function! For CSV, _empty fields_ are
3356 -- considered to default to numerical zeroes.
3357 local tonumber = tonumber
3358 local function try_number(x)
3359 if thousands_dot then x = x:gsub('%.(...)','%1') end
3360 if csv and x == '' then x = '0' end
3361 local v = tonumber(x)
3362 if v == nil then return nil,"not a number" end
3363 return v
3364 end
3365
3366 count = 1
3367 line = f:read()
3368 if not line then return nil, "empty file" end
3369
3370 -- first question: what is the delimiter?
3371 D.delim = cnfg.delim and cnfg.delim or guess_delim(line)
3372 local delim = D.delim
3373
3374 local conversion
3375 local numfields = {}
3376 local function append_conversion (idx,conv)
3377 conversion = conversion or {}
3378 append(numfields,idx)
3379 append(conversion,conv)
3380 end
3381 if cnfg.numfields then
3382 for _,n in ipairs(cnfg.numfields) do append_conversion(n,try_number) end
3383 end
3384
3385 -- some space-delimited data starts with a space. This should not be a column,
3386 -- although it certainly would be for comma-separated, etc.
3387 local stripper
3388 if delim == '%s+' and line:find(delim) == 1 then
3389 stripper = function(s) return s:gsub('^%s+','') end
3390 line = stripper(line)
3391 end
3392 -- first line will usually be field names. Unless fieldnames are specified,
3393 -- we check if it contains purely numerical values for the case of reading
3394 -- plain data files.
3395 if not cnfg.fieldnames then
3396 local fields,nums
3397 fields = split(line,delim,csv)
3398 if not cnfg.convert then
3399 nums = map(tonumber,fields)
3400 if #nums == #fields then -- they're ALL numbers!
3401 append(D,nums) -- add the first converted row
3402 -- and specify conversions for subsequent rows
3403 for i = 1,#nums do append_conversion(i,try_number) end
3404 else -- we'll try to check numbers just now..
3405 nums = nil
3406 end
3407 else -- [explicit column conversions] (any deduced number conversions will be added)
3408 for idx,conv in pairs(cnfg.convert) do append_conversion(idx,conv) end
3409 end
3410 if nums == nil then
3411 cnfg.fieldnames = fields
3412 end
3413 line = f:read()
3414 count = count + 1
3415 if stripper then line = stripper(line) end
3416 elseif type(cnfg.fieldnames) == 'string' then
3417 cnfg.fieldnames = split(cnfg.fieldnames,delim,csv)
3418 end
3419 local nfields
3420 -- at this point, the column headers have been read in. If the first
3421 -- row consisted of numbers, it has already been added to the dataset.
3422 if cnfg.fieldnames then
3423 D.fieldnames = cnfg.fieldnames
3424 -- [collecting end field] If @last_field_collect then we'll
3425 -- only split as many fields as there are fieldnames
3426 if cnfg.last_field_collect then
3427 nfields = #D.fieldnames
3428 end
3429 -- [implicit column conversion] unless @no_convert, we need the numerical field indices
3430 -- of the first data row. These can also be specified explicitly by @numfields.
3431 if not cnfg.no_convert then
3432 local fields = split(line,D.delim,csv,nfields)
3433 for i = 1,#fields do
3434 if not find(numfields,i) and try_number(fields[i]) then
3435 append_conversion(i,try_number)
3436 end
3437 end
3438 end
3439 end
3440 -- keep going until finished
3441 while line do
3442 if not line:find ('^%s*$') then -- [blank lines] ignore them!
3443 if stripper then line = stripper(line) end
3444 local fields = split(line,delim,csv,nfields)
3445 if conversion then -- there were field conversions...
3446 for k = 1,#numfields do
3447 local i,conv = numfields[k],conversion[k]
3448 local val,err = conv(fields[i])
3449 if val == nil then
3450 return nil, err..": "..fields[i].." at line "..count
3451 else
3452 fields[i] = val
3453 end
3454 end
3455 end
3456 append(D,fields)
3457 end
3458 line = f:read()
3459 count = count + 1
3460 end
3461 if opened then f:close() end
3462 if delim == '%s+' then D.delim = ' ' end
3463 if not D.fieldnames then D.fieldnames = {} end
3464 return data.new(D)
3465 end
3466
3467 local function write_row (data,f,row,delim)
3468 data.temp = array_tostring(row,data.temp)
3469 f:write(concat(data.temp,delim),'\n')
3470 end
3471
3472 function DataMT:write_row(f,row)
3473 write_row(self,f,row,self.delim)
3474 end
3475
3476 --- write 2D data to a file.
3477 -- Does not assume that the data has actually been
3478 -- generated with `new` or `read`.
3479 -- @param data 2D array
3480 -- @param file filename or file-like object
3481 -- @tparam[opt] {string} fieldnames list of fields (optional)
3482 -- @string[opt='\t'] delim delimiter (default tab)
3483 -- @return true or nil, error
3484 function data.write (data,file,fieldnames,delim)
3485 local f,err,opened = open_file(file,'w')
3486 if not f then return nil, err end
3487 if not fieldnames then
3488 fieldnames = data.fieldnames
3489 end
3490 delim = delim or '\t'
3491 if fieldnames and #fieldnames > 0 then
3492 f:write(concat(fieldnames,delim),'\n')
3493 end
3494 for i = 1,#data do
3495 write_row(data,f,data[i],delim)
3496 end
3497 if opened then f:close() end
3498 return true
3499 end
3500
3501
3502 function DataMT:write(file)
3503 data.write(self,file,self.fieldnames,self.delim)
3504 end
3505
3506 local function massage_fieldnames (fields,copy)
3507 -- fieldnames must be valid Lua identifiers; ignore any surrounding padding
3508 -- but keep the original fieldnames...
3509 for i = 1,#fields do
3510 local f = strip(fields[i])
3511 copy[i] = f
3512 fields[i] = f:gsub('%W','_')
3513 end
3514 end
3515
3516 --- create a new dataset from a table of rows.
3517 -- Can specify the fieldnames, else the table must have a field called
3518 -- 'fieldnames', which is either a string of delimiter-separated names,
3519 -- or a table of names. <br>
3520 -- If the table does not have a field called 'delim', then an attempt will be
3521 -- made to guess it from the fieldnames string, defaults otherwise to tab.
3522 -- @param d the table.
3523 -- @tparam[opt] {string} fieldnames optional fieldnames
3524 -- @return the table.
3525 function data.new (d,fieldnames)
3526 d.fieldnames = d.fieldnames or fieldnames or ''
3527 if not d.delim and type(d.fieldnames) == 'string' then
3528 d.delim = guess_delim(d.fieldnames)
3529 d.fieldnames = split(d.fieldnames,d.delim)
3530 end
3531 d.fieldnames = makelist(d.fieldnames)
3532 d.original_fieldnames = {}
3533 massage_fieldnames(d.fieldnames,d.original_fieldnames)
3534 setmetatable(d,DataMT)
3535 -- a query with just the fieldname will return a sequence
3536 -- of values, which seq.copy turns into a table.
3537 return d
3538 end
3539
3540 local sorted_query = [[
3541 return function (t)
3542 local i = 0
3543 local v
3544 local ls = {}
3545 for i,v in ipairs(t) do
3546 if CONDITION then
3547 ls[#ls+1] = v
3548 end
3549 end
3550 table.sort(ls,function(v1,v2)
3551 return SORT_EXPR
3552 end)
3553 local n = #ls
3554 return function()
3555 i = i + 1
3556 v = ls[i]
3557 if i > n then return end
3558 return FIELDLIST
3559 end
3560 end
3561 ]]
3562
3563 -- question: is this optimized case actually worth the extra code?
3564 local simple_query = [[
3565 return function (t)
3566 local n = #t
3567 local i = 0
3568 local v
3569 return function()
3570 repeat
3571 i = i + 1
3572 v = t[i]
3573 until i > n or CONDITION
3574 if i > n then return end
3575 return FIELDLIST
3576 end
3577 end
3578 ]]
3579
3580 local function is_string (s)
3581 return type(s) == 'string'
3582 end
3583
3584 local field_error
3585
3586 local function fieldnames_as_string (data)
3587 return concat(data.fieldnames,',')
3588 end
3589
3590 local function massage_fields(data,f)
3591 local idx
3592 if f:find '^%d+$' then
3593 idx = tonumber(f)
3594 else
3595 idx = find(data.fieldnames,f)
3596 end
3597 if idx then
3598 return 'v['..idx..']'
3599 else
3600 field_error = f..' not found in '..fieldnames_as_string(data)
3601 return f
3602 end
3603 end
3604
3605
3606 local function process_select (data,parms)
3607 --- preparing fields ----
3608 field_error = nil
3609 local fields = parms.fields
3610 local numfields = fields:find '%$' or #data.fieldnames == 0
3611 if fields:find '^%s*%*%s*' then
3612 if not numfields then
3613 fields = fieldnames_as_string(data)
3614 else
3615 local ncol = #data[1]
3616 fields = {}
3617 for i = 1,ncol do append(fields,'$'..i) end
3618 fields = concat(fields,',')
3619 end
3620 end
3621 local idpat = patterns.IDEN
3622 if numfields then
3623 idpat = '%$(%d+)'
3624 else
3625 -- massage field names to replace non-identifier chars
3626 fields = rstrip(fields):gsub('[^,%w]','_')
3627 end
3628 local massage_fields = utils.bind1(massage_fields,data)
3629 local ret = gsub(fields,idpat,massage_fields)
3630 if field_error then return nil,field_error end
3631 parms.fields = fields
3632 parms.proc_fields = ret
3633 parms.where = parms.where or 'true'
3634 if is_string(parms.where) then
3635 parms.where = gsub(parms.where,idpat,massage_fields)
3636 field_error = nil
3637 end
3638 return true
3639 end
3640
3641
3642 parse_select = function(s,data)
3643 local endp
3644 local parms = {}
3645 local w1,w2 = s:find('where ')
3646 local s1,s2 = s:find('sort by ')
3647 if w1 then -- where clause!
3648 endp = (s1 or 0)-1
3649 parms.where = s:sub(w2+1,endp)
3650 end
3651 if s1 then -- sort by clause (must be last!)
3652 parms.sort_by = s:sub(s2+1)
3653 end
3654 endp = (w1 or s1 or 0)-1
3655 parms.fields = s:sub(1,endp)
3656 local status,err = process_select(data,parms)
3657 if not status then return nil,err
3658 else return parms end
3659 end
3660
3661 --- create a query iterator from a select string.
3662 -- Select string has this format: <br>
3663 -- FIELDLIST [ where LUA-CONDN [ sort by FIELD] ]<br>
3664 -- FIELDLIST is a comma-separated list of valid fields, or '*'. <br> <br>
3665 -- The condition can also be a table, with fields 'fields' (comma-sep string or
3666 -- table), 'sort_by' (string) and 'where' (Lua expression string or function)
3667 -- @param data table produced by read
3668 -- @param condn select string or table
3669 -- @param context a list of tables to be searched when resolving functions
3670 -- @param return_row if true, wrap the results in a row table
3671 -- @return an iterator over the specified fields, or nil
3672 -- @return an error message
3673 function data.query(data,condn,context,return_row)
3674 local err
3675 if is_string(condn) then
3676 condn,err = parse_select(condn,data)
3677 if not condn then return nil,err end
3678 elseif type(condn) == 'table' then
3679 if type(condn.fields) == 'table' then
3680 condn.fields = concat(condn.fields,',')
3681 end
3682 if not condn.proc_fields then
3683 local status,err = process_select(data,condn)
3684 if not status then return nil,err end
3685 end
3686 else
3687 return nil, "condition must be a string or a table"
3688 end
3689 local query
3690 if condn.sort_by then -- use sorted_query
3691 query = sorted_query
3692 else
3693 query = simple_query
3694 end
3695 local fields = condn.proc_fields or condn.fields
3696 if return_row then
3697 fields = '{'..fields..'}'
3698 end
3699 query = query:gsub('FIELDLIST',fields)
3700 if is_string(condn.where) then
3701 query = query:gsub('CONDITION',condn.where)
3702 condn.where = nil
3703 else
3704 query = query:gsub('CONDITION','_condn(v)')
3705 condn.where = function_arg(0,condn.where,'condition.where must be callable')
3706 end
3707 if condn.sort_by then
3708 local expr,sort_var,sort_dir
3709 local sort_by = condn.sort_by
3710 local i1,i2 = sort_by:find('%s+')
3711 if i1 then
3712 sort_var,sort_dir = sort_by:sub(1,i1-1),sort_by:sub(i2+1)
3713 else
3714 sort_var = sort_by
3715 sort_dir = 'asc'
3716 end
3717 if sort_var:match '^%$' then sort_var = sort_var:sub(2) end
3718 sort_var = massage_fields(data,sort_var)
3719 if field_error then return nil,field_error end
3720 if sort_dir == 'asc' then
3721 sort_dir = '<'
3722 else
3723 sort_dir = '>'
3724 end
3725 expr = ('%s %s %s'):format(sort_var:gsub('v','v1'),sort_dir,sort_var:gsub('v','v2'))
3726 query = query:gsub('SORT_EXPR',expr)
3727 end
3728 if condn.where then
3729 query = 'return function(_condn) '..query..' end'
3730 end
3731 if _DEBUG then print(query) end
3732
3733 local fn,err = utils.load(query,'tmp')
3734 if not fn then return nil,err end
3735 fn = fn() -- get the function
3736 if condn.where then
3737 fn = fn(condn.where)
3738 end
3739 local qfun = fn(data)
3740 if context then
3741 -- [specifying context for condition] @context is a list of tables which are
3742 -- 'injected'into the condition's custom context
3743 append(context,_G)
3744 local lookup = {}
3745 utils.setfenv(qfun,lookup)
3746 setmetatable(lookup,{
3747 __index = function(tbl,key)
3748 -- _G.print(tbl,key)
3749 for k,t in ipairs(context) do
3750 if t[key] then return t[key] end
3751 end
3752 end
3753 })
3754 end
3755 return qfun
3756 end
3757
3758
3759 DataMT.select = data.query
3760 DataMT.select_row = function(d,condn,context)
3761 return data.query(d,condn,context,true)
3762 end
3763
3764 --- Filter input using a query.
3765 -- @string Q a query string
3766 -- @param infile filename or file-like object
3767 -- @param outfile filename or file-like object
3768 -- @bool dont_fail true if you want to return an error, not just fail
3769 function data.filter (Q,infile,outfile,dont_fail)
3770 local d = data.read(infile or 'stdin')
3771 local out = open_file(outfile or 'stdout')
3772 local iter,err = d:select(Q)
3773 local delim = d.delim
3774 if not iter then
3775 err = 'error: '..err
3776 if dont_fail then
3777 return nil,err
3778 else
3779 utils.quit(1,err)
3780 end
3781 end
3782 while true do
3783 local res = {iter()}
3784 if #res == 0 then break end
3785 out:write(concat(res,delim),'\n')
3786 end
3787 end
3788
3789 return data
3790
3791
3792 end,
3793
3794 ["pl.Date"] = function()
3795 --------------------
3796 -- Module: 'pl.Date'
3797 --------------------
3798 --- Date and Date Format classes.
3799 -- See @{05-dates.md|the Guide}.
3800 --
3801 -- NOTE: the date module is deprecated! see
3802 -- https://github.com/lunarmodules/Penlight/issues/285
3803 --
3804 -- Dependencies: `pl.class`, `pl.stringx`, `pl.utils`
3805 -- @classmod pl.Date
3806 -- @pragma nostrip
3807
3808 local class = require 'pl.class'
3809 local os_time, os_date = os.time, os.date
3810 local stringx = require 'pl.stringx'
3811 local utils = require 'pl.utils'
3812 local assert_arg,assert_string = utils.assert_arg,utils.assert_string
3813
3814
3815 utils.raise_deprecation {
3816 source = "Penlight " .. utils._VERSION,
3817 message = "the 'Date' module is deprecated, see https://github.com/lunarmodules/Penlight/issues/285",
3818 version_removed = "2.0.0",
3819 version_deprecated = "1.9.2",
3820 }
3821
3822
3823 local Date = class()
3824 Date.Format = class()
3825
3826 --- Date constructor.
3827 -- @param t this can be either
3828 --
3829 -- * `nil` or empty - use current date and time
3830 -- * number - seconds since epoch (as returned by `os.time`). Resulting time is UTC
3831 -- * `Date` - make a copy of this date
3832 -- * table - table containing year, month, etc as for `os.time`. You may leave out year, month or day,
3833 -- in which case current values will be used.
3834 -- * year (will be followed by month, day etc)
3835 --
3836 -- @param ... true if Universal Coordinated Time, or two to five numbers: month,day,hour,min,sec
3837 -- @function Date
3838 function Date:_init(t,...)
3839 local time
3840 local nargs = select('#',...)
3841 if nargs > 2 then
3842 local extra = {...}
3843 local year = t
3844 t = {
3845 year = year,
3846 month = extra[1],
3847 day = extra[2],
3848 hour = extra[3],
3849 min = extra[4],
3850 sec = extra[5]
3851 }
3852 end
3853 if nargs == 1 then
3854 self.utc = select(1,...) == true
3855 end
3856 if t == nil or t == 'utc' then
3857 time = os_time()
3858 self.utc = t == 'utc'
3859 elseif type(t) == 'number' then
3860 time = t
3861 if self.utc == nil then self.utc = true end
3862 elseif type(t) == 'table' then
3863 if getmetatable(t) == Date then -- copy ctor
3864 time = t.time
3865 self.utc = t.utc
3866 else
3867 if not (t.year and t.month) then
3868 local lt = os_date('*t')
3869 if not t.year and not t.month and not t.day then
3870 t.year = lt.year
3871 t.month = lt.month
3872 t.day = lt.day
3873 else
3874 t.year = t.year or lt.year
3875 t.month = t.month or (t.day and lt.month or 1)
3876 t.day = t.day or 1
3877 end
3878 end
3879 t.day = t.day or 1
3880 time = os_time(t)
3881 end
3882 else
3883 error("bad type for Date constructor: "..type(t),2)
3884 end
3885 self:set(time)
3886 end
3887
3888 --- set the current time of this Date object.
3889 -- @int t seconds since epoch
3890 function Date:set(t)
3891 self.time = t
3892 if self.utc then
3893 self.tab = os_date('!*t',t)
3894 else
3895 self.tab = os_date('*t',t)
3896 end
3897 end
3898
3899 --- get the time zone offset from UTC.
3900 -- @int ts seconds ahead of UTC
3901 function Date.tzone (ts)
3902 if ts == nil then
3903 ts = os_time()
3904 elseif type(ts) == "table" then
3905 if getmetatable(ts) == Date then
3906 ts = ts.time
3907 else
3908 ts = Date(ts).time
3909 end
3910 end
3911 local utc = os_date('!*t',ts)
3912 local lcl = os_date('*t',ts)
3913 lcl.isdst = false
3914 return os.difftime(os_time(lcl), os_time(utc))
3915 end
3916
3917 --- convert this date to UTC.
3918 function Date:toUTC ()
3919 local ndate = Date(self)
3920 if not self.utc then
3921 ndate.utc = true
3922 ndate:set(ndate.time)
3923 end
3924 return ndate
3925 end
3926
3927 --- convert this UTC date to local.
3928 function Date:toLocal ()
3929 local ndate = Date(self)
3930 if self.utc then
3931 ndate.utc = false
3932 ndate:set(ndate.time)
3933 --~ ndate:add { sec = Date.tzone(self) }
3934 end
3935 return ndate
3936 end
3937
3938 --- set the year.
3939 -- @int y Four-digit year
3940 -- @class function
3941 -- @name Date:year
3942
3943 --- set the month.
3944 -- @int m month
3945 -- @class function
3946 -- @name Date:month
3947
3948 --- set the day.
3949 -- @int d day
3950 -- @class function
3951 -- @name Date:day
3952
3953 --- set the hour.
3954 -- @int h hour
3955 -- @class function
3956 -- @name Date:hour
3957
3958 --- set the minutes.
3959 -- @int min minutes
3960 -- @class function
3961 -- @name Date:min
3962
3963 --- set the seconds.
3964 -- @int sec seconds
3965 -- @class function
3966 -- @name Date:sec
3967
3968 --- set the day of year.
3969 -- @class function
3970 -- @int yday day of year
3971 -- @name Date:yday
3972
3973 --- get the year.
3974 -- @int y Four-digit year
3975 -- @class function
3976 -- @name Date:year
3977
3978 --- get the month.
3979 -- @class function
3980 -- @name Date:month
3981
3982 --- get the day.
3983 -- @class function
3984 -- @name Date:day
3985
3986 --- get the hour.
3987 -- @class function
3988 -- @name Date:hour
3989
3990 --- get the minutes.
3991 -- @class function
3992 -- @name Date:min
3993
3994 --- get the seconds.
3995 -- @class function
3996 -- @name Date:sec
3997
3998 --- get the day of year.
3999 -- @class function
4000 -- @name Date:yday
4001
4002
4003 for _,c in ipairs{'year','month','day','hour','min','sec','yday'} do
4004 Date[c] = function(self,val)
4005 if val then
4006 assert_arg(1,val,"number")
4007 self.tab[c] = val
4008 self:set(os_time(self.tab))
4009 return self
4010 else
4011 return self.tab[c]
4012 end
4013 end
4014 end
4015
4016 --- name of day of week.
4017 -- @bool full abbreviated if true, full otherwise.
4018 -- @ret string name
4019 function Date:weekday_name(full)
4020 return os_date(full and '%A' or '%a',self.time)
4021 end
4022
4023 --- name of month.
4024 -- @int full abbreviated if true, full otherwise.
4025 -- @ret string name
4026 function Date:month_name(full)
4027 return os_date(full and '%B' or '%b',self.time)
4028 end
4029
4030 --- is this day on a weekend?.
4031 function Date:is_weekend()
4032 return self.tab.wday == 1 or self.tab.wday == 7
4033 end
4034
4035 --- add to a date object.
4036 -- @param t a table containing one of the following keys and a value:
4037 -- one of `year`,`month`,`day`,`hour`,`min`,`sec`
4038 -- @return this date
4039 function Date:add(t)
4040 local old_dst = self.tab.isdst
4041 local key,val = next(t)
4042 self.tab[key] = self.tab[key] + val
4043 self:set(os_time(self.tab))
4044 if old_dst ~= self.tab.isdst then
4045 self.tab.hour = self.tab.hour - (old_dst and 1 or -1)
4046 self:set(os_time(self.tab))
4047 end
4048 return self
4049 end
4050
4051 --- last day of the month.
4052 -- @return int day
4053 function Date:last_day()
4054 local d = 28
4055 local m = self.tab.month
4056 while self.tab.month == m do
4057 d = d + 1
4058 self:add{day=1}
4059 end
4060 self:add{day=-1}
4061 return self
4062 end
4063
4064 --- difference between two Date objects.
4065 -- @tparam Date other Date object
4066 -- @treturn Date.Interval object
4067 function Date:diff(other)
4068 local dt = self.time - other.time
4069 if dt < 0 then error("date difference is negative!",2) end
4070 return Date.Interval(dt)
4071 end
4072
4073 --- long numerical ISO data format version of this date.
4074 function Date:__tostring()
4075 local fmt = '%Y-%m-%dT%H:%M:%S'
4076 if self.utc then
4077 fmt = "!"..fmt
4078 end
4079 local t = os_date(fmt,self.time)
4080 if self.utc then
4081 return t .. 'Z'
4082 else
4083 local offs = self:tzone()
4084 if offs == 0 then
4085 return t .. 'Z'
4086 end
4087 local sign = offs > 0 and '+' or '-'
4088 local h = math.ceil(offs/3600)
4089 local m = (offs % 3600)/60
4090 if m == 0 then
4091 return t .. ('%s%02d'):format(sign,h)
4092 else
4093 return t .. ('%s%02d:%02d'):format(sign,h,m)
4094 end
4095 end
4096 end
4097
4098 --- equality between Date objects.
4099 function Date:__eq(other)
4100 return self.time == other.time
4101 end
4102
4103 --- ordering between Date objects.
4104 function Date:__lt(other)
4105 return self.time < other.time
4106 end
4107
4108 --- difference between Date objects.
4109 -- @function Date:__sub
4110 Date.__sub = Date.diff
4111
4112 --- add a date and an interval.
4113 -- @param other either a `Date.Interval` object or a table such as
4114 -- passed to `Date:add`
4115 function Date:__add(other)
4116 local nd = Date(self)
4117 if Date.Interval:class_of(other) then
4118 other = {sec=other.time}
4119 end
4120 nd:add(other)
4121 return nd
4122 end
4123
4124 Date.Interval = class(Date)
4125
4126 ---- Date.Interval constructor
4127 -- @int t an interval in seconds
4128 -- @function Date.Interval
4129 function Date.Interval:_init(t)
4130 self:set(t)
4131 end
4132
4133 function Date.Interval:set(t)
4134 self.time = t
4135 self.tab = os_date('!*t',self.time)
4136 end
4137
4138 local function ess(n)
4139 if n > 1 then return 's '
4140 else return ' '
4141 end
4142 end
4143
4144 --- If it's an interval then the format is '2 hours 29 sec' etc.
4145 function Date.Interval:__tostring()
4146 local t, res = self.tab, ''
4147 local y,m,d = t.year - 1970, t.month - 1, t.day - 1
4148 if y > 0 then res = res .. y .. ' year'..ess(y) end
4149 if m > 0 then res = res .. m .. ' month'..ess(m) end
4150 if d > 0 then res = res .. d .. ' day'..ess(d) end
4151 if y == 0 and m == 0 then
4152 local h = t.hour
4153 if h > 0 then res = res .. h .. ' hour'..ess(h) end
4154 if t.min > 0 then res = res .. t.min .. ' min ' end
4155 if t.sec > 0 then res = res .. t.sec .. ' sec ' end
4156 end
4157 if res == '' then res = 'zero' end
4158 return res
4159 end
4160
4161 ------------ Date.Format class: parsing and renderinig dates ------------
4162
4163 -- short field names, explicit os.date names, and a mask for allowed field repeats
4164 local formats = {
4165 d = {'day',{true,true}},
4166 y = {'year',{false,true,false,true}},
4167 m = {'month',{true,true}},
4168 H = {'hour',{true,true}},
4169 M = {'min',{true,true}},
4170 S = {'sec',{true,true}},
4171 }
4172
4173 --- Date.Format constructor.
4174 -- @string fmt. A string where the following fields are significant:
4175 --
4176 -- * d day (either d or dd)
4177 -- * y year (either yy or yyy)
4178 -- * m month (either m or mm)
4179 -- * H hour (either H or HH)
4180 -- * M minute (either M or MM)
4181 -- * S second (either S or SS)
4182 --
4183 -- Alternatively, if fmt is nil then this returns a flexible date parser
4184 -- that tries various date/time schemes in turn:
4185 --
4186 -- * [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601), like `2010-05-10 12:35:23Z` or `2008-10-03T14:30+02`
4187 -- * times like 15:30 or 8.05pm (assumed to be today's date)
4188 -- * dates like 28/10/02 (European order!) or 5 Feb 2012
4189 -- * month name like march or Mar (case-insensitive, first 3 letters); here the
4190 -- day will be 1 and the year this current year
4191 --
4192 -- A date in format 3 can be optionally followed by a time in format 2.
4193 -- Please see test-date.lua in the tests folder for more examples.
4194 -- @usage df = Date.Format("yyyy-mm-dd HH:MM:SS")
4195 -- @class function
4196 -- @name Date.Format
4197 function Date.Format:_init(fmt)
4198 if not fmt then
4199 self.fmt = '%Y-%m-%d %H:%M:%S'
4200 self.outf = self.fmt
4201 self.plain = true
4202 return
4203 end
4204 local append = table.insert
4205 local D,PLUS,OPENP,CLOSEP = '\001','\002','\003','\004'
4206 local vars,used = {},{}
4207 local patt,outf = {},{}
4208 local i = 1
4209 while i < #fmt do
4210 local ch = fmt:sub(i,i)
4211 local df = formats[ch]
4212 if df then
4213 if used[ch] then error("field appeared twice: "..ch,4) end
4214 used[ch] = true
4215 -- this field may be repeated
4216 local _,inext = fmt:find(ch..'+',i+1)
4217 local cnt = not _ and 1 or inext-i+1
4218 if not df[2][cnt] then error("wrong number of fields: "..ch,4) end
4219 -- single chars mean 'accept more than one digit'
4220 local p = cnt==1 and (D..PLUS) or (D):rep(cnt)
4221 append(patt,OPENP..p..CLOSEP)
4222 append(vars,ch)
4223 if ch == 'y' then
4224 append(outf,cnt==2 and '%y' or '%Y')
4225 else
4226 append(outf,'%'..ch)
4227 end
4228 i = i + cnt
4229 else
4230 append(patt,ch)
4231 append(outf,ch)
4232 i = i + 1
4233 end
4234 end
4235 -- escape any magic characters
4236 fmt = utils.escape(table.concat(patt))
4237 -- fmt = table.concat(patt):gsub('[%-%.%+%[%]%(%)%$%^%%%?%*]','%%%1')
4238 -- replace markers with their magic equivalents
4239 fmt = fmt:gsub(D,'%%d'):gsub(PLUS,'+'):gsub(OPENP,'('):gsub(CLOSEP,')')
4240 self.fmt = fmt
4241 self.outf = table.concat(outf)
4242 self.vars = vars
4243 end
4244
4245 local parse_date
4246
4247 --- parse a string into a Date object.
4248 -- @string str a date string
4249 -- @return date object
4250 function Date.Format:parse(str)
4251 assert_string(1,str)
4252 if self.plain then
4253 return parse_date(str,self.us)
4254 end
4255 local res = {str:match(self.fmt)}
4256 if #res==0 then return nil, 'cannot parse '..str end
4257 local tab = {}
4258 for i,v in ipairs(self.vars) do
4259 local name = formats[v][1] -- e.g. 'y' becomes 'year'
4260 tab[name] = tonumber(res[i])
4261 end
4262 -- os.date() requires these fields; if not present, we assume
4263 -- that the time set is for the current day.
4264 if not (tab.year and tab.month and tab.day) then
4265 local today = Date()
4266 tab.year = tab.year or today:year()
4267 tab.month = tab.month or today:month()
4268 tab.day = tab.day or today:day()
4269 end
4270 local Y = tab.year
4271 if Y < 100 then -- classic Y2K pivot
4272 tab.year = Y + (Y < 35 and 2000 or 1999)
4273 elseif not Y then
4274 tab.year = 1970
4275 end
4276 return Date(tab)
4277 end
4278
4279 --- convert a Date object into a string.
4280 -- @param d a date object, or a time value as returned by @{os.time}
4281 -- @return string
4282 function Date.Format:tostring(d)
4283 local tm
4284 local fmt = self.outf
4285 if type(d) == 'number' then
4286 tm = d
4287 else
4288 tm = d.time
4289 if d.utc then
4290 fmt = '!'..fmt
4291 end
4292 end
4293 return os_date(fmt,tm)
4294 end
4295
4296 --- force US order in dates like 9/11/2001
4297 function Date.Format:US_order(yesno)
4298 self.us = yesno
4299 end
4300
4301 --local months = {jan=1,feb=2,mar=3,apr=4,may=5,jun=6,jul=7,aug=8,sep=9,oct=10,nov=11,dec=12}
4302 local months
4303 local parse_date_unsafe
4304 local function create_months()
4305 local ld, day1 = parse_date_unsafe '2000-12-31', {day=1}
4306 months = {}
4307 for i = 1,12 do
4308 ld = ld:last_day()
4309 ld:add(day1)
4310 local mon = ld:month_name():lower()
4311 months [mon] = i
4312 end
4313 end
4314
4315 --[[
4316 Allowed patterns:
4317 - [day] [monthname] [year] [time]
4318 - [day]/[month][/year] [time]
4319
4320 ]]
4321
4322 local function looks_like_a_month(w)
4323 return w:match '^%a+,*$' ~= nil
4324 end
4325 local is_number = stringx.isdigit
4326 local function tonum(s,l1,l2,kind)
4327 kind = kind or ''
4328 local n = tonumber(s)
4329 if not n then error(("%snot a number: '%s'"):format(kind,s)) end
4330 if n < l1 or n > l2 then
4331 error(("%s out of range: %s is not between %d and %d"):format(kind,s,l1,l2))
4332 end
4333 return n
4334 end
4335
4336 local function parse_iso_end(p,ns,sec)
4337 -- may be fractional part of seconds
4338 local _,nfrac,secfrac = p:find('^%.%d+',ns+1)
4339 if secfrac then
4340 sec = sec .. secfrac
4341 p = p:sub(nfrac+1)
4342 else
4343 p = p:sub(ns+1)
4344 end
4345 -- ISO 8601 dates may end in Z (for UTC) or [+-][isotime]
4346 -- (we're working with the date as lower case, hence 'z')
4347 if p:match 'z$' then -- we're UTC!
4348 return sec, {h=0,m=0}
4349 end
4350 p = p:gsub(':','') -- turn 00:30 to 0030
4351 local _,_,sign,offs = p:find('^([%+%-])(%d+)')
4352 if not sign then return sec, nil end -- not UTC
4353
4354 if #offs == 2 then offs = offs .. '00' end -- 01 to 0100
4355 local tz = { h = tonumber(offs:sub(1,2)), m = tonumber(offs:sub(3,4)) }
4356 if sign == '-' then tz.h = -tz.h; tz.m = -tz.m end
4357 return sec, tz
4358 end
4359
4360 function parse_date_unsafe (s,US)
4361 s = s:gsub('T',' ') -- ISO 8601
4362 local parts = stringx.split(s:lower())
4363 local i,p = 1,parts[1]
4364 local function nextp() i = i + 1; p = parts[i] end
4365 local year,min,hour,sec,apm
4366 local tz
4367 local _,nxt,day, month = p:find '^(%d+)/(%d+)'
4368 if day then
4369 -- swop for US case
4370 if US then
4371 day, month = month, day
4372 end
4373 _,_,year = p:find('^/(%d+)',nxt+1)
4374 nextp()
4375 else -- ISO
4376 year,month,day = p:match('^(%d+)%-(%d+)%-(%d+)')
4377 if year then
4378 nextp()
4379 end
4380 end
4381 if p and not year and is_number(p) then -- has to be date
4382 if #p < 4 then
4383 day = p
4384 nextp()
4385 else -- unless it looks like a 24-hour time
4386 year = true
4387 end
4388 end
4389 if p and looks_like_a_month(p) then -- date followed by month
4390 p = p:sub(1,3)
4391 if not months then
4392 create_months()
4393 end
4394 local mon = months[p]
4395 if mon then
4396 month = mon
4397 else error("not a month: " .. p) end
4398 nextp()
4399 end
4400 if p and not year and is_number(p) then
4401 year = p
4402 nextp()
4403 end
4404
4405 if p then -- time is hh:mm[:ss], hhmm[ss] or H.M[am|pm]
4406 _,nxt,hour,min = p:find '^(%d+):(%d+)'
4407 local ns
4408 if nxt then -- are there seconds?
4409 _,ns,sec = p:find ('^:(%d+)',nxt+1)
4410 --if ns then
4411 sec,tz = parse_iso_end(p,ns or nxt,sec)
4412 --end
4413 else -- might be h.m
4414 _,ns,hour,min = p:find '^(%d+)%.(%d+)'
4415 if ns then
4416 apm = p:match '[ap]m$'
4417 else -- or hhmm[ss]
4418 local hourmin
4419 _,nxt,hourmin = p:find ('^(%d+)')
4420 if nxt then
4421 hour = hourmin:sub(1,2)
4422 min = hourmin:sub(3,4)
4423 sec = hourmin:sub(5,6)
4424 if #sec == 0 then sec = nil end
4425 sec,tz = parse_iso_end(p,nxt,sec)
4426 end
4427 end
4428 end
4429 end
4430 local today
4431 if year == true then year = nil end
4432 if not (year and month and day) then
4433 today = Date()
4434 end
4435 day = day and tonum(day,1,31,'day') or (month and 1 or today:day())
4436 month = month and tonum(month,1,12,'month') or today:month()
4437 year = year and tonumber(year) or today:year()
4438 if year < 100 then -- two-digit year pivot around year < 2035
4439 year = year + (year < 35 and 2000 or 1900)
4440 end
4441 hour = hour and tonum(hour,0,apm and 12 or 24,'hour') or 12
4442 if apm == 'pm' then
4443 hour = hour + 12
4444 end
4445 min = min and tonum(min,0,59) or 0
4446 sec = sec and tonum(sec,0,60) or 0 --60 used to indicate leap second
4447 local res = Date {year = year, month = month, day = day, hour = hour, min = min, sec = sec}
4448 if tz then -- ISO 8601 UTC time
4449 local corrected = false
4450 if tz.h ~= 0 then res:add {hour = -tz.h}; corrected = true end
4451 if tz.m ~= 0 then res:add {min = -tz.m}; corrected = true end
4452 res.utc = true
4453 -- we're in UTC, so let's go local...
4454 if corrected then
4455 res = res:toLocal()
4456 end-- we're UTC!
4457 end
4458 return res
4459 end
4460
4461 function parse_date (s)
4462 local ok, d = pcall(parse_date_unsafe,s)
4463 if not ok then -- error
4464 d = d:gsub('.-:%d+: ','')
4465 return nil, d
4466 else
4467 return d
4468 end
4469 end
4470
4471 return Date
4472
4473
4474 end,
4475
4476 ["pl.dir"] = function()
4477 --------------------
4478 -- Module: 'pl.dir'
4479 --------------------
4480 --- Listing files in directories and creating/removing directory paths.
4481 --
4482 -- Dependencies: `pl.utils`, `pl.path`
4483 --
4484 -- Soft Dependencies: `alien`, `ffi` (either are used on Windows for copying/moving files)
4485 -- @module pl.dir
4486
4487 local utils = require 'pl.utils'
4488 local path = require 'pl.path'
4489 local is_windows = path.is_windows
4490 local ldir = path.dir
4491 local mkdir = path.mkdir
4492 local rmdir = path.rmdir
4493 local sub = string.sub
4494 local os,pcall,ipairs,pairs,require,setmetatable = os,pcall,ipairs,pairs,require,setmetatable
4495 local remove = os.remove
4496 local append = table.insert
4497 local assert_arg,assert_string,raise = utils.assert_arg,utils.assert_string,utils.raise
4498
4499 local exists, isdir = path.exists, path.isdir
4500 local sep = path.sep
4501
4502 local dir = {}
4503
4504 local function makelist(l)
4505 return setmetatable(l, require('pl.List'))
4506 end
4507
4508 local function assert_dir (n,val)
4509 assert_arg(n,val,'string',path.isdir,'not a directory',4)
4510 end
4511
4512 local function filemask(mask)
4513 mask = utils.escape(path.normcase(mask))
4514 return '^'..mask:gsub('%%%*','.*'):gsub('%%%?','.')..'$'
4515 end
4516
4517 --- Test whether a file name matches a shell pattern.
4518 -- Both parameters are case-normalized if operating system is
4519 -- case-insensitive.
4520 -- @string filename A file name.
4521 -- @string pattern A shell pattern. The only special characters are
4522 -- `'*'` and `'?'`: `'*'` matches any sequence of characters and
4523 -- `'?'` matches any single character.
4524 -- @treturn bool
4525 -- @raise dir and mask must be strings
4526 function dir.fnmatch(filename,pattern)
4527 assert_string(1,filename)
4528 assert_string(2,pattern)
4529 return path.normcase(filename):find(filemask(pattern)) ~= nil
4530 end
4531
4532 --- Return a list of all file names within an array which match a pattern.
4533 -- @tab filenames An array containing file names.
4534 -- @string pattern A shell pattern (see `fnmatch`).
4535 -- @treturn List(string) List of matching file names.
4536 -- @raise dir and mask must be strings
4537 function dir.filter(filenames,pattern)
4538 assert_arg(1,filenames,'table')
4539 assert_string(2,pattern)
4540 local res = {}
4541 local mask = filemask(pattern)
4542 for i,f in ipairs(filenames) do
4543 if path.normcase(f):find(mask) then append(res,f) end
4544 end
4545 return makelist(res)
4546 end
4547
4548 local function _listfiles(dirname,filemode,match)
4549 local res = {}
4550 local check = utils.choose(filemode,path.isfile,path.isdir)
4551 if not dirname then dirname = '.' end
4552 for f in ldir(dirname) do
4553 if f ~= '.' and f ~= '..' then
4554 local p = path.join(dirname,f)
4555 if check(p) and (not match or match(f)) then
4556 append(res,p)
4557 end
4558 end
4559 end
4560 return makelist(res)
4561 end
4562
4563 --- return a list of all files in a directory which match a shell pattern.
4564 -- @string[opt='.'] dirname A directory.
4565 -- @string[opt] mask A shell pattern (see `fnmatch`). If not given, all files are returned.
4566 -- @treturn {string} list of files
4567 -- @raise dirname and mask must be strings
4568 function dir.getfiles(dirname,mask)
4569 dirname = dirname or '.'
4570 assert_dir(1,dirname)
4571 if mask then assert_string(2,mask) end
4572 local match
4573 if mask then
4574 mask = filemask(mask)
4575 match = function(f)
4576 return path.normcase(f):find(mask)
4577 end
4578 end
4579 return _listfiles(dirname,true,match)
4580 end
4581
4582 --- return a list of all subdirectories of the directory.
4583 -- @string[opt='.'] dirname A directory.
4584 -- @treturn {string} a list of directories
4585 -- @raise dir must be a valid directory
4586 function dir.getdirectories(dirname)
4587 dirname = dirname or '.'
4588 assert_dir(1,dirname)
4589 return _listfiles(dirname,false)
4590 end
4591
4592 local alien,ffi,ffi_checked,CopyFile,MoveFile,GetLastError,win32_errors,cmd_tmpfile
4593
4594 local function execute_command(cmd,parms)
4595 if not cmd_tmpfile then cmd_tmpfile = path.tmpname () end
4596 local err = path.is_windows and ' > ' or ' 2> '
4597 cmd = cmd..' '..parms..err..utils.quote_arg(cmd_tmpfile)
4598 local ret = utils.execute(cmd)
4599 if not ret then
4600 local err = (utils.readfile(cmd_tmpfile):gsub('\n(.*)',''))
4601 remove(cmd_tmpfile)
4602 return false,err
4603 else
4604 remove(cmd_tmpfile)
4605 return true
4606 end
4607 end
4608
4609 local function find_ffi_copyfile ()
4610 if not ffi_checked then
4611 ffi_checked = true
4612 local res
4613 res,alien = pcall(require,'alien')
4614 if not res then
4615 alien = nil
4616 res, ffi = pcall(require,'ffi')
4617 end
4618 if not res then
4619 ffi = nil
4620 return
4621 end
4622 else
4623 return
4624 end
4625 if alien then
4626 -- register the Win32 CopyFile and MoveFile functions
4627 local kernel = alien.load('kernel32.dll')
4628 CopyFile = kernel.CopyFileA
4629 CopyFile:types{'string','string','int',ret='int',abi='stdcall'}
4630 MoveFile = kernel.MoveFileA
4631 MoveFile:types{'string','string',ret='int',abi='stdcall'}
4632 GetLastError = kernel.GetLastError
4633 GetLastError:types{ret ='int', abi='stdcall'}
4634 elseif ffi then
4635 ffi.cdef [[
4636 int CopyFileA(const char *src, const char *dest, int iovr);
4637 int MoveFileA(const char *src, const char *dest);
4638 int GetLastError();
4639 ]]
4640 CopyFile = ffi.C.CopyFileA
4641 MoveFile = ffi.C.MoveFileA
4642 GetLastError = ffi.C.GetLastError
4643 end
4644 win32_errors = {
4645 ERROR_FILE_NOT_FOUND = 2,
4646 ERROR_PATH_NOT_FOUND = 3,
4647 ERROR_ACCESS_DENIED = 5,
4648 ERROR_WRITE_PROTECT = 19,
4649 ERROR_BAD_UNIT = 20,
4650 ERROR_NOT_READY = 21,
4651 ERROR_WRITE_FAULT = 29,
4652 ERROR_READ_FAULT = 30,
4653 ERROR_SHARING_VIOLATION = 32,
4654 ERROR_LOCK_VIOLATION = 33,
4655 ERROR_HANDLE_DISK_FULL = 39,
4656 ERROR_BAD_NETPATH = 53,
4657 ERROR_NETWORK_BUSY = 54,
4658 ERROR_DEV_NOT_EXIST = 55,
4659 ERROR_FILE_EXISTS = 80,
4660 ERROR_OPEN_FAILED = 110,
4661 ERROR_INVALID_NAME = 123,
4662 ERROR_BAD_PATHNAME = 161,
4663 ERROR_ALREADY_EXISTS = 183,
4664 }
4665 end
4666
4667 local function two_arguments (f1,f2)
4668 return utils.quote_arg(f1)..' '..utils.quote_arg(f2)
4669 end
4670
4671 local function file_op (is_copy,src,dest,flag)
4672 if flag == 1 and path.exists(dest) then
4673 return false,"cannot overwrite destination"
4674 end
4675 if is_windows then
4676 -- if we haven't tried to load Alien/LuaJIT FFI before, then do so
4677 find_ffi_copyfile()
4678 -- fallback if there's no Alien, just use DOS commands *shudder*
4679 -- 'rename' involves a copy and then deleting the source.
4680 if not CopyFile then
4681 if path.is_windows then
4682 src = src:gsub("/","\\")
4683 dest = dest:gsub("/","\\")
4684 end
4685 local res, err = execute_command('copy',two_arguments(src,dest))
4686 if not res then return false,err end
4687 if not is_copy then
4688 return execute_command('del',utils.quote_arg(src))
4689 end
4690 return true
4691 else
4692 if path.isdir(dest) then
4693 dest = path.join(dest,path.basename(src))
4694 end
4695 local ret
4696 if is_copy then ret = CopyFile(src,dest,flag)
4697 else ret = MoveFile(src,dest) end
4698 if ret == 0 then
4699 local err = GetLastError()
4700 for name,value in pairs(win32_errors) do
4701 if value == err then return false,name end
4702 end
4703 return false,"Error #"..err
4704 else return true
4705 end
4706 end
4707 else -- for Unix, just use cp for now
4708 return execute_command(is_copy and 'cp' or 'mv',
4709 two_arguments(src,dest))
4710 end
4711 end
4712
4713 --- copy a file.
4714 -- @string src source file
4715 -- @string dest destination file or directory
4716 -- @bool flag true if you want to force the copy (default)
4717 -- @treturn bool operation succeeded
4718 -- @raise src and dest must be strings
4719 function dir.copyfile (src,dest,flag)
4720 assert_string(1,src)
4721 assert_string(2,dest)
4722 flag = flag==nil or flag
4723 return file_op(true,src,dest,flag and 0 or 1)
4724 end
4725
4726 --- move a file.
4727 -- @string src source file
4728 -- @string dest destination file or directory
4729 -- @treturn bool operation succeeded
4730 -- @raise src and dest must be strings
4731 function dir.movefile (src,dest)
4732 assert_string(1,src)
4733 assert_string(2,dest)
4734 return file_op(false,src,dest,0)
4735 end
4736
4737 local function _dirfiles(dirname,attrib)
4738 local dirs = {}
4739 local files = {}
4740 for f in ldir(dirname) do
4741 if f ~= '.' and f ~= '..' then
4742 local p = path.join(dirname,f)
4743 local mode = attrib(p,'mode')
4744 if mode=='directory' then
4745 append(dirs,f)
4746 else
4747 append(files,f)
4748 end
4749 end
4750 end
4751 return makelist(dirs), makelist(files)
4752 end
4753
4754
4755 --- return an iterator which walks through a directory tree starting at root.
4756 -- The iterator returns (root,dirs,files)
4757 -- Note that dirs and files are lists of names (i.e. you must say path.join(root,d)
4758 -- to get the actual full path)
4759 -- If bottom_up is false (or not present), then the entries at the current level are returned
4760 -- before we go deeper. This means that you can modify the returned list of directories before
4761 -- continuing.
4762 -- This is a clone of os.walk from the Python libraries.
4763 -- @string root A starting directory
4764 -- @bool bottom_up False if we start listing entries immediately.
4765 -- @bool follow_links follow symbolic links
4766 -- @return an iterator returning root,dirs,files
4767 -- @raise root must be a directory
4768 function dir.walk(root,bottom_up,follow_links)
4769 assert_dir(1,root)
4770 local attrib
4771 if path.is_windows or not follow_links then
4772 attrib = path.attrib
4773 else
4774 attrib = path.link_attrib
4775 end
4776
4777 local to_scan = { root }
4778 local to_return = {}
4779 local iter = function()
4780 while #to_scan > 0 do
4781 local current_root = table.remove(to_scan)
4782 local dirs,files = _dirfiles(current_root, attrib)
4783 for _, d in ipairs(dirs) do
4784 table.insert(to_scan, current_root..path.sep..d)
4785 end
4786 if not bottom_up then
4787 return current_root, dirs, files
4788 else
4789 table.insert(to_return, { current_root, dirs, files })
4790 end
4791 end
4792 if #to_return > 0 then
4793 return utils.unpack(table.remove(to_return))
4794 end
4795 end
4796
4797 return iter
4798 end
4799
4800 --- remove a whole directory tree.
4801 -- Symlinks in the tree will be deleted without following them.
4802 -- @string fullpath A directory path (must be an actual directory, not a symlink)
4803 -- @return true or nil
4804 -- @return error if failed
4805 -- @raise fullpath must be a string
4806 function dir.rmtree(fullpath)
4807 assert_dir(1,fullpath)
4808 if path.islink(fullpath) then return false,'will not follow symlink' end
4809 for root,dirs,files in dir.walk(fullpath,true) do
4810 if path.islink(root) then
4811 -- sub dir is a link, remove link, do not follow
4812 if is_windows then
4813 -- Windows requires using "rmdir". Deleting the link like a file
4814 -- will instead delete all files from the target directory!!
4815 local res, err = rmdir(root)
4816 if not res then return nil,err .. ": " .. root end
4817 else
4818 local res, err = remove(root)
4819 if not res then return nil,err .. ": " .. root end
4820 end
4821 else
4822 for i,f in ipairs(files) do
4823 local res, err = remove(path.join(root,f))
4824 if not res then return nil,err .. ": " .. path.join(root,f) end
4825 end
4826 local res, err = rmdir(root)
4827 if not res then return nil,err .. ": " .. root end
4828 end
4829 end
4830 return true
4831 end
4832
4833
4834 do
4835 local dirpat
4836 if path.is_windows then
4837 dirpat = '(.+)\\[^\\]+$'
4838 else
4839 dirpat = '(.+)/[^/]+$'
4840 end
4841
4842 local _makepath
4843 function _makepath(p)
4844 -- windows root drive case
4845 if p:find '^%a:[\\]*$' then
4846 return true
4847 end
4848 if not path.isdir(p) then
4849 local subp = p:match(dirpat)
4850 if subp then
4851 local ok, err = _makepath(subp)
4852 if not ok then return nil, err end
4853 end
4854 return mkdir(p)
4855 else
4856 return true
4857 end
4858 end
4859
4860 --- create a directory path.
4861 -- This will create subdirectories as necessary!
4862 -- @string p A directory path
4863 -- @return true on success, nil + errormsg on failure
4864 -- @raise failure to create
4865 function dir.makepath (p)
4866 assert_string(1,p)
4867 if path.is_windows then
4868 p = p:gsub("/", "\\")
4869 end
4870 return _makepath(path.abspath(p))
4871 end
4872 end
4873
4874 --- clone a directory tree. Will always try to create a new directory structure
4875 -- if necessary.
4876 -- @string path1 the base path of the source tree
4877 -- @string path2 the new base path for the destination
4878 -- @func file_fun an optional function to apply on all files
4879 -- @bool verbose an optional boolean to control the verbosity of the output.
4880 -- It can also be a logging function that behaves like print()
4881 -- @return true, or nil
4882 -- @return error message, or list of failed directory creations
4883 -- @return list of failed file operations
4884 -- @raise path1 and path2 must be strings
4885 -- @usage clonetree('.','../backup',copyfile)
4886 function dir.clonetree (path1,path2,file_fun,verbose)
4887 assert_string(1,path1)
4888 assert_string(2,path2)
4889 if verbose == true then verbose = print end
4890 local abspath,normcase,isdir,join = path.abspath,path.normcase,path.isdir,path.join
4891 local faildirs,failfiles = {},{}
4892 if not isdir(path1) then return raise 'source is not a valid directory' end
4893 path1 = abspath(normcase(path1))
4894 path2 = abspath(normcase(path2))
4895 if verbose then verbose('normalized:',path1,path2) end
4896 -- particularly NB that the new path isn't fully contained in the old path
4897 if path1 == path2 then return raise "paths are the same" end
4898 local _,i2 = path2:find(path1,1,true)
4899 if i2 == #path1 and path2:sub(i2+1,i2+1) == path.sep then
4900 return raise 'destination is a subdirectory of the source'
4901 end
4902 local cp = path.common_prefix (path1,path2)
4903 local idx = #cp
4904 if idx == 0 then -- no common path, but watch out for Windows paths!
4905 if path1:sub(2,2) == ':' then idx = 3 end
4906 end
4907 for root,dirs,files in dir.walk(path1) do
4908 local opath = path2..root:sub(idx)
4909 if verbose then verbose('paths:',opath,root) end
4910 if not isdir(opath) then
4911 local ret = dir.makepath(opath)
4912 if not ret then append(faildirs,opath) end
4913 if verbose then verbose('creating:',opath,ret) end
4914 end
4915 if file_fun then
4916 for i,f in ipairs(files) do
4917 local p1 = join(root,f)
4918 local p2 = join(opath,f)
4919 local ret = file_fun(p1,p2)
4920 if not ret then append(failfiles,p2) end
4921 if verbose then
4922 verbose('files:',p1,p2,ret)
4923 end
4924 end
4925 end
4926 end
4927 return true,faildirs,failfiles
4928 end
4929
4930
4931 -- each entry of the stack is an array with three items:
4932 -- 1. the name of the directory
4933 -- 2. the lfs iterator function
4934 -- 3. the lfs iterator userdata
4935 local function treeiter(iterstack)
4936 local diriter = iterstack[#iterstack]
4937 if not diriter then
4938 return -- done
4939 end
4940
4941 local dirname = diriter[1]
4942 local entry = diriter[2](diriter[3])
4943 if not entry then
4944 table.remove(iterstack)
4945 return treeiter(iterstack) -- tail-call to try next
4946 end
4947
4948 if entry ~= "." and entry ~= ".." then
4949 entry = dirname .. sep .. entry
4950 if exists(entry) then -- Just in case a symlink is broken.
4951 local is_dir = isdir(entry)
4952 if is_dir then
4953 table.insert(iterstack, { entry, ldir(entry) })
4954 end
4955 return entry, is_dir
4956 end
4957 end
4958
4959 return treeiter(iterstack) -- tail-call to try next
4960 end
4961
4962
4963 --- return an iterator over all entries in a directory tree
4964 -- @string d a directory
4965 -- @return an iterator giving pathname and mode (true for dir, false otherwise)
4966 -- @raise d must be a non-empty string
4967 function dir.dirtree( d )
4968 assert( d and d ~= "", "directory parameter is missing or empty" )
4969
4970 local last = sub ( d, -1 )
4971 if last == sep or last == '/' then
4972 d = sub( d, 1, -2 )
4973 end
4974
4975 local iterstack = { {d, ldir(d)} }
4976
4977 return treeiter, iterstack
4978 end
4979
4980
4981 --- Recursively returns all the file starting at 'path'. It can optionally take a shell pattern and
4982 -- only returns files that match 'shell_pattern'. If a pattern is given it will do a case insensitive search.
4983 -- @string[opt='.'] start_path A directory.
4984 -- @string[opt='*'] shell_pattern A shell pattern (see `fnmatch`).
4985 -- @treturn List(string) containing all the files found recursively starting at 'path' and filtered by 'shell_pattern'.
4986 -- @raise start_path must be a directory
4987 function dir.getallfiles( start_path, shell_pattern )
4988 start_path = start_path or '.'
4989 assert_dir(1,start_path)
4990 shell_pattern = shell_pattern or "*"
4991
4992 local files = {}
4993 local normcase = path.normcase
4994 for filename, mode in dir.dirtree( start_path ) do
4995 if not mode then
4996 local mask = filemask( shell_pattern )
4997 if normcase(filename):find( mask ) then
4998 files[#files + 1] = filename
4999 end
5000 end
5001 end
5002
5003 return makelist(files)
5004 end
5005
5006 return dir
5007
5008 end,
5009
5010 ["pl.file"] = function()
5011 --------------------
5012 -- Module: 'pl.file'
5013 --------------------
5014 --- File manipulation functions: reading, writing, moving and copying.
5015 --
5016 -- This module wraps a number of functions from other modules into a
5017 -- file related module for convenience.
5018 --
5019 -- Dependencies: `pl.utils`, `pl.dir`, `pl.path`
5020 -- @module pl.file
5021 local os = os
5022 local utils = require 'pl.utils'
5023 local dir = require 'pl.dir'
5024 local path = require 'pl.path'
5025
5026 local file = {}
5027
5028 --- return the contents of a file as a string.
5029 -- This function is a copy of `utils.readfile`.
5030 -- @function file.read
5031 file.read = utils.readfile
5032
5033 --- write a string to a file.
5034 -- This function is a copy of `utils.writefile`.
5035 -- @function file.write
5036 file.write = utils.writefile
5037
5038 --- copy a file.
5039 -- This function is a copy of `dir.copyfile`.
5040 -- @function file.copy
5041 file.copy = dir.copyfile
5042
5043 --- move a file.
5044 -- This function is a copy of `dir.movefile`.
5045 -- @function file.move
5046 file.move = dir.movefile
5047
5048 --- Return the time of last access as the number of seconds since the epoch.
5049 -- This function is a copy of `path.getatime`.
5050 -- @function file.access_time
5051 file.access_time = path.getatime
5052
5053 ---Return when the file was created.
5054 -- This function is a copy of `path.getctime`.
5055 -- @function file.creation_time
5056 file.creation_time = path.getctime
5057
5058 --- Return the time of last modification.
5059 -- This function is a copy of `path.getmtime`.
5060 -- @function file.modified_time
5061 file.modified_time = path.getmtime
5062
5063 --- Delete a file.
5064 -- This function is a copy of `os.remove`.
5065 -- @function file.delete
5066 file.delete = os.remove
5067
5068 return file
5069
5070 end,
5071
5072 ["pl.func"] = function()
5073 --------------------
5074 -- Module: 'pl.func'
5075 --------------------
5076 --- Functional helpers like composition, binding and placeholder expressions.
5077 -- Placeholder expressions are useful for short anonymous functions, and were
5078 -- inspired by the Boost Lambda library.
5079 --
5080 -- > utils.import 'pl.func'
5081 -- > ls = List{10,20,30}
5082 -- > = ls:map(_1+1)
5083 -- {11,21,31}
5084 --
5085 -- They can also be used to _bind_ particular arguments of a function.
5086 --
5087 -- > p = bind(print,'start>',_0)
5088 -- > p(10,20,30)
5089 -- > start> 10 20 30
5090 --
5091 -- See @{07-functional.md.Creating_Functions_from_Functions|the Guide}
5092 --
5093 -- Dependencies: `pl.utils`, `pl.tablex`
5094 -- @module pl.func
5095 local type,setmetatable,getmetatable,rawset = type,setmetatable,getmetatable,rawset
5096 local concat,append = table.concat,table.insert
5097 local tostring = tostring
5098 local utils = require 'pl.utils'
5099 local pairs,rawget,unpack,pack = pairs,rawget,utils.unpack,utils.pack
5100 local tablex = require 'pl.tablex'
5101 local map = tablex.map
5102 local _DEBUG = rawget(_G,'_DEBUG')
5103 local assert_arg = utils.assert_arg
5104
5105 local func = {}
5106
5107 -- metatable for Placeholder Expressions (PE)
5108 local _PEMT = {}
5109
5110 local function P (t)
5111 setmetatable(t,_PEMT)
5112 return t
5113 end
5114
5115 func.PE = P
5116
5117 local function isPE (obj)
5118 return getmetatable(obj) == _PEMT
5119 end
5120
5121 func.isPE = isPE
5122
5123 -- construct a placeholder variable (e.g _1 and _2)
5124 local function PH (idx)
5125 return P {op='X',repr='_'..idx, index=idx}
5126 end
5127
5128 -- construct a constant placeholder variable (e.g _C1 and _C2)
5129 local function CPH (idx)
5130 return P {op='X',repr='_C'..idx, index=idx}
5131 end
5132
5133 func._1,func._2,func._3,func._4,func._5 = PH(1),PH(2),PH(3),PH(4),PH(5)
5134 func._0 = P{op='X',repr='...',index=0}
5135
5136 function func.Var (name)
5137 local ls = utils.split(name,'[%s,]+')
5138 local res = {}
5139 for i = 1, #ls do
5140 append(res,P{op='X',repr=ls[i],index=0})
5141 end
5142 return unpack(res)
5143 end
5144
5145 function func._ (value)
5146 return P{op='X',repr=value,index='wrap'}
5147 end
5148
5149 local repr
5150
5151 func.Nil = func.Var 'nil'
5152
5153 function _PEMT.__index(obj,key)
5154 return P{op='[]',obj,key}
5155 end
5156
5157 function _PEMT.__call(fun,...)
5158 return P{op='()',fun,...}
5159 end
5160
5161 function _PEMT.__tostring (e)
5162 return repr(e)
5163 end
5164
5165 function _PEMT.__unm(arg)
5166 return P{op='unm',arg}
5167 end
5168
5169 function func.Not (arg)
5170 return P{op='not',arg}
5171 end
5172
5173 function func.Len (arg)
5174 return P{op='#',arg}
5175 end
5176
5177
5178 local function binreg(context,t)
5179 for name,op in pairs(t) do
5180 rawset(context,name,function(x,y)
5181 return P{op=op,x,y}
5182 end)
5183 end
5184 end
5185
5186 local function import_name (name,fun,context)
5187 rawset(context,name,function(...)
5188 return P{op='()',fun,...}
5189 end)
5190 end
5191
5192 local imported_functions = {}
5193
5194 local function is_global_table (n)
5195 return type(_G[n]) == 'table'
5196 end
5197
5198 --- wrap a table of functions. This makes them available for use in
5199 -- placeholder expressions.
5200 -- @string tname a table name
5201 -- @tab context context to put results, defaults to environment of caller
5202 function func.import(tname,context)
5203 assert_arg(1,tname,'string',is_global_table,'arg# 1: not a name of a global table')
5204 local t = _G[tname]
5205 context = context or _G
5206 for name,fun in pairs(t) do
5207 import_name(name,fun,context)
5208 imported_functions[fun] = name
5209 end
5210 end
5211
5212 --- register a function for use in placeholder expressions.
5213 -- @func fun a function
5214 -- @string[opt] name an optional name
5215 -- @return a placeholder functiond
5216 function func.register (fun,name)
5217 assert_arg(1,fun,'function')
5218 if name then
5219 assert_arg(2,name,'string')
5220 imported_functions[fun] = name
5221 end
5222 return function(...)
5223 return P{op='()',fun,...}
5224 end
5225 end
5226
5227 function func.lookup_imported_name (fun)
5228 return imported_functions[fun]
5229 end
5230
5231 local function _arg(...) return ... end
5232
5233 function func.Args (...)
5234 return P{op='()',_arg,...}
5235 end
5236
5237 -- binary operators with their precedences (see Lua manual)
5238 -- precedences might be incremented by one before use depending on
5239 -- left- or right-associativity, space them out
5240 local binary_operators = {
5241 ['or'] = 0,
5242 ['and'] = 2,
5243 ['=='] = 4, ['~='] = 4, ['<'] = 4, ['>'] = 4, ['<='] = 4, ['>='] = 4,
5244 ['..'] = 6,
5245 ['+'] = 8, ['-'] = 8,
5246 ['*'] = 10, ['/'] = 10, ['%'] = 10,
5247 ['^'] = 14
5248 }
5249
5250 -- unary operators with their precedences
5251 local unary_operators = {
5252 ['not'] = 12, ['#'] = 12, ['unm'] = 12
5253 }
5254
5255 -- comparisons (as prefix functions)
5256 binreg (func,{And='and',Or='or',Eq='==',Lt='<',Gt='>',Le='<=',Ge='>='})
5257
5258 -- standard binary operators (as metamethods)
5259 binreg (_PEMT,{__add='+',__sub='-',__mul='*',__div='/',__mod='%',__pow='^',__concat='..'})
5260
5261 binreg (_PEMT,{__eq='=='})
5262
5263 --- all elements of a table except the first.
5264 -- @tab ls a list-like table.
5265 function func.tail (ls)
5266 assert_arg(1,ls,'table')
5267 local res = {}
5268 for i = 2,#ls do
5269 append(res,ls[i])
5270 end
5271 return res
5272 end
5273
5274 --- create a string representation of a placeholder expression.
5275 -- @param e a placeholder expression
5276 -- @param lastpred not used
5277 function repr (e,lastpred)
5278 local tail = func.tail
5279 if isPE(e) then
5280 local pred = binary_operators[e.op] or unary_operators[e.op]
5281 if pred then
5282 -- binary or unary operator
5283 local s
5284 if binary_operators[e.op] then
5285 local left_pred = pred
5286 local right_pred = pred
5287 if e.op == '..' or e.op == '^' then
5288 left_pred = left_pred + 1
5289 else
5290 right_pred = right_pred + 1
5291 end
5292 local left_arg = repr(e[1], left_pred)
5293 local right_arg = repr(e[2], right_pred)
5294 s = left_arg..' '..e.op..' '..right_arg
5295 else
5296 local op = e.op == 'unm' and '-' or e.op
5297 s = op..' '..repr(e[1], pred)
5298 end
5299 if lastpred and lastpred > pred then
5300 s = '('..s..')'
5301 end
5302 return s
5303 else -- either postfix, or a placeholder
5304 local ls = map(repr,e)
5305 if e.op == '[]' then
5306 return ls[1]..'['..ls[2]..']'
5307 elseif e.op == '()' then
5308 local fn
5309 if ls[1] ~= nil then -- was _args, undeclared!
5310 fn = ls[1]
5311 else
5312 fn = ''
5313 end
5314 return fn..'('..concat(tail(ls),',')..')'
5315 else
5316 return e.repr
5317 end
5318 end
5319 elseif type(e) == 'string' then
5320 return '"'..e..'"'
5321 elseif type(e) == 'function' then
5322 local name = func.lookup_imported_name(e)
5323 if name then return name else return tostring(e) end
5324 else
5325 return tostring(e) --should not really get here!
5326 end
5327 end
5328 func.repr = repr
5329
5330 -- collect all the non-PE values in this PE into vlist, and replace each occurrence
5331 -- with a constant PH (_C1, etc). Return the maximum placeholder index found.
5332 local collect_values
5333 function collect_values (e,vlist)
5334 if isPE(e) then
5335 if e.op ~= 'X' then
5336 local m = 0
5337 for i = 1,#e do
5338 local subx = e[i]
5339 local pe = isPE(subx)
5340 if pe then
5341 if subx.op == 'X' and subx.index == 'wrap' then
5342 subx = subx.repr
5343 pe = false
5344 else
5345 m = math.max(m,collect_values(subx,vlist))
5346 end
5347 end
5348 if not pe then
5349 append(vlist,subx)
5350 e[i] = CPH(#vlist)
5351 end
5352 end
5353 return m
5354 else -- was a placeholder, it has an index...
5355 return e.index
5356 end
5357 else -- plain value has no placeholder dependence
5358 return 0
5359 end
5360 end
5361 func.collect_values = collect_values
5362
5363 --- instantiate a PE into an actual function. First we find the largest placeholder used,
5364 -- e.g. _2; from this a list of the formal parameters can be build. Then we collect and replace
5365 -- any non-PE values from the PE, and build up a constant binding list.
5366 -- Finally, the expression can be compiled, and e.__PE_function is set.
5367 -- @param e a placeholder expression
5368 -- @return a function
5369 function func.instantiate (e)
5370 local consts,values,parms = {},{},{}
5371 local rep, err, fun
5372 local n = func.collect_values(e,values)
5373 for i = 1,#values do
5374 append(consts,'_C'..i)
5375 if _DEBUG then print(i,values[i]) end
5376 end
5377 for i =1,n do
5378 append(parms,'_'..i)
5379 end
5380 consts = concat(consts,',')
5381 parms = concat(parms,',')
5382 rep = repr(e)
5383 local fstr = ('return function(%s) return function(%s) return %s end end'):format(consts,parms,rep)
5384 if _DEBUG then print(fstr) end
5385 fun,err = utils.load(fstr,'fun')
5386 if not fun then return nil,err end
5387 fun = fun() -- get wrapper
5388 fun = fun(unpack(values)) -- call wrapper (values could be empty)
5389 e.__PE_function = fun
5390 return fun
5391 end
5392
5393 --- instantiate a PE unless it has already been done.
5394 -- @param e a placeholder expression
5395 -- @return the function
5396 function func.I(e)
5397 if rawget(e,'__PE_function') then
5398 return e.__PE_function
5399 else return func.instantiate(e)
5400 end
5401 end
5402
5403 utils.add_function_factory(_PEMT,func.I)
5404
5405 --- bind the first parameter of the function to a value.
5406 -- @function func.bind1
5407 -- @func fn a function of one or more arguments
5408 -- @param p a value
5409 -- @return a function of one less argument
5410 -- @usage (bind1(math.max,10))(20) == math.max(10,20)
5411 func.bind1 = utils.bind1
5412 func.curry = func.bind1
5413
5414 --- create a function which chains multiple functions.
5415 -- @func f a function of at least one argument
5416 -- @func g a function of at least one argument
5417 -- @param ... additional functions to compose
5418 -- @return a function
5419 -- @usage printf = compose(io.write, string.format)
5420 -- @usage printf = compose(io.write, string.lower, string.format)
5421 function func.compose (...)
5422 local args = pack(...)
5423 return tablex.reduce(function(f, g)
5424 return function(...)
5425 return f(g(...))
5426 end
5427 end, args)
5428 end
5429
5430 --- bind the arguments of a function to given values.
5431 -- `bind(fn,v,_2)` is equivalent to `bind1(fn,v)`.
5432 -- @func fn a function of at least one argument
5433 -- @param ... values or placeholder variables
5434 -- @return a function
5435 -- @usage (bind(f,_1,a))(b) == f(a,b)
5436 -- @usage (bind(f,_2,_1))(a,b) == f(b,a)
5437 function func.bind(fn,...)
5438 local args = pack(...)
5439 local holders,parms,bvalues,values = {},{},{'fn'},{}
5440 local nv,maxplace,varargs = 1,0,false
5441 for i = 1,args.n do
5442 local a = args[i]
5443 if isPE(a) and a.op == 'X' then
5444 append(holders,a.repr)
5445 maxplace = math.max(maxplace,a.index)
5446 if a.index == 0 then varargs = true end
5447 else
5448 local v = '_v'..nv
5449 append(bvalues,v)
5450 append(holders,v)
5451 append(values,a)
5452 nv = nv + 1
5453 end
5454 end
5455 for np = 1,maxplace do
5456 append(parms,'_'..np)
5457 end
5458 if varargs then append(parms,'...') end
5459 bvalues = concat(bvalues,',')
5460 parms = concat(parms,',')
5461 holders = concat(holders,',')
5462 local fstr = ([[
5463 return function (%s)
5464 return function(%s) return fn(%s) end
5465 end
5466 ]]):format(bvalues,parms,holders)
5467 if _DEBUG then print(fstr) end
5468 local res = utils.load(fstr)
5469 res = res()
5470 return res(fn,unpack(values))
5471 end
5472
5473 return func
5474
5475
5476
5477 end,
5478
5479 ["pl.import_into"] = function()
5480 --------------------
5481 -- Module: 'pl.import_into'
5482 --------------------
5483 --------------
5484 -- PL loader, for loading all PL libraries, only on demand.
5485 -- Whenever a module is implicitly accessed, the table will have the module automatically injected.
5486 -- (e.g. `_ENV.tablex`)
5487 -- then that module is dynamically loaded. The submodules are all brought into
5488 -- the table that is provided as the argument, or returned in a new table.
5489 -- If a table is provided, that table's metatable is clobbered, but the values are not.
5490 -- This module returns a single function, which is passed the environment.
5491 -- If this is `true`, then return a 'shadow table' as the module
5492 -- See @{01-introduction.md.To_Inject_or_not_to_Inject_|the Guide}
5493
5494 -- @module pl.import_into
5495
5496 return function(env)
5497 local mod
5498 if env == true then
5499 mod = {}
5500 env = {}
5501 end
5502 local env = env or {}
5503
5504 local modules = {
5505 utils = true,path=true,dir=true,tablex=true,stringio=true,sip=true,
5506 input=true,seq=true,lexer=true,stringx=true,
5507 config=true,pretty=true,data=true,func=true,text=true,
5508 operator=true,lapp=true,array2d=true,
5509 comprehension=true,xml=true,types=true,
5510 test = true, app = true, file = true, class = true,
5511 luabalanced = true, permute = true, template = true,
5512 url = true, compat = true,
5513 -- classes --
5514 List = true, Map = true, Set = true,
5515 OrderedMap = true, MultiMap = true, Date = true,
5516 }
5517 rawset(env,'utils',require 'pl.utils')
5518
5519 for name,klass in pairs(env.utils.stdmt) do
5520 klass.__index = function(t,key)
5521 return require ('pl.'..name)[key]
5522 end;
5523 end
5524
5525 -- ensure that we play nice with libraries that also attach a metatable
5526 -- to the global table; always forward to a custom __index if we don't
5527 -- match
5528
5529 local _hook,_prev_index
5530 local gmt = {}
5531 local prevenvmt = getmetatable(env)
5532 if prevenvmt then
5533 _prev_index = prevenvmt.__index
5534 if prevenvmt.__newindex then
5535 gmt.__newindex = prevenvmt.__newindex
5536 end
5537 end
5538
5539 function gmt.hook(handler)
5540 _hook = handler
5541 end
5542
5543 function gmt.__index(t,name)
5544 local found = modules[name]
5545 -- either true, or the name of the module containing this class.
5546 -- either way, we load the required module and make it globally available.
5547 if found then
5548 -- e..g pretty.dump causes pl.pretty to become available as 'pretty'
5549 rawset(env,name,require('pl.'..name))
5550 return env[name]
5551 else
5552 local res
5553 if _hook then
5554 res = _hook(t,name)
5555 if res then return res end
5556 end
5557 if _prev_index then
5558 return _prev_index(t,name)
5559 end
5560 end
5561 end
5562
5563 if mod then
5564 function gmt.__newindex(t,name,value)
5565 mod[name] = value
5566 rawset(t,name,value)
5567 end
5568 end
5569
5570 setmetatable(env,gmt)
5571
5572 return env,mod or env
5573 end
5574
5575 end,
5576
5577 ["pl.init"] = function()
5578 --------------------
5579 -- Module: 'pl.init'
5580 --------------------
5581 --------------
5582 -- Entry point for loading all PL libraries only on demand, into the global space.
5583 -- Requiring 'pl' means that whenever a module is implicitly accessed
5584 -- (e.g. `utils.split`)
5585 -- then that module is dynamically loaded. The submodules are all brought into
5586 -- the global space.
5587 --Updated to use @{pl.import_into}
5588 -- @module pl
5589 require'pl.import_into'(_G)
5590
5591 if rawget(_G,'PENLIGHT_STRICT') then require 'pl.strict' end
5592
5593 end,
5594
5595 ["pl.input"] = function()
5596 --------------------
5597 -- Module: 'pl.input'
5598 --------------------
5599 --- Iterators for extracting words or numbers from an input source.
5600 --
5601 -- require 'pl'
5602 -- local total,n = seq.sum(input.numbers())
5603 -- print('average',total/n)
5604 --
5605 -- _source_ is defined as a string or a file-like object (i.e. has a read() method which returns the next line)
5606 --
5607 -- See @{06-data.md.Reading_Unstructured_Text_Data|here}
5608 --
5609 -- Dependencies: `pl.utils`
5610 -- @module pl.input
5611 local strfind = string.find
5612 local strsub = string.sub
5613 local strmatch = string.match
5614 local utils = require 'pl.utils'
5615 local unpack = utils.unpack
5616 local pairs,type,tonumber = pairs,type,tonumber
5617 local patterns = utils.patterns
5618 local io = io
5619
5620 local input = {}
5621
5622 --- create an iterator over all tokens.
5623 -- based on allwords from PiL, 7.1
5624 -- @func getter any function that returns a line of text
5625 -- @string pattern
5626 -- @string[opt] fn Optionally can pass a function to process each token as it's found.
5627 -- @return an iterator
5628 function input.alltokens (getter,pattern,fn)
5629 local line = getter() -- current line
5630 local pos = 1 -- current position in the line
5631 return function () -- iterator function
5632 while line do -- repeat while there are lines
5633 local s, e = strfind(line, pattern, pos)
5634 if s then -- found a word?
5635 pos = e + 1 -- next position is after this token
5636 local res = strsub(line, s, e) -- return the token
5637 if fn then res = fn(res) end
5638 return res
5639 else
5640 line = getter() -- token not found; try next line
5641 pos = 1 -- restart from first position
5642 end
5643 end
5644 return nil -- no more lines: end of traversal
5645 end
5646 end
5647 local alltokens = input.alltokens
5648
5649 -- question: shd this _split_ a string containing line feeds?
5650
5651 --- create a function which grabs the next value from a source. If the source is a string, then the getter
5652 -- will return the string and thereafter return nil. If not specified then the source is assumed to be stdin.
5653 -- @param f a string or a file-like object (i.e. has a read() method which returns the next line)
5654 -- @return a getter function
5655 function input.create_getter(f)
5656 if f then
5657 if type(f) == 'string' then
5658 local ls = utils.split(f,'\n')
5659 local i,n = 0,#ls
5660 return function()
5661 i = i + 1
5662 if i > n then return nil end
5663 return ls[i]
5664 end
5665 else
5666 -- anything that supports the read() method!
5667 if not f.read then error('not a file-like object') end
5668 return function() return f:read() end
5669 end
5670 else
5671 return io.read -- i.e. just read from stdin
5672 end
5673 end
5674
5675 --- generate a sequence of numbers from a source.
5676 -- @param f A source
5677 -- @return An iterator
5678 function input.numbers(f)
5679 return alltokens(input.create_getter(f),
5680 '('..patterns.FLOAT..')',tonumber)
5681 end
5682
5683 --- generate a sequence of words from a source.
5684 -- @param f A source
5685 -- @return An iterator
5686 function input.words(f)
5687 return alltokens(input.create_getter(f),"%w+")
5688 end
5689
5690 local function apply_tonumber (no_fail,...)
5691 local args = {...}
5692 for i = 1,#args do
5693 local n = tonumber(args[i])
5694 if n == nil then
5695 if not no_fail then return nil,args[i] end
5696 else
5697 args[i] = n
5698 end
5699 end
5700 return args
5701 end
5702
5703 --- parse an input source into fields.
5704 -- By default, will fail if it cannot convert a field to a number.
5705 -- @param ids a list of field indices, or a maximum field index
5706 -- @string delim delimiter to parse fields (default space)
5707 -- @param f a source @see create_getter
5708 -- @tab opts option table, `{no_fail=true}`
5709 -- @return an iterator with the field values
5710 -- @usage for x,y in fields {2,3} do print(x,y) end -- 2nd and 3rd fields from stdin
5711 function input.fields (ids,delim,f,opts)
5712 local sep
5713 local s
5714 local getter = input.create_getter(f)
5715 local no_fail = opts and opts.no_fail
5716 local no_convert = opts and opts.no_convert
5717 if not delim or delim == ' ' then
5718 delim = '%s'
5719 sep = '%s+'
5720 s = '%s*'
5721 else
5722 sep = delim
5723 s = ''
5724 end
5725 local max_id = 0
5726 if type(ids) == 'table' then
5727 for i,id in pairs(ids) do
5728 if id > max_id then max_id = id end
5729 end
5730 else
5731 max_id = ids
5732 ids = {}
5733 for i = 1,max_id do ids[#ids+1] = i end
5734 end
5735 local pat = '[^'..delim..']*'
5736 local k = 1
5737 for i = 1,max_id do
5738 if ids[k] == i then
5739 k = k + 1
5740 s = s..'('..pat..')'
5741 else
5742 s = s..pat
5743 end
5744 if i < max_id then
5745 s = s..sep
5746 end
5747 end
5748 local linecount = 1
5749 return function()
5750 local line,results,err
5751 repeat
5752 line = getter()
5753 linecount = linecount + 1
5754 if not line then return nil end
5755 if no_convert then
5756 results = {strmatch(line,s)}
5757 else
5758 results,err = apply_tonumber(no_fail,strmatch(line,s))
5759 if not results then
5760 utils.quit("line "..(linecount-1)..": cannot convert '"..err.."' to number")
5761 end
5762 end
5763 until #results > 0
5764 return unpack(results)
5765 end
5766 end
5767
5768 return input
5769
5770
5771 end,
5772
5773 ["pl.lapp"] = function()
5774 --------------------
5775 -- Module: 'pl.lapp'
5776 --------------------
5777 --- Simple command-line parsing using human-readable specification.
5778 -- Supports GNU-style parameters.
5779 --
5780 -- lapp = require 'pl.lapp'
5781 -- local args = lapp [[
5782 -- Does some calculations
5783 -- -o,--offset (default 0.0) Offset to add to scaled number
5784 -- -s,--scale (number) Scaling factor
5785 -- <number> (number) Number to be scaled
5786 -- ]]
5787 --
5788 -- print(args.offset + args.scale * args.number)
5789 --
5790 -- Lines beginning with `'-'` are flags; there may be a short and a long name;
5791 -- lines beginning with `'<var>'` are arguments. Anything in parens after
5792 -- the flag/argument is either a default, a type name or a range constraint.
5793 --
5794 -- See @{08-additional.md.Command_line_Programs_with_Lapp|the Guide}
5795 --
5796 -- Dependencies: `pl.sip`
5797 -- @module pl.lapp
5798
5799 local status,sip = pcall(require,'pl.sip')
5800 if not status then
5801 sip = require 'sip'
5802 end
5803 local match = sip.match_at_start
5804 local append,tinsert = table.insert,table.insert
5805
5806 sip.custom_pattern('X','(%a[%w_%-]*)')
5807
5808 local function lines(s) return s:gmatch('([^\n]*)\n') end
5809 local function lstrip(str) return str:gsub('^%s+','') end
5810 local function strip(str) return lstrip(str):gsub('%s+$','') end
5811 local function at(s,k) return s:sub(k,k) end
5812
5813 local lapp = {}
5814
5815 local open_files,parms,aliases,parmlist,usage,script
5816
5817 lapp.callback = false -- keep Strict happy
5818
5819 local filetypes = {
5820 stdin = {io.stdin,'file-in'}, stdout = {io.stdout,'file-out'},
5821 stderr = {io.stderr,'file-out'}
5822 }
5823
5824 --- controls whether to dump usage on error.
5825 -- Defaults to true
5826 lapp.show_usage_error = true
5827
5828 --- quit this script immediately.
5829 -- @string msg optional message
5830 -- @bool no_usage suppress 'usage' display
5831 function lapp.quit(msg,no_usage)
5832 if no_usage == 'throw' then
5833 error(msg)
5834 end
5835 if msg then
5836 io.stderr:write(msg..'\n\n')
5837 end
5838 if not no_usage then
5839 io.stderr:write(usage)
5840 end
5841 os.exit(1)
5842 end
5843
5844 --- print an error to stderr and quit.
5845 -- @string msg a message
5846 -- @bool no_usage suppress 'usage' display
5847 function lapp.error(msg,no_usage)
5848 if not lapp.show_usage_error then
5849 no_usage = true
5850 elseif lapp.show_usage_error == 'throw' then
5851 no_usage = 'throw'
5852 end
5853 lapp.quit(script..': '..msg,no_usage)
5854 end
5855
5856 --- open a file.
5857 -- This will quit on error, and keep a list of file objects for later cleanup.
5858 -- @string file filename
5859 -- @string[opt] opt same as second parameter of `io.open`
5860 function lapp.open (file,opt)
5861 local val,err = io.open(file,opt)
5862 if not val then lapp.error(err,true) end
5863 append(open_files,val)
5864 return val
5865 end
5866
5867 --- quit if the condition is false.
5868 -- @bool condn a condition
5869 -- @string msg message text
5870 function lapp.assert(condn,msg)
5871 if not condn then
5872 lapp.error(msg)
5873 end
5874 end
5875
5876 local function range_check(x,min,max,parm)
5877 lapp.assert(min <= x and max >= x,parm..' out of range')
5878 end
5879
5880 local function xtonumber(s)
5881 local val = tonumber(s)
5882 if not val then lapp.error("unable to convert to number: "..s) end
5883 return val
5884 end
5885
5886 local types = {}
5887
5888 local builtin_types = {string=true,number=true,['file-in']='file',['file-out']='file',boolean=true}
5889
5890 local function convert_parameter(ps,val)
5891 if ps.converter then
5892 val = ps.converter(val)
5893 end
5894 if ps.type == 'number' then
5895 val = xtonumber(val)
5896 elseif builtin_types[ps.type] == 'file' then
5897 val = lapp.open(val,(ps.type == 'file-in' and 'r') or 'w' )
5898 elseif ps.type == 'boolean' then
5899 return val
5900 end
5901 if ps.constraint then
5902 ps.constraint(val)
5903 end
5904 return val
5905 end
5906
5907 --- add a new type to Lapp. These appear in parens after the value like
5908 -- a range constraint, e.g. '<ival> (integer) Process PID'
5909 -- @string name name of type
5910 -- @param converter either a function to convert values, or a Lua type name.
5911 -- @func[opt] constraint optional function to verify values, should use lapp.error
5912 -- if failed.
5913 function lapp.add_type (name,converter,constraint)
5914 types[name] = {converter=converter,constraint=constraint}
5915 end
5916
5917 local function force_short(short)
5918 lapp.assert(#short==1,short..": short parameters should be one character")
5919 end
5920
5921 -- deducing type of variable from default value;
5922 local function process_default (sval,vtype)
5923 local val, success
5924 if not vtype or vtype == 'number' then
5925 val = tonumber(sval)
5926 end
5927 if val then -- we have a number!
5928 return val,'number'
5929 elseif filetypes[sval] then
5930 local ft = filetypes[sval]
5931 return ft[1],ft[2]
5932 else
5933 if sval == 'true' and not vtype then
5934 return true, 'boolean'
5935 end
5936 if sval:match '^["\']' then sval = sval:sub(2,-2) end
5937
5938 local ps = types[vtype] or {}
5939 ps.type = vtype
5940
5941 local show_usage_error = lapp.show_usage_error
5942 lapp.show_usage_error = "throw"
5943 success, val = pcall(convert_parameter, ps, sval)
5944 lapp.show_usage_error = show_usage_error
5945 if success then
5946 return val, vtype or 'string'
5947 end
5948
5949 return sval,vtype or 'string'
5950 end
5951 end
5952
5953 --- process a Lapp options string.
5954 -- Usually called as `lapp()`.
5955 -- @string str the options text
5956 -- @tparam {string} args a table of arguments (default is `_G.arg`)
5957 -- @return a table with parameter-value pairs
5958 function lapp.process_options_string(str,args)
5959 local results = {}
5960 local varargs
5961 local arg = args or _G.arg
5962 open_files = {}
5963 parms = {}
5964 aliases = {}
5965 parmlist = {}
5966
5967 local function check_varargs(s)
5968 local res,cnt = s:gsub('^%.%.%.%s*','')
5969 return res, (cnt > 0)
5970 end
5971
5972 local function set_result(ps,parm,val)
5973 parm = type(parm) == "string" and parm:gsub("%W", "_") or parm -- so foo-bar becomes foo_bar in Lua
5974 if not ps.varargs then
5975 results[parm] = val
5976 else
5977 if not results[parm] then
5978 results[parm] = { val }
5979 else
5980 append(results[parm],val)
5981 end
5982 end
5983 end
5984
5985 usage = str
5986
5987 for _,a in ipairs(arg) do
5988 if a == "-h" or a == "--help" then
5989 return lapp.quit()
5990 end
5991 end
5992
5993
5994 for line in lines(str) do
5995 local res = {}
5996 local optparm,defval,vtype,constraint,rest
5997 line = lstrip(line)
5998 local function check(str)
5999 return match(str,line,res)
6000 end
6001
6002 -- flags: either '-<short>', '-<short>,--<long>' or '--<long>'
6003 if check '-$v{short}, --$o{long} $' or check '-$v{short} $' or check '--$o{long} $' then
6004 if res.long then
6005 optparm = res.long:gsub('[^%w%-]','_') -- I'm not sure the $o pattern will let anything else through?
6006 if #res.rest == 1 then optparm = optparm .. res.rest end
6007 if res.short then aliases[res.short] = optparm end
6008 else
6009 optparm = res.short
6010 end
6011 if res.short and not lapp.slack then force_short(res.short) end
6012 res.rest, varargs = check_varargs(res.rest)
6013 elseif check '$<{name} $' then -- is it <parameter_name>?
6014 -- so <input file...> becomes input_file ...
6015 optparm,rest = res.name:match '([^%.]+)(.*)'
6016 -- follow lua legal variable names
6017 optparm = optparm:sub(1,1):gsub('%A','_') .. optparm:sub(2):gsub('%W', '_')
6018 varargs = rest == '...'
6019 append(parmlist,optparm)
6020 end
6021 -- this is not a pure doc line and specifies the flag/parameter type
6022 if res.rest then
6023 line = res.rest
6024 res = {}
6025 local optional
6026 local defval_str
6027 -- do we have ([optional] [<type>] [default <val>])?
6028 if match('$({def} $',line,res) or match('$({def}',line,res) then
6029 local typespec = strip(res.def)
6030 local ftype, rest = typespec:match('^(%S+)(.*)$')
6031 rest = strip(rest)
6032 if ftype == 'optional' then
6033 ftype, rest = rest:match('^(%S+)(.*)$')
6034 rest = strip(rest)
6035 optional = true
6036 end
6037 local default
6038 if ftype == 'default' then
6039 default = true
6040 if rest == '' then lapp.error("value must follow default") end
6041 else -- a type specification
6042 if match('$f{min}..$f{max}',ftype,res) then
6043 -- a numerical range like 1..10
6044 local min,max = res.min,res.max
6045 vtype = 'number'
6046 constraint = function(x)
6047 range_check(x,min,max,optparm)
6048 end
6049 elseif not ftype:match '|' then -- plain type
6050 vtype = ftype
6051 else
6052 -- 'enum' type is a string which must belong to
6053 -- one of several distinct values
6054 local enums = ftype
6055 local enump = '|' .. enums .. '|'
6056 vtype = 'string'
6057 constraint = function(s)
6058 lapp.assert(enump:find('|'..s..'|', 1, true),
6059 "value '"..s.."' not in "..enums
6060 )
6061 end
6062 end
6063 end
6064 res.rest = rest
6065 typespec = res.rest
6066 -- optional 'default value' clause. Type is inferred as
6067 -- 'string' or 'number' if there's no explicit type
6068 if default or match('default $r{rest}',typespec,res) then
6069 defval_str = res.rest
6070 defval,vtype = process_default(res.rest,vtype)
6071 end
6072 else -- must be a plain flag, no extra parameter required
6073 defval = false
6074 vtype = 'boolean'
6075 end
6076 local ps = {
6077 type = vtype,
6078 defval = defval,
6079 defval_str = defval_str,
6080 required = defval == nil and not optional,
6081 comment = res.rest or optparm,
6082 constraint = constraint,
6083 varargs = varargs
6084 }
6085 varargs = nil
6086 if types[vtype] then
6087 local converter = types[vtype].converter
6088 if type(converter) == 'string' then
6089 ps.type = converter
6090 else
6091 ps.converter = converter
6092 end
6093 ps.constraint = types[vtype].constraint
6094 elseif not builtin_types[vtype] and vtype then
6095 lapp.error(vtype.." is unknown type")
6096 end
6097 parms[optparm] = ps
6098 end
6099 end
6100 -- cool, we have our parms, let's parse the command line args
6101 local iparm = 1
6102 local iextra = 1
6103 local i = 1
6104 local parm,ps,val
6105 local end_of_flags = false
6106
6107 local function check_parm (parm)
6108 local eqi = parm:find '[=:]'
6109 if eqi then
6110 tinsert(arg,i+1,parm:sub(eqi+1))
6111 parm = parm:sub(1,eqi-1)
6112 end
6113 return parm,eqi
6114 end
6115
6116 local function is_flag (parm)
6117 return parms[aliases[parm] or parm]
6118 end
6119
6120 while i <= #arg do
6121 local theArg = arg[i]
6122 local res = {}
6123 -- after '--' we don't parse args and they end up in
6124 -- the array part of the result (args[1] etc)
6125 if theArg == '--' then
6126 end_of_flags = true
6127 iparm = #parmlist + 1
6128 i = i + 1
6129 theArg = arg[i]
6130 if not theArg then
6131 break
6132 end
6133 end
6134 -- look for a flag, -<short flags> or --<long flag>
6135 if not end_of_flags and (match('--$S{long}',theArg,res) or match('-$S{short}',theArg,res)) then
6136 if res.long then -- long option
6137 parm = check_parm(res.long)
6138 elseif #res.short == 1 or is_flag(res.short) then
6139 parm = res.short
6140 else
6141 local parmstr,eq = check_parm(res.short)
6142 if not eq then
6143 parm = at(parmstr,1)
6144 local flag = is_flag(parm)
6145 if flag and flag.type ~= 'boolean' then
6146 --if isdigit(at(parmstr,2)) then
6147 -- a short option followed by a digit is an exception (for AW;))
6148 -- push ahead into the arg array
6149 tinsert(arg,i+1,parmstr:sub(2))
6150 else
6151 -- push multiple flags into the arg array!
6152 for k = 2,#parmstr do
6153 tinsert(arg,i+k-1,'-'..at(parmstr,k))
6154 end
6155 end
6156 else
6157 parm = parmstr
6158 end
6159 end
6160 if aliases[parm] then parm = aliases[parm] end
6161 if not parms[parm] and (parm == 'h' or parm == 'help') then
6162 lapp.quit()
6163 end
6164 else -- a parameter
6165 parm = parmlist[iparm]
6166 if not parm then
6167 -- extra unnamed parameters are indexed starting at 1
6168 parm = iextra
6169 ps = { type = 'string' }
6170 parms[parm] = ps
6171 iextra = iextra + 1
6172 else
6173 ps = parms[parm]
6174 end
6175 if not ps.varargs then
6176 iparm = iparm + 1
6177 end
6178 val = theArg
6179 end
6180 ps = parms[parm]
6181 if not ps then lapp.error("unrecognized parameter: "..parm) end
6182 if ps.type ~= 'boolean' then -- we need a value! This should follow
6183 if not val then
6184 i = i + 1
6185 val = arg[i]
6186 theArg = val
6187 end
6188 lapp.assert(val,parm.." was expecting a value")
6189 else -- toggle boolean flags (usually false -> true)
6190 val = not ps.defval
6191 end
6192 ps.used = true
6193 val = convert_parameter(ps,val)
6194 set_result(ps,parm,val)
6195 if builtin_types[ps.type] == 'file' then
6196 set_result(ps,parm..'_name',theArg)
6197 end
6198 if lapp.callback then
6199 lapp.callback(parm,theArg,res)
6200 end
6201 i = i + 1
6202 val = nil
6203 end
6204 -- check unused parms, set defaults and check if any required parameters were missed
6205 for parm,ps in pairs(parms) do
6206 if not ps.used then
6207 if ps.required then lapp.error("missing required parameter: "..parm) end
6208 set_result(ps,parm,ps.defval)
6209 if builtin_types[ps.type] == "file" then
6210 set_result(ps, parm .. "_name", ps.defval_str)
6211 end
6212 end
6213 end
6214 return results
6215 end
6216
6217 if arg then
6218 script = arg[0]
6219 script = script or rawget(_G,"LAPP_SCRIPT") or "unknown"
6220 -- strip dir and extension to get current script name
6221 script = script:gsub('.+[\\/]',''):gsub('%.%a+$','')
6222 else
6223 script = "inter"
6224 end
6225
6226
6227 setmetatable(lapp, {
6228 __call = function(tbl,str,args) return lapp.process_options_string(str,args) end,
6229 })
6230
6231
6232 return lapp
6233
6234
6235
6236 end,
6237
6238 ["pl.lexer"] = function()
6239 --------------------
6240 -- Module: 'pl.lexer'
6241 --------------------
6242 --- Lexical scanner for creating a sequence of tokens from text.
6243 -- `lexer.scan(s)` returns an iterator over all tokens found in the
6244 -- string `s`. This iterator returns two values, a token type string
6245 -- (such as 'string' for quoted string, 'iden' for identifier) and the value of the
6246 -- token.
6247 --
6248 -- Versions specialized for Lua and C are available; these also handle block comments
6249 -- and classify keywords as 'keyword' tokens. For example:
6250 --
6251 -- > s = 'for i=1,n do'
6252 -- > for t,v in lexer.lua(s) do print(t,v) end
6253 -- keyword for
6254 -- iden i
6255 -- = =
6256 -- number 1
6257 -- , ,
6258 -- iden n
6259 -- keyword do
6260 --
6261 -- See the Guide for further @{06-data.md.Lexical_Scanning|discussion}
6262 -- @module pl.lexer
6263
6264 local strfind = string.find
6265 local strsub = string.sub
6266 local append = table.insert
6267
6268
6269 local function assert_arg(idx,val,tp)
6270 if type(val) ~= tp then
6271 error("argument "..idx.." must be "..tp, 2)
6272 end
6273 end
6274
6275 local lexer = {}
6276
6277 local NUMBER1 = '^[%+%-]?%d+%.?%d*[eE][%+%-]?%d+'
6278 local NUMBER1a = '^[%+%-]?%d*%.%d+[eE][%+%-]?%d+'
6279 local NUMBER2 = '^[%+%-]?%d+%.?%d*'
6280 local NUMBER2a = '^[%+%-]?%d*%.%d+'
6281 local NUMBER3 = '^0x[%da-fA-F]+'
6282 local NUMBER4 = '^%d+%.?%d*[eE][%+%-]?%d+'
6283 local NUMBER4a = '^%d*%.%d+[eE][%+%-]?%d+'
6284 local NUMBER5 = '^%d+%.?%d*'
6285 local NUMBER5a = '^%d*%.%d+'
6286 local IDEN = '^[%a_][%w_]*'
6287 local WSPACE = '^%s+'
6288 local STRING1 = "^(['\"])%1" -- empty string
6289 local STRING2 = [[^(['"])(\*)%2%1]]
6290 local STRING3 = [[^(['"]).-[^\](\*)%2%1]]
6291 local CHAR1 = "^''"
6292 local CHAR2 = [[^'(\*)%1']]
6293 local CHAR3 = [[^'.-[^\](\*)%1']]
6294 local PREPRO = '^#.-[^\\]\n'
6295
6296 local plain_matches,lua_matches,cpp_matches,lua_keyword,cpp_keyword
6297
6298 local function tdump(tok)
6299 return tok,tok
6300 end
6301
6302 local function ndump(tok,options)
6303 if options and options.number then
6304 tok = tonumber(tok)
6305 end
6306 return "number",tok
6307 end
6308
6309 -- regular strings, single or double quotes; usually we want them
6310 -- without the quotes
6311 local function sdump(tok,options)
6312 if options and options.string then
6313 tok = tok:sub(2,-2)
6314 end
6315 return "string",tok
6316 end
6317
6318 -- long Lua strings need extra work to get rid of the quotes
6319 local function sdump_l(tok,options,findres)
6320 if options and options.string then
6321 local quotelen = 3
6322 if findres[3] then
6323 quotelen = quotelen + findres[3]:len()
6324 end
6325 tok = tok:sub(quotelen, -quotelen)
6326 if tok:sub(1, 1) == "\n" then
6327 tok = tok:sub(2)
6328 end
6329 end
6330 return "string",tok
6331 end
6332
6333 local function chdump(tok,options)
6334 if options and options.string then
6335 tok = tok:sub(2,-2)
6336 end
6337 return "char",tok
6338 end
6339
6340 local function cdump(tok)
6341 return "comment",tok
6342 end
6343
6344 local function wsdump (tok)
6345 return "space",tok
6346 end
6347
6348 local function pdump (tok)
6349 return "prepro",tok
6350 end
6351
6352 local function plain_vdump(tok)
6353 return "iden",tok
6354 end
6355
6356 local function lua_vdump(tok)
6357 if lua_keyword[tok] then
6358 return "keyword",tok
6359 else
6360 return "iden",tok
6361 end
6362 end
6363
6364 local function cpp_vdump(tok)
6365 if cpp_keyword[tok] then
6366 return "keyword",tok
6367 else
6368 return "iden",tok
6369 end
6370 end
6371
6372 --- create a plain token iterator from a string or file-like object.
6373 -- @tparam string|file s a string or a file-like object with `:read()` method returning lines.
6374 -- @tab matches an optional match table - array of token descriptions.
6375 -- A token is described by a `{pattern, action}` pair, where `pattern` should match
6376 -- token body and `action` is a function called when a token of described type is found.
6377 -- @tab[opt] filter a table of token types to exclude, by default `{space=true}`
6378 -- @tab[opt] options a table of options; by default, `{number=true,string=true}`,
6379 -- which means convert numbers and strip string quotes.
6380 function lexer.scan(s,matches,filter,options)
6381 local file = type(s) ~= 'string' and s
6382 filter = filter or {space=true}
6383 options = options or {number=true,string=true}
6384 if filter then
6385 if filter.space then filter[wsdump] = true end
6386 if filter.comments then
6387 filter[cdump] = true
6388 end
6389 end
6390 if not matches then
6391 if not plain_matches then
6392 plain_matches = {
6393 {WSPACE,wsdump},
6394 {NUMBER3,ndump},
6395 {IDEN,plain_vdump},
6396 {NUMBER1,ndump},
6397 {NUMBER1a,ndump},
6398 {NUMBER2,ndump},
6399 {NUMBER2a,ndump},
6400 {STRING1,sdump},
6401 {STRING2,sdump},
6402 {STRING3,sdump},
6403 {'^.',tdump}
6404 }
6405 end
6406 matches = plain_matches
6407 end
6408
6409 local line_nr = 0
6410 local next_line = file and file:read()
6411 local sz = file and 0 or #s
6412 local idx = 1
6413
6414 local tlist_i
6415 local tlist
6416
6417 local first_hit = true
6418
6419 local function iter(res)
6420 local tp = type(res)
6421
6422 if tlist then -- returning the inserted token list
6423 local cur = tlist[tlist_i]
6424 if cur then
6425 tlist_i = tlist_i + 1
6426 return cur[1], cur[2]
6427 else
6428 tlist = nil
6429 end
6430 end
6431
6432 if tp == 'string' then -- search up to some special pattern
6433 local i1,i2 = strfind(s,res,idx)
6434 if i1 then
6435 local tok = strsub(s,i1,i2)
6436 idx = i2 + 1
6437 return '', tok
6438 else
6439 idx = sz + 1
6440 return '', ''
6441 end
6442
6443 elseif tp == 'table' then -- insert a token list
6444 tlist_i = 1
6445 tlist = res
6446 return '', ''
6447
6448 elseif tp ~= 'nil' then -- return position
6449 return line_nr, idx
6450
6451 else -- look for next token
6452 if first_hit then
6453 if not file then line_nr = 1 end
6454 first_hit = false
6455 end
6456
6457 if idx > sz then
6458 if file then
6459 if not next_line then
6460 return -- past the end of file, done
6461 end
6462 s = next_line
6463 line_nr = line_nr + 1
6464 next_line = file:read()
6465 if next_line then
6466 s = s .. '\n'
6467 end
6468 idx, sz = 1, #s
6469 else
6470 return -- past the end of input, done
6471 end
6472 end
6473
6474 for _,m in ipairs(matches) do
6475 local pat = m[1]
6476 local fun = m[2]
6477 local findres = {strfind(s,pat,idx)}
6478 local i1, i2 = findres[1], findres[2]
6479 if i1 then
6480 local tok = strsub(s,i1,i2)
6481 idx = i2 + 1
6482 local ret1, ret2
6483 if not (filter and filter[fun]) then
6484 lexer.finished = idx > sz
6485 ret1, ret2 = fun(tok, options, findres)
6486 end
6487 if not file and tok:find("\n") then
6488 -- Update line number.
6489 local _, newlines = tok:gsub("\n", {})
6490 line_nr = line_nr + newlines
6491 end
6492 if ret1 then
6493 return ret1, ret2 -- found a match
6494 else
6495 return iter() -- tail-call to try again
6496 end
6497 end
6498 end
6499 end
6500 end
6501
6502 return iter
6503 end
6504
6505 local function isstring (s)
6506 return type(s) == 'string'
6507 end
6508
6509 --- insert tokens into a stream.
6510 -- @param tok a token stream
6511 -- @param a1 a string is the type, a table is a token list and
6512 -- a function is assumed to be a token-like iterator (returns type & value)
6513 -- @string a2 a string is the value
6514 function lexer.insert (tok,a1,a2)
6515 if not a1 then return end
6516 local ts
6517 if isstring(a1) and isstring(a2) then
6518 ts = {{a1,a2}}
6519 elseif type(a1) == 'function' then
6520 ts = {}
6521 for t,v in a1() do
6522 append(ts,{t,v})
6523 end
6524 else
6525 ts = a1
6526 end
6527 tok(ts)
6528 end
6529
6530 --- get everything in a stream upto a newline.
6531 -- @param tok a token stream
6532 -- @return a string
6533 function lexer.getline (tok)
6534 local _,v = tok('.-\n')
6535 return v
6536 end
6537
6538 --- get current line number.
6539 -- @param tok a token stream
6540 -- @return the line number.
6541 -- if the input source is a file-like object,
6542 -- also return the column.
6543 function lexer.lineno (tok)
6544 return tok(0)
6545 end
6546
6547 --- get the rest of the stream.
6548 -- @param tok a token stream
6549 -- @return a string
6550 function lexer.getrest (tok)
6551 local _,v = tok('.+')
6552 return v
6553 end
6554
6555 --- get the Lua keywords as a set-like table.
6556 -- So `res["and"]` etc would be `true`.
6557 -- @return a table
6558 function lexer.get_keywords ()
6559 if not lua_keyword then
6560 lua_keyword = {
6561 ["and"] = true, ["break"] = true, ["do"] = true,
6562 ["else"] = true, ["elseif"] = true, ["end"] = true,
6563 ["false"] = true, ["for"] = true, ["function"] = true,
6564 ["if"] = true, ["in"] = true, ["local"] = true, ["nil"] = true,
6565 ["not"] = true, ["or"] = true, ["repeat"] = true,
6566 ["return"] = true, ["then"] = true, ["true"] = true,
6567 ["until"] = true, ["while"] = true
6568 }
6569 end
6570 return lua_keyword
6571 end
6572
6573 --- create a Lua token iterator from a string or file-like object.
6574 -- Will return the token type and value.
6575 -- @string s the string
6576 -- @tab[opt] filter a table of token types to exclude, by default `{space=true,comments=true}`
6577 -- @tab[opt] options a table of options; by default, `{number=true,string=true}`,
6578 -- which means convert numbers and strip string quotes.
6579 function lexer.lua(s,filter,options)
6580 filter = filter or {space=true,comments=true}
6581 lexer.get_keywords()
6582 if not lua_matches then
6583 lua_matches = {
6584 {WSPACE,wsdump},
6585 {NUMBER3,ndump},
6586 {IDEN,lua_vdump},
6587 {NUMBER4,ndump},
6588 {NUMBER4a,ndump},
6589 {NUMBER5,ndump},
6590 {NUMBER5a,ndump},
6591 {STRING1,sdump},
6592 {STRING2,sdump},
6593 {STRING3,sdump},
6594 {'^%-%-%[(=*)%[.-%]%1%]',cdump},
6595 {'^%-%-.-\n',cdump},
6596 {'^%[(=*)%[.-%]%1%]',sdump_l},
6597 {'^==',tdump},
6598 {'^~=',tdump},
6599 {'^<=',tdump},
6600 {'^>=',tdump},
6601 {'^%.%.%.',tdump},
6602 {'^%.%.',tdump},
6603 {'^.',tdump}
6604 }
6605 end
6606 return lexer.scan(s,lua_matches,filter,options)
6607 end
6608
6609 --- create a C/C++ token iterator from a string or file-like object.
6610 -- Will return the token type type and value.
6611 -- @string s the string
6612 -- @tab[opt] filter a table of token types to exclude, by default `{space=true,comments=true}`
6613 -- @tab[opt] options a table of options; by default, `{number=true,string=true}`,
6614 -- which means convert numbers and strip string quotes.
6615 function lexer.cpp(s,filter,options)
6616 filter = filter or {space=true,comments=true}
6617 if not cpp_keyword then
6618 cpp_keyword = {
6619 ["class"] = true, ["break"] = true, ["do"] = true, ["sizeof"] = true,
6620 ["else"] = true, ["continue"] = true, ["struct"] = true,
6621 ["false"] = true, ["for"] = true, ["public"] = true, ["void"] = true,
6622 ["private"] = true, ["protected"] = true, ["goto"] = true,
6623 ["if"] = true, ["static"] = true, ["const"] = true, ["typedef"] = true,
6624 ["enum"] = true, ["char"] = true, ["int"] = true, ["bool"] = true,
6625 ["long"] = true, ["float"] = true, ["true"] = true, ["delete"] = true,
6626 ["double"] = true, ["while"] = true, ["new"] = true,
6627 ["namespace"] = true, ["try"] = true, ["catch"] = true,
6628 ["switch"] = true, ["case"] = true, ["extern"] = true,
6629 ["return"] = true,["default"] = true,['unsigned'] = true,['signed'] = true,
6630 ["union"] = true, ["volatile"] = true, ["register"] = true,["short"] = true,
6631 }
6632 end
6633 if not cpp_matches then
6634 cpp_matches = {
6635 {WSPACE,wsdump},
6636 {PREPRO,pdump},
6637 {NUMBER3,ndump},
6638 {IDEN,cpp_vdump},
6639 {NUMBER4,ndump},
6640 {NUMBER4a,ndump},
6641 {NUMBER5,ndump},
6642 {NUMBER5a,ndump},
6643 {CHAR1,chdump},
6644 {CHAR2,chdump},
6645 {CHAR3,chdump},
6646 {STRING1,sdump},
6647 {STRING2,sdump},
6648 {STRING3,sdump},
6649 {'^//.-\n',cdump},
6650 {'^/%*.-%*/',cdump},
6651 {'^==',tdump},
6652 {'^!=',tdump},
6653 {'^<=',tdump},
6654 {'^>=',tdump},
6655 {'^->',tdump},
6656 {'^&&',tdump},
6657 {'^||',tdump},
6658 {'^%+%+',tdump},
6659 {'^%-%-',tdump},
6660 {'^%+=',tdump},
6661 {'^%-=',tdump},
6662 {'^%*=',tdump},
6663 {'^/=',tdump},
6664 {'^|=',tdump},
6665 {'^%^=',tdump},
6666 {'^::',tdump},
6667 {'^.',tdump}
6668 }
6669 end
6670 return lexer.scan(s,cpp_matches,filter,options)
6671 end
6672
6673 --- get a list of parameters separated by a delimiter from a stream.
6674 -- @param tok the token stream
6675 -- @string[opt=')'] endtoken end of list. Can be '\n'
6676 -- @string[opt=','] delim separator
6677 -- @return a list of token lists.
6678 function lexer.get_separated_list(tok,endtoken,delim)
6679 endtoken = endtoken or ')'
6680 delim = delim or ','
6681 local parm_values = {}
6682 local level = 1 -- used to count ( and )
6683 local tl = {}
6684 local function tappend (tl,t,val)
6685 val = val or t
6686 append(tl,{t,val})
6687 end
6688 local is_end
6689 if endtoken == '\n' then
6690 is_end = function(t,val)
6691 return t == 'space' and val:find '\n'
6692 end
6693 else
6694 is_end = function (t)
6695 return t == endtoken
6696 end
6697 end
6698 local token,value
6699 while true do
6700 token,value=tok()
6701 if not token then return nil,'EOS' end -- end of stream is an error!
6702 if is_end(token,value) and level == 1 then
6703 append(parm_values,tl)
6704 break
6705 elseif token == '(' then
6706 level = level + 1
6707 tappend(tl,'(')
6708 elseif token == ')' then
6709 level = level - 1
6710 if level == 0 then -- finished with parm list
6711 append(parm_values,tl)
6712 break
6713 else
6714 tappend(tl,')')
6715 end
6716 elseif token == delim and level == 1 then
6717 append(parm_values,tl) -- a new parm
6718 tl = {}
6719 else
6720 tappend(tl,token,value)
6721 end
6722 end
6723 return parm_values,{token,value}
6724 end
6725
6726 --- get the next non-space token from the stream.
6727 -- @param tok the token stream.
6728 function lexer.skipws (tok)
6729 local t,v = tok()
6730 while t == 'space' do
6731 t,v = tok()
6732 end
6733 return t,v
6734 end
6735
6736 local skipws = lexer.skipws
6737
6738 --- get the next token, which must be of the expected type.
6739 -- Throws an error if this type does not match!
6740 -- @param tok the token stream
6741 -- @string expected_type the token type
6742 -- @bool no_skip_ws whether we should skip whitespace
6743 function lexer.expecting (tok,expected_type,no_skip_ws)
6744 assert_arg(1,tok,'function')
6745 assert_arg(2,expected_type,'string')
6746 local t,v
6747 if no_skip_ws then
6748 t,v = tok()
6749 else
6750 t,v = skipws(tok)
6751 end
6752 if t ~= expected_type then error ("expecting "..expected_type,2) end
6753 return v
6754 end
6755
6756 return lexer
6757
6758 end,
6759
6760 ["pl.List"] = function()
6761 --------------------
6762 -- Module: 'pl.List'
6763 --------------------
6764 --- Python-style list class.
6765 --
6766 -- **Please Note**: methods that change the list will return the list.
6767 -- This is to allow for method chaining, but please note that `ls = ls:sort()`
6768 -- does not mean that a new copy of the list is made. In-place (mutable) methods
6769 -- are marked as returning 'the list' in this documentation.
6770 --
6771 -- See the Guide for further @{02-arrays.md.Python_style_Lists|discussion}
6772 --
6773 -- See <a href="http://www.python.org/doc/current/tut/tut.html">http://www.python.org/doc/current/tut/tut.html</a>, section 5.1
6774 --
6775 -- **Note**: The comments before some of the functions are from the Python docs
6776 -- and contain Python code.
6777 --
6778 -- Written for Lua version Nick Trout 4.0; Redone for Lua 5.1, Steve Donovan.
6779 --
6780 -- Dependencies: `pl.utils`, `pl.tablex`, `pl.class`
6781 -- @classmod pl.List
6782 -- @pragma nostrip
6783
6784 local tinsert,tremove,concat,tsort = table.insert,table.remove,table.concat,table.sort
6785 local setmetatable, getmetatable,type,tostring,string = setmetatable,getmetatable,type,tostring,string
6786 local tablex = require 'pl.tablex'
6787 local filter,imap,imap2,reduce,transform,tremovevalues = tablex.filter,tablex.imap,tablex.imap2,tablex.reduce,tablex.transform,tablex.removevalues
6788 local tsub = tablex.sub
6789 local utils = require 'pl.utils'
6790 local class = require 'pl.class'
6791
6792 local array_tostring,split,assert_arg,function_arg = utils.array_tostring,utils.split,utils.assert_arg,utils.function_arg
6793 local normalize_slice = tablex._normalize_slice
6794
6795 -- metatable for our list and map objects has already been defined..
6796 local Multimap = utils.stdmt.MultiMap
6797 local List = utils.stdmt.List
6798
6799 local iter
6800
6801 class(nil,nil,List)
6802
6803 -- we want the result to be _covariant_, i.e. t must have type of obj if possible
6804 local function makelist (t,obj)
6805 local klass = List
6806 if obj then
6807 klass = getmetatable(obj)
6808 end
6809 return setmetatable(t,klass)
6810 end
6811
6812 local function simple_table(t)
6813 return type(t) == 'table' and not getmetatable(t) and #t > 0
6814 end
6815
6816 function List._create (src)
6817 if simple_table(src) then return src end
6818 end
6819
6820 function List:_init (src)
6821 if self == src then return end -- existing table used as self!
6822 if src then
6823 for v in iter(src) do
6824 tinsert(self,v)
6825 end
6826 end
6827 end
6828
6829 --- Create a new list. Can optionally pass a table;
6830 -- passing another instance of List will cause a copy to be created;
6831 -- this will return a plain table with an appropriate metatable.
6832 -- we pass anything which isn't a simple table to iterate() to work out
6833 -- an appropriate iterator
6834 -- @see List.iterate
6835 -- @param[opt] t An optional list-like table
6836 -- @return a new List
6837 -- @usage ls = List(); ls = List {1,2,3,4}
6838 -- @function List.new
6839
6840 List.new = List
6841
6842 --- Make a copy of an existing list.
6843 -- The difference from a plain 'copy constructor' is that this returns
6844 -- the actual List subtype.
6845 function List:clone()
6846 local ls = makelist({},self)
6847 ls:extend(self)
6848 return ls
6849 end
6850
6851 --- Add an item to the end of the list.
6852 -- @param i An item
6853 -- @return the list
6854 function List:append(i)
6855 tinsert(self,i)
6856 return self
6857 end
6858
6859 List.push = tinsert
6860
6861 --- Extend the list by appending all the items in the given list.
6862 -- equivalent to 'a[len(a):] = L'.
6863 -- @tparam List L Another List
6864 -- @return the list
6865 function List:extend(L)
6866 assert_arg(1,L,'table')
6867 for i = 1,#L do tinsert(self,L[i]) end
6868 return self
6869 end
6870
6871 --- Insert an item at a given position. i is the index of the
6872 -- element before which to insert.
6873 -- @int i index of element before whichh to insert
6874 -- @param x A data item
6875 -- @return the list
6876 function List:insert(i, x)
6877 assert_arg(1,i,'number')
6878 tinsert(self,i,x)
6879 return self
6880 end
6881
6882 --- Insert an item at the beginning of the list.
6883 -- @param x a data item
6884 -- @return the list
6885 function List:put (x)
6886 return self:insert(1,x)
6887 end
6888
6889 --- Remove an element given its index.
6890 -- (equivalent of Python's del s[i])
6891 -- @int i the index
6892 -- @return the list
6893 function List:remove (i)
6894 assert_arg(1,i,'number')
6895 tremove(self,i)
6896 return self
6897 end
6898
6899 --- Remove the first item from the list whose value is given.
6900 -- (This is called 'remove' in Python; renamed to avoid confusion
6901 -- with table.remove)
6902 -- Return nil if there is no such item.
6903 -- @param x A data value
6904 -- @return the list
6905 function List:remove_value(x)
6906 for i=1,#self do
6907 if self[i]==x then tremove(self,i) return self end
6908 end
6909 return self
6910 end
6911
6912 --- Remove the item at the given position in the list, and return it.
6913 -- If no index is specified, a:pop() returns the last item in the list.
6914 -- The item is also removed from the list.
6915 -- @int[opt] i An index
6916 -- @return the item
6917 function List:pop(i)
6918 if not i then i = #self end
6919 assert_arg(1,i,'number')
6920 return tremove(self,i)
6921 end
6922
6923 List.get = List.pop
6924
6925 --- Return the index in the list of the first item whose value is given.
6926 -- Return nil if there is no such item.
6927 -- @function List:index
6928 -- @param x A data value
6929 -- @int[opt=1] idx where to start search
6930 -- @return the index, or nil if not found.
6931
6932 local tfind = tablex.find
6933 List.index = tfind
6934
6935 --- Does this list contain the value?
6936 -- @param x A data value
6937 -- @return true or false
6938 function List:contains(x)
6939 return tfind(self,x) and true or false
6940 end
6941
6942 --- Return the number of times value appears in the list.
6943 -- @param x A data value
6944 -- @return number of times x appears
6945 function List:count(x)
6946 local cnt=0
6947 for i=1,#self do
6948 if self[i]==x then cnt=cnt+1 end
6949 end
6950 return cnt
6951 end
6952
6953 --- Sort the items of the list, in place.
6954 -- @func[opt='<'] cmp an optional comparison function
6955 -- @return the list
6956 function List:sort(cmp)
6957 if cmp then cmp = function_arg(1,cmp) end
6958 tsort(self,cmp)
6959 return self
6960 end
6961
6962 --- Return a sorted copy of this list.
6963 -- @func[opt='<'] cmp an optional comparison function
6964 -- @return a new list
6965 function List:sorted(cmp)
6966 return List(self):sort(cmp)
6967 end
6968
6969 --- Reverse the elements of the list, in place.
6970 -- @return the list
6971 function List:reverse()
6972 local t = self
6973 local n = #t
6974 for i = 1,n/2 do
6975 t[i],t[n] = t[n],t[i]
6976 n = n - 1
6977 end
6978 return self
6979 end
6980
6981 --- Return the minimum and the maximum value of the list.
6982 -- @return minimum value
6983 -- @return maximum value
6984 function List:minmax()
6985 local vmin,vmax = 1e70,-1e70
6986 for i = 1,#self do
6987 local v = self[i]
6988 if v < vmin then vmin = v end
6989 if v > vmax then vmax = v end
6990 end
6991 return vmin,vmax
6992 end
6993
6994 --- Emulate list slicing. like 'list[first:last]' in Python.
6995 -- If first or last are negative then they are relative to the end of the list
6996 -- eg. slice(-2) gives last 2 entries in a list, and
6997 -- slice(-4,-2) gives from -4th to -2nd
6998 -- @param first An index
6999 -- @param last An index
7000 -- @return a new List
7001 function List:slice(first,last)
7002 return tsub(self,first,last)
7003 end
7004
7005 --- Empty the list.
7006 -- @return the list
7007 function List:clear()
7008 for i=1,#self do tremove(self) end
7009 return self
7010 end
7011
7012 local eps = 1.0e-10
7013
7014 --- Emulate Python's range(x) function.
7015 -- Include it in List table for tidiness
7016 -- @int start A number
7017 -- @int[opt] finish A number greater than start; if absent,
7018 -- then start is 1 and finish is start
7019 -- @int[opt=1] incr an increment (may be less than 1)
7020 -- @return a List from start .. finish
7021 -- @usage List.range(0,3) == List{0,1,2,3}
7022 -- @usage List.range(4) = List{1,2,3,4}
7023 -- @usage List.range(5,1,-1) == List{5,4,3,2,1}
7024 function List.range(start,finish,incr)
7025 if not finish then
7026 finish = start
7027 start = 1
7028 end
7029 if incr then
7030 assert_arg(3,incr,'number')
7031 if math.ceil(incr) ~= incr then finish = finish + eps end
7032 else
7033 incr = 1
7034 end
7035 assert_arg(1,start,'number')
7036 assert_arg(2,finish,'number')
7037 local t = List()
7038 for i=start,finish,incr do tinsert(t,i) end
7039 return t
7040 end
7041
7042 --- list:len() is the same as #list.
7043 function List:len()
7044 return #self
7045 end
7046
7047 -- Extended operations --
7048
7049 --- Remove a subrange of elements.
7050 -- equivalent to 'del s[i1:i2]' in Python.
7051 -- @int i1 start of range
7052 -- @int i2 end of range
7053 -- @return the list
7054 function List:chop(i1,i2)
7055 return tremovevalues(self,i1,i2)
7056 end
7057
7058 --- Insert a sublist into a list
7059 -- equivalent to 's[idx:idx] = list' in Python
7060 -- @int idx index
7061 -- @tparam List list list to insert
7062 -- @return the list
7063 -- @usage l = List{10,20}; l:splice(2,{21,22}); assert(l == List{10,21,22,20})
7064 function List:splice(idx,list)
7065 assert_arg(1,idx,'number')
7066 idx = idx - 1
7067 local i = 1
7068 for v in iter(list) do
7069 tinsert(self,i+idx,v)
7070 i = i + 1
7071 end
7072 return self
7073 end
7074
7075 --- General slice assignment s[i1:i2] = seq.
7076 -- @int i1 start index
7077 -- @int i2 end index
7078 -- @tparam List seq a list
7079 -- @return the list
7080 function List:slice_assign(i1,i2,seq)
7081 assert_arg(1,i1,'number')
7082 assert_arg(1,i2,'number')
7083 i1,i2 = normalize_slice(self,i1,i2)
7084 if i2 >= i1 then self:chop(i1,i2) end
7085 self:splice(i1,seq)
7086 return self
7087 end
7088
7089 --- Concatenation operator.
7090 -- @within metamethods
7091 -- @tparam List L another List
7092 -- @return a new list consisting of the list with the elements of the new list appended
7093 function List:__concat(L)
7094 assert_arg(1,L,'table')
7095 local ls = self:clone()
7096 ls:extend(L)
7097 return ls
7098 end
7099
7100 --- Equality operator ==. True iff all elements of two lists are equal.
7101 -- @within metamethods
7102 -- @tparam List L another List
7103 -- @return true or false
7104 function List:__eq(L)
7105 if #self ~= #L then return false end
7106 for i = 1,#self do
7107 if self[i] ~= L[i] then return false end
7108 end
7109 return true
7110 end
7111
7112 --- Join the elements of a list using a delimiter.
7113 -- This method uses tostring on all elements.
7114 -- @string[opt=''] delim a delimiter string, can be empty.
7115 -- @return a string
7116 function List:join (delim)
7117 delim = delim or ''
7118 assert_arg(1,delim,'string')
7119 return concat(array_tostring(self),delim)
7120 end
7121
7122 --- Join a list of strings. <br>
7123 -- Uses `table.concat` directly.
7124 -- @function List:concat
7125 -- @string[opt=''] delim a delimiter
7126 -- @return a string
7127 List.concat = concat
7128
7129 local function tostring_q(val)
7130 local s = tostring(val)
7131 if type(val) == 'string' then
7132 s = '"'..s..'"'
7133 end
7134 return s
7135 end
7136
7137 --- How our list should be rendered as a string. Uses join().
7138 -- @within metamethods
7139 -- @see List:join
7140 function List:__tostring()
7141 return '{'..self:join(',',tostring_q)..'}'
7142 end
7143
7144 --- Call the function on each element of the list.
7145 -- @func fun a function or callable object
7146 -- @param ... optional values to pass to function
7147 function List:foreach (fun,...)
7148 fun = function_arg(1,fun)
7149 for i = 1,#self do
7150 fun(self[i],...)
7151 end
7152 end
7153
7154 local function lookup_fun (obj,name)
7155 local f = obj[name]
7156 if not f then error(type(obj).." does not have method "..name,3) end
7157 return f
7158 end
7159
7160 --- Call the named method on each element of the list.
7161 -- @string name the method name
7162 -- @param ... optional values to pass to function
7163 function List:foreachm (name,...)
7164 for i = 1,#self do
7165 local obj = self[i]
7166 local f = lookup_fun(obj,name)
7167 f(obj,...)
7168 end
7169 end
7170
7171 --- Create a list of all elements which match a function.
7172 -- @func fun a boolean function
7173 -- @param[opt] arg optional argument to be passed as second argument of the predicate
7174 -- @return a new filtered list.
7175 function List:filter (fun,arg)
7176 return makelist(filter(self,fun,arg),self)
7177 end
7178
7179 --- Split a string using a delimiter.
7180 -- @string s the string
7181 -- @string[opt] delim the delimiter (default spaces)
7182 -- @return a List of strings
7183 -- @see pl.utils.split
7184 function List.split (s,delim)
7185 assert_arg(1,s,'string')
7186 return makelist(split(s,delim))
7187 end
7188
7189 --- Apply a function to all elements.
7190 -- Any extra arguments will be passed to the function.
7191 -- @func fun a function of at least one argument
7192 -- @param ... arbitrary extra arguments.
7193 -- @return a new list: {f(x) for x in self}
7194 -- @usage List{'one','two'}:map(string.upper) == {'ONE','TWO'}
7195 -- @see pl.tablex.imap
7196 function List:map (fun,...)
7197 return makelist(imap(fun,self,...),self)
7198 end
7199
7200 --- Apply a function to all elements, in-place.
7201 -- Any extra arguments are passed to the function.
7202 -- @func fun A function that takes at least one argument
7203 -- @param ... arbitrary extra arguments.
7204 -- @return the list.
7205 function List:transform (fun,...)
7206 transform(fun,self,...)
7207 return self
7208 end
7209
7210 --- Apply a function to elements of two lists.
7211 -- Any extra arguments will be passed to the function
7212 -- @func fun a function of at least two arguments
7213 -- @tparam List ls another list
7214 -- @param ... arbitrary extra arguments.
7215 -- @return a new list: {f(x,y) for x in self, for x in arg1}
7216 -- @see pl.tablex.imap2
7217 function List:map2 (fun,ls,...)
7218 return makelist(imap2(fun,self,ls,...),self)
7219 end
7220
7221 --- apply a named method to all elements.
7222 -- Any extra arguments will be passed to the method.
7223 -- @string name name of method
7224 -- @param ... extra arguments
7225 -- @return a new list of the results
7226 -- @see pl.seq.mapmethod
7227 function List:mapm (name,...)
7228 local res = {}
7229 for i = 1,#self do
7230 local val = self[i]
7231 local fn = lookup_fun(val,name)
7232 res[i] = fn(val,...)
7233 end
7234 return makelist(res,self)
7235 end
7236
7237 local function composite_call (method,f)
7238 return function(self,...)
7239 return self[method](self,f,...)
7240 end
7241 end
7242
7243 function List.default_map_with(T)
7244 return function(self,name)
7245 local m
7246 if T then
7247 local f = lookup_fun(T,name)
7248 m = composite_call('map',f)
7249 else
7250 m = composite_call('mapn',name)
7251 end
7252 getmetatable(self)[name] = m -- and cache..
7253 return m
7254 end
7255 end
7256
7257 List.default_map = List.default_map_with
7258
7259 --- 'reduce' a list using a binary function.
7260 -- @func fun a function of two arguments
7261 -- @return result of the function
7262 -- @see pl.tablex.reduce
7263 function List:reduce (fun)
7264 return reduce(fun,self)
7265 end
7266
7267 --- Partition a list using a classifier function.
7268 -- The function may return nil, but this will be converted to the string key '<nil>'.
7269 -- @func fun a function of at least one argument
7270 -- @param ... will also be passed to the function
7271 -- @treturn MultiMap a table where the keys are the returned values, and the values are Lists
7272 -- of values where the function returned that key.
7273 -- @see pl.MultiMap
7274 function List:partition (fun,...)
7275 fun = function_arg(1,fun)
7276 local res = {}
7277 for i = 1,#self do
7278 local val = self[i]
7279 local klass = fun(val,...)
7280 if klass == nil then klass = '<nil>' end
7281 if not res[klass] then res[klass] = List() end
7282 res[klass]:append(val)
7283 end
7284 return setmetatable(res,Multimap)
7285 end
7286
7287 --- return an iterator over all values.
7288 function List:iter ()
7289 return iter(self)
7290 end
7291
7292 --- Create an iterator over a sequence.
7293 -- This captures the Python concept of 'sequence'.
7294 -- For tables, iterates over all values with integer indices.
7295 -- @param seq a sequence; a string (over characters), a table, a file object (over lines) or an iterator function
7296 -- @usage for x in iterate {1,10,22,55} do io.write(x,',') end ==> 1,10,22,55
7297 -- @usage for ch in iterate 'help' do do io.write(ch,' ') end ==> h e l p
7298 function List.iterate(seq)
7299 if type(seq) == 'string' then
7300 local idx = 0
7301 local n = #seq
7302 local sub = string.sub
7303 return function ()
7304 idx = idx + 1
7305 if idx > n then return nil
7306 else
7307 return sub(seq,idx,idx)
7308 end
7309 end
7310 elseif type(seq) == 'table' then
7311 local idx = 0
7312 local n = #seq
7313 return function()
7314 idx = idx + 1
7315 if idx > n then return nil
7316 else
7317 return seq[idx]
7318 end
7319 end
7320 elseif type(seq) == 'function' then
7321 return seq
7322 elseif type(seq) == 'userdata' and io.type(seq) == 'file' then
7323 return seq:lines()
7324 end
7325 end
7326 iter = List.iterate
7327
7328 return List
7329
7330
7331 end,
7332
7333 ["pl.luabalanced"] = function()
7334 --------------------
7335 -- Module: 'pl.luabalanced'
7336 --------------------
7337 --- Extract delimited Lua sequences from strings.
7338 -- Inspired by Damian Conway's Text::Balanced in Perl. <br/>
7339 -- <ul>
7340 -- <li>[1] <a href="http://lua-users.org/wiki/LuaBalanced">Lua Wiki Page</a></li>
7341 -- <li>[2] http://search.cpan.org/dist/Text-Balanced/lib/Text/Balanced.pm</li>
7342 -- </ul> <br/>
7343 -- <pre class=example>
7344 -- local lb = require "pl.luabalanced"
7345 -- --Extract Lua expression starting at position 4.
7346 -- print(lb.match_expression("if x^2 + x > 5 then print(x) end", 4))
7347 -- --> x^2 + x > 5 16
7348 -- --Extract Lua string starting at (default) position 1.
7349 -- print(lb.match_string([["test\"123" .. "more"]]))
7350 -- --> "test\"123" 12
7351 -- </pre>
7352 -- (c) 2008, David Manura, Licensed under the same terms as Lua (MIT license).
7353 -- @class module
7354 -- @name pl.luabalanced
7355
7356 local M = {}
7357
7358 local assert = assert
7359
7360 -- map opening brace <-> closing brace.
7361 local ends = { ['('] = ')', ['{'] = '}', ['['] = ']' }
7362 local begins = {}; for k,v in pairs(ends) do begins[v] = k end
7363
7364
7365 -- Match Lua string in string <s> starting at position <pos>.
7366 -- Returns <string>, <posnew>, where <string> is the matched
7367 -- string (or nil on no match) and <posnew> is the character
7368 -- following the match (or <pos> on no match).
7369 -- Supports all Lua string syntax: "...", '...', [[...]], [=[...]=], etc.
7370 local function match_string(s, pos)
7371 pos = pos or 1
7372 local posa = pos
7373 local c = s:sub(pos,pos)
7374 if c == '"' or c == "'" then
7375 pos = pos + 1
7376 while 1 do
7377 pos = assert(s:find("[" .. c .. "\\]", pos), 'syntax error')
7378 if s:sub(pos,pos) == c then
7379 local part = s:sub(posa, pos)
7380 return part, pos + 1
7381 else
7382 pos = pos + 2
7383 end
7384 end
7385 else
7386 local sc = s:match("^%[(=*)%[", pos)
7387 if sc then
7388 local _; _, pos = s:find("%]" .. sc .. "%]", pos)
7389 assert(pos)
7390 local part = s:sub(posa, pos)
7391 return part, pos + 1
7392 else
7393 return nil, pos
7394 end
7395 end
7396 end
7397 M.match_string = match_string
7398
7399
7400 -- Match bracketed Lua expression, e.g. "(...)", "{...}", "[...]", "[[...]]",
7401 -- [=[...]=], etc.
7402 -- Function interface is similar to match_string.
7403 local function match_bracketed(s, pos)
7404 pos = pos or 1
7405 local posa = pos
7406 local ca = s:sub(pos,pos)
7407 if not ends[ca] then
7408 return nil, pos
7409 end
7410 local stack = {}
7411 while 1 do
7412 pos = s:find('[%(%{%[%)%}%]\"\']', pos)
7413 assert(pos, 'syntax error: unbalanced')
7414 local c = s:sub(pos,pos)
7415 if c == '"' or c == "'" then
7416 local part; part, pos = match_string(s, pos)
7417 assert(part)
7418 elseif ends[c] then -- open
7419 local mid, posb
7420 if c == '[' then mid, posb = s:match('^%[(=*)%[()', pos) end
7421 if mid then
7422 pos = s:match('%]' .. mid .. '%]()', posb)
7423 assert(pos, 'syntax error: long string not terminated')
7424 if #stack == 0 then
7425 local part = s:sub(posa, pos-1)
7426 return part, pos
7427 end
7428 else
7429 stack[#stack+1] = c
7430 pos = pos + 1
7431 end
7432 else -- close
7433 assert(stack[#stack] == assert(begins[c]), 'syntax error: unbalanced')
7434 stack[#stack] = nil
7435 if #stack == 0 then
7436 local part = s:sub(posa, pos)
7437 return part, pos+1
7438 end
7439 pos = pos + 1
7440 end
7441 end
7442 end
7443 M.match_bracketed = match_bracketed
7444
7445
7446 -- Match Lua comment, e.g. "--...\n", "--[[...]]", "--[=[...]=]", etc.
7447 -- Function interface is similar to match_string.
7448 local function match_comment(s, pos)
7449 pos = pos or 1
7450 if s:sub(pos, pos+1) ~= '--' then
7451 return nil, pos
7452 end
7453 pos = pos + 2
7454 local partt, post = match_string(s, pos)
7455 if partt then
7456 return '--' .. partt, post
7457 end
7458 local part; part, pos = s:match('^([^\n]*\n?)()', pos)
7459 return '--' .. part, pos
7460 end
7461
7462
7463 -- Match Lua expression, e.g. "a + b * c[e]".
7464 -- Function interface is similar to match_string.
7465 local wordop = {['and']=true, ['or']=true, ['not']=true}
7466 local is_compare = {['>']=true, ['<']=true, ['~']=true}
7467 local function match_expression(s, pos)
7468 pos = pos or 1
7469 local _
7470 local posa = pos
7471 local lastident
7472 local poscs, posce
7473 while pos do
7474 local c = s:sub(pos,pos)
7475 if c == '"' or c == "'" or c == '[' and s:find('^[=%[]', pos+1) then
7476 local part; part, pos = match_string(s, pos)
7477 assert(part, 'syntax error')
7478 elseif c == '-' and s:sub(pos+1,pos+1) == '-' then
7479 -- note: handle adjacent comments in loop to properly support
7480 -- backtracing (poscs/posce).
7481 poscs = pos
7482 while s:sub(pos,pos+1) == '--' do
7483 local part; part, pos = match_comment(s, pos)
7484 assert(part)
7485 pos = s:match('^%s*()', pos)
7486 posce = pos
7487 end
7488 elseif c == '(' or c == '{' or c == '[' then
7489 _, pos = match_bracketed(s, pos)
7490 elseif c == '=' and s:sub(pos+1,pos+1) == '=' then
7491 pos = pos + 2 -- skip over two-char op containing '='
7492 elseif c == '=' and is_compare[s:sub(pos-1,pos-1)] then
7493 pos = pos + 1 -- skip over two-char op containing '='
7494 elseif c:match'^[%)%}%];,=]' then
7495 local part = s:sub(posa, pos-1)
7496 return part, pos
7497 elseif c:match'^[%w_]' then
7498 local newident,newpos = s:match('^([%w_]+)()', pos)
7499 if pos ~= posa and not wordop[newident] then -- non-first ident
7500 local pose = ((posce == pos) and poscs or pos) - 1
7501 while s:match('^%s', pose) do pose = pose - 1 end
7502 local ce = s:sub(pose,pose)
7503 if ce:match'[%)%}\'\"%]]' or
7504 ce:match'[%w_]' and not wordop[lastident]
7505 then
7506 local part = s:sub(posa, pos-1)
7507 return part, pos
7508 end
7509 end
7510 lastident, pos = newident, newpos
7511 else
7512 pos = pos + 1
7513 end
7514 pos = s:find('[%(%{%[%)%}%]\"\';,=%w_%-]', pos)
7515 end
7516 local part = s:sub(posa, #s)
7517 return part, #s+1
7518 end
7519 M.match_expression = match_expression
7520
7521
7522 -- Match name list (zero or more names). E.g. "a,b,c"
7523 -- Function interface is similar to match_string,
7524 -- but returns array as match.
7525 local function match_namelist(s, pos)
7526 pos = pos or 1
7527 local list = {}
7528 while 1 do
7529 local c = #list == 0 and '^' or '^%s*,%s*'
7530 local item, post = s:match(c .. '([%a_][%w_]*)%s*()', pos)
7531 if item then pos = post else break end
7532 list[#list+1] = item
7533 end
7534 return list, pos
7535 end
7536 M.match_namelist = match_namelist
7537
7538
7539 -- Match expression list (zero or more expressions). E.g. "a+b,b*c".
7540 -- Function interface is similar to match_string,
7541 -- but returns array as match.
7542 local function match_explist(s, pos)
7543 pos = pos or 1
7544 local list = {}
7545 while 1 do
7546 if #list ~= 0 then
7547 local post = s:match('^%s*,%s*()', pos)
7548 if post then pos = post else break end
7549 end
7550 local item; item, pos = match_expression(s, pos)
7551 assert(item, 'syntax error')
7552 list[#list+1] = item
7553 end
7554 return list, pos
7555 end
7556 M.match_explist = match_explist
7557
7558
7559 -- Replace snippets of code in Lua code string <s>
7560 -- using replacement function f(u,sin) --> sout.
7561 -- <u> is the type of snippet ('c' = comment, 's' = string,
7562 -- 'e' = any other code).
7563 -- Snippet is replaced with <sout> (unless <sout> is nil or false, in
7564 -- which case the original snippet is kept)
7565 -- This is somewhat analogous to string.gsub .
7566 local function gsub(s, f)
7567 local pos = 1
7568 local posa = 1
7569 local sret = ''
7570 while 1 do
7571 pos = s:find('[%-\'\"%[]', pos)
7572 if not pos then break end
7573 if s:match('^%-%-', pos) then
7574 local exp = s:sub(posa, pos-1)
7575 if #exp > 0 then sret = sret .. (f('e', exp) or exp) end
7576 local comment; comment, pos = match_comment(s, pos)
7577 sret = sret .. (f('c', assert(comment)) or comment)
7578 posa = pos
7579 else
7580 local posb = s:find('^[\'\"%[]', pos)
7581 local str
7582 if posb then str, pos = match_string(s, posb) end
7583 if str then
7584 local exp = s:sub(posa, posb-1)
7585 if #exp > 0 then sret = sret .. (f('e', exp) or exp) end
7586 sret = sret .. (f('s', str) or str)
7587 posa = pos
7588 else
7589 pos = pos + 1
7590 end
7591 end
7592 end
7593 local exp = s:sub(posa)
7594 if #exp > 0 then sret = sret .. (f('e', exp) or exp) end
7595 return sret
7596 end
7597 M.gsub = gsub
7598
7599
7600 return M
7601
7602 end,
7603
7604 ["pl.Map"] = function()
7605 --------------------
7606 -- Module: 'pl.Map'
7607 --------------------
7608 --- A Map class.
7609 --
7610 -- > Map = require 'pl.Map'
7611 -- > m = Map{one=1,two=2}
7612 -- > m:update {three=3,four=4,two=20}
7613 -- > = m == M{one=1,two=20,three=3,four=4}
7614 -- true
7615 --
7616 -- Dependencies: `pl.utils`, `pl.class`, `pl.tablex`, `pl.pretty`
7617 -- @classmod pl.Map
7618
7619 local tablex = require 'pl.tablex'
7620 local utils = require 'pl.utils'
7621 local stdmt = utils.stdmt
7622 local deepcompare = tablex.deepcompare
7623
7624 local pretty_write = require 'pl.pretty' . write
7625 local Map = stdmt.Map
7626 local Set = stdmt.Set
7627
7628 local class = require 'pl.class'
7629
7630 -- the Map class ---------------------
7631 class(nil,nil,Map)
7632
7633 function Map:_init (t)
7634 local mt = getmetatable(t)
7635 if mt == Set or mt == Map then
7636 self:update(t)
7637 else
7638 return t -- otherwise assumed to be a map-like table
7639 end
7640 end
7641
7642
7643 local function makelist(t)
7644 return setmetatable(t, require('pl.List'))
7645 end
7646
7647 --- return a List of all keys.
7648 -- @class function
7649 -- @name Map:keys
7650 Map.keys = tablex.keys
7651
7652 --- return a List of all values.
7653 -- @class function
7654 -- @name Map:values
7655 Map.values = tablex.values
7656
7657 --- return an iterator over all key-value pairs.
7658 function Map:iter ()
7659 return pairs(self)
7660 end
7661
7662 --- return a List of all key-value pairs, sorted by the keys in ascending order.
7663 function Map:items()
7664 local ls = makelist(tablex.pairmap (function (k,v) return makelist {k,v} end, self))
7665 ls:sort(function(t1,t2) return t1[1] < t2[1] end)
7666 return ls
7667 end
7668
7669 --- set a value in the map if it doesn't exist yet.
7670 -- @param key the key
7671 -- @param default value to set
7672 -- @return the value stored in the map (existing value, or the new value)
7673 function Map:setdefault(key, default)
7674 local val = self[key]
7675 if val ~= nil then
7676 return val
7677 end
7678 self:set(key,default)
7679 return default
7680 end
7681
7682 --- size of map.
7683 -- note: this is a relatively expensive operation!
7684 -- @class function
7685 -- @name Map:len
7686 Map.len = tablex.size
7687
7688 --- put a value into the map.
7689 -- This will remove the key if the value is `nil`
7690 -- @param key the key
7691 -- @param val the value
7692 function Map:set (key,val)
7693 self[key] = val
7694 end
7695
7696 --- get a value from the map.
7697 -- @param key the key
7698 -- @return the value, or nil if not found.
7699 function Map:get (key)
7700 return rawget(self,key)
7701 end
7702
7703 local index_by = tablex.index_by
7704
7705 --- get a list of values indexed by a list of keys.
7706 -- @param keys a list-like table of keys
7707 -- @return a new list
7708 function Map:getvalues (keys)
7709 return makelist(index_by(self,keys))
7710 end
7711
7712 --- update the map using key/value pairs from another table.
7713 -- @tab table
7714 -- @function Map:update
7715 Map.update = tablex.update
7716
7717 --- equality between maps.
7718 -- @within metamethods
7719 -- @tparam Map m another map.
7720 function Map:__eq (m)
7721 -- note we explicitly ask deepcompare _not_ to use __eq!
7722 return deepcompare(self,m,true)
7723 end
7724
7725 --- string representation of a map.
7726 -- @within metamethods
7727 function Map:__tostring ()
7728 return pretty_write(self,'')
7729 end
7730
7731 return Map
7732
7733 end,
7734
7735 ["pl.MultiMap"] = function()
7736 --------------------
7737 -- Module: 'pl.MultiMap'
7738 --------------------
7739 --- MultiMap, a Map which has multiple values per key.
7740 --
7741 -- Dependencies: `pl.utils`, `pl.class`, `pl.List`, `pl.Map`
7742 -- @classmod pl.MultiMap
7743
7744 local utils = require 'pl.utils'
7745 local class = require 'pl.class'
7746 local List = require 'pl.List'
7747 local Map = require 'pl.Map'
7748
7749 -- MultiMap is a standard MT
7750 local MultiMap = utils.stdmt.MultiMap
7751
7752 class(Map,nil,MultiMap)
7753 MultiMap._name = 'MultiMap'
7754
7755 function MultiMap:_init (t)
7756 if not t then return end
7757 self:update(t)
7758 end
7759
7760 --- update a MultiMap using a table.
7761 -- @param t either a Multimap or a map-like table.
7762 -- @return the map
7763 function MultiMap:update (t)
7764 utils.assert_arg(1,t,'table')
7765 if Map:class_of(t) then
7766 for k,v in pairs(t) do
7767 self[k] = List()
7768 self[k]:append(v)
7769 end
7770 else
7771 for k,v in pairs(t) do
7772 self[k] = List(v)
7773 end
7774 end
7775 end
7776
7777 --- add a new value to a key. Setting a nil value removes the key.
7778 -- @param key the key
7779 -- @param val the value
7780 -- @return the map
7781 function MultiMap:set (key,val)
7782 if val == nil then
7783 self[key] = nil
7784 else
7785 if not self[key] then
7786 self[key] = List()
7787 end
7788 self[key]:append(val)
7789 end
7790 end
7791
7792 return MultiMap
7793
7794 end,
7795
7796 ["pl.operator"] = function()
7797 --------------------
7798 -- Module: 'pl.operator'
7799 --------------------
7800 --- Lua operators available as functions.
7801 --
7802 -- (similar to the Python module of the same name)
7803 --
7804 -- There is a module field `optable` which maps the operator strings
7805 -- onto these functions, e.g. `operator.optable['()']==operator.call`
7806 --
7807 -- Operator strings like '>' and '{}' can be passed to most Penlight functions
7808 -- expecting a function argument.
7809 --
7810 -- @module pl.operator
7811
7812 local strfind = string.find
7813
7814 local operator = {}
7815
7816 --- apply function to some arguments **()**
7817 -- @param fn a function or callable object
7818 -- @param ... arguments
7819 function operator.call(fn,...)
7820 return fn(...)
7821 end
7822
7823 --- get the indexed value from a table **[]**
7824 -- @param t a table or any indexable object
7825 -- @param k the key
7826 function operator.index(t,k)
7827 return t[k]
7828 end
7829
7830 --- returns true if arguments are equal **==**
7831 -- @param a value
7832 -- @param b value
7833 function operator.eq(a,b)
7834 return a==b
7835 end
7836
7837 --- returns true if arguments are not equal **~=**
7838 -- @param a value
7839 -- @param b value
7840 function operator.neq(a,b)
7841 return a~=b
7842 end
7843
7844 --- returns true if a is less than b **<**
7845 -- @param a value
7846 -- @param b value
7847 function operator.lt(a,b)
7848 return a < b
7849 end
7850
7851 --- returns true if a is less or equal to b **<=**
7852 -- @param a value
7853 -- @param b value
7854 function operator.le(a,b)
7855 return a <= b
7856 end
7857
7858 --- returns true if a is greater than b **>**
7859 -- @param a value
7860 -- @param b value
7861 function operator.gt(a,b)
7862 return a > b
7863 end
7864
7865 --- returns true if a is greater or equal to b **>=**
7866 -- @param a value
7867 -- @param b value
7868 function operator.ge(a,b)
7869 return a >= b
7870 end
7871
7872 --- returns length of string or table **#**
7873 -- @param a a string or a table
7874 function operator.len(a)
7875 return #a
7876 end
7877
7878 --- add two values **+**
7879 -- @param a value
7880 -- @param b value
7881 function operator.add(a,b)
7882 return a+b
7883 end
7884
7885 --- subtract b from a **-**
7886 -- @param a value
7887 -- @param b value
7888 function operator.sub(a,b)
7889 return a-b
7890 end
7891
7892 --- multiply two values __*__
7893 -- @param a value
7894 -- @param b value
7895 function operator.mul(a,b)
7896 return a*b
7897 end
7898
7899 --- divide first value by second **/**
7900 -- @param a value
7901 -- @param b value
7902 function operator.div(a,b)
7903 return a/b
7904 end
7905
7906 --- raise first to the power of second **^**
7907 -- @param a value
7908 -- @param b value
7909 function operator.pow(a,b)
7910 return a^b
7911 end
7912
7913 --- modulo; remainder of a divided by b **%**
7914 -- @param a value
7915 -- @param b value
7916 function operator.mod(a,b)
7917 return a%b
7918 end
7919
7920 --- concatenate two values (either strings or `__concat` defined) **..**
7921 -- @param a value
7922 -- @param b value
7923 function operator.concat(a,b)
7924 return a..b
7925 end
7926
7927 --- return the negative of a value **-**
7928 -- @param a value
7929 function operator.unm(a)
7930 return -a
7931 end
7932
7933 --- false if value evaluates as true **not**
7934 -- @param a value
7935 function operator.lnot(a)
7936 return not a
7937 end
7938
7939 --- true if both values evaluate as true **and**
7940 -- @param a value
7941 -- @param b value
7942 function operator.land(a,b)
7943 return a and b
7944 end
7945
7946 --- true if either value evaluate as true **or**
7947 -- @param a value
7948 -- @param b value
7949 function operator.lor(a,b)
7950 return a or b
7951 end
7952
7953 --- make a table from the arguments **{}**
7954 -- @param ... non-nil arguments
7955 -- @return a table
7956 function operator.table (...)
7957 return {...}
7958 end
7959
7960 --- match two strings **~**.
7961 -- uses @{string.find}
7962 function operator.match (a,b)
7963 return strfind(a,b)~=nil
7964 end
7965
7966 --- the null operation.
7967 -- @param ... arguments
7968 -- @return the arguments
7969 function operator.nop (...)
7970 return ...
7971 end
7972
7973 ---- Map from operator symbol to function.
7974 -- Most of these map directly from operators;
7975 -- But note these extras
7976 --
7977 -- * __'()'__ `call`
7978 -- * __'[]'__ `index`
7979 -- * __'{}'__ `table`
7980 -- * __'~'__ `match`
7981 --
7982 -- @table optable
7983 -- @field operator
7984 operator.optable = {
7985 ['+']=operator.add,
7986 ['-']=operator.sub,
7987 ['*']=operator.mul,
7988 ['/']=operator.div,
7989 ['%']=operator.mod,
7990 ['^']=operator.pow,
7991 ['..']=operator.concat,
7992 ['()']=operator.call,
7993 ['[]']=operator.index,
7994 ['<']=operator.lt,
7995 ['<=']=operator.le,
7996 ['>']=operator.gt,
7997 ['>=']=operator.ge,
7998 ['==']=operator.eq,
7999 ['~=']=operator.neq,
8000 ['#']=operator.len,
8001 ['and']=operator.land,
8002 ['or']=operator.lor,
8003 ['{}']=operator.table,
8004 ['~']=operator.match,
8005 ['']=operator.nop,
8006 }
8007
8008 return operator
8009
8010 end,
8011
8012 ["pl.OrderedMap"] = function()
8013 --------------------
8014 -- Module: 'pl.OrderedMap'
8015 --------------------
8016 --- OrderedMap, a map which preserves ordering.
8017 --
8018 -- Derived from `pl.Map`.
8019 --
8020 -- Dependencies: `pl.utils`, `pl.tablex`, `pl.class`, `pl.List`, `pl.Map`
8021 -- @classmod pl.OrderedMap
8022
8023 local tablex = require 'pl.tablex'
8024 local utils = require 'pl.utils'
8025 local List = require 'pl.List'
8026 local index_by,tsort,concat = tablex.index_by,table.sort,table.concat
8027
8028 local class = require 'pl.class'
8029 local Map = require 'pl.Map'
8030
8031 local OrderedMap = class(Map)
8032 OrderedMap._name = 'OrderedMap'
8033
8034 local rawset = rawset
8035
8036 --- construct an OrderedMap.
8037 -- Will throw an error if the argument is bad.
8038 -- @param t optional initialization table, same as for @{OrderedMap:update}
8039 function OrderedMap:_init (t)
8040 rawset(self,'_keys',List())
8041 if t then
8042 local map,err = self:update(t)
8043 if not map then error(err,2) end
8044 end
8045 end
8046
8047 local assert_arg,raise = utils.assert_arg,utils.raise
8048
8049 --- update an OrderedMap using a table.
8050 -- If the table is itself an OrderedMap, then its entries will be appended.
8051 -- if it s a table of the form `{{key1=val1},{key2=val2},...}` these will be appended.
8052 --
8053 -- Otherwise, it is assumed to be a map-like table, and order of extra entries is arbitrary.
8054 -- @tab t a table.
8055 -- @return the map, or nil in case of error
8056 -- @return the error message
8057 function OrderedMap:update (t)
8058 assert_arg(1,t,'table')
8059 if OrderedMap:class_of(t) then
8060 for k,v in t:iter() do
8061 self:set(k,v)
8062 end
8063 elseif #t > 0 then -- an array must contain {key=val} tables
8064 if type(t[1]) == 'table' then
8065 for _,pair in ipairs(t) do
8066 local key,value = next(pair)
8067 if not key then return raise 'empty pair initialization table' end
8068 self:set(key,value)
8069 end
8070 else
8071 return raise 'cannot use an array to initialize an OrderedMap'
8072 end
8073 else
8074 for k,v in pairs(t) do
8075 self:set(k,v)
8076 end
8077 end
8078 return self
8079 end
8080
8081 --- set the key's value. This key will be appended at the end of the map.
8082 --
8083 -- If the value is nil, then the key is removed.
8084 -- @param key the key
8085 -- @param val the value
8086 -- @return the map
8087 function OrderedMap:set (key,val)
8088 if rawget(self, key) == nil and val ~= nil then -- new key
8089 self._keys:append(key) -- we keep in order
8090 rawset(self,key,val) -- don't want to provoke __newindex!
8091 else -- existing key-value pair
8092 if val == nil then
8093 self._keys:remove_value(key)
8094 rawset(self,key,nil)
8095 else
8096 self[key] = val
8097 end
8098 end
8099 return self
8100 end
8101
8102 OrderedMap.__newindex = OrderedMap.set
8103
8104 --- insert a key/value pair before a given position.
8105 -- Note: if the map already contains the key, then this effectively
8106 -- moves the item to the new position by first removing at the old position.
8107 -- Has no effect if the key does not exist and val is nil
8108 -- @int pos a position starting at 1
8109 -- @param key the key
8110 -- @param val the value; if nil use the old value
8111 function OrderedMap:insert (pos,key,val)
8112 local oldval = self[key]
8113 val = val or oldval
8114 if oldval then
8115 self._keys:remove_value(key)
8116 end
8117 if val then
8118 self._keys:insert(pos,key)
8119 rawset(self,key,val)
8120 end
8121 return self
8122 end
8123
8124 --- return the keys in order.
8125 -- (Not a copy!)
8126 -- @return List
8127 function OrderedMap:keys ()
8128 return self._keys
8129 end
8130
8131 --- return the values in order.
8132 -- this is relatively expensive.
8133 -- @return List
8134 function OrderedMap:values ()
8135 return List(index_by(self,self._keys))
8136 end
8137
8138 --- sort the keys.
8139 -- @func cmp a comparison function as for @{table.sort}
8140 -- @return the map
8141 function OrderedMap:sort (cmp)
8142 tsort(self._keys,cmp)
8143 return self
8144 end
8145
8146 --- iterate over key-value pairs in order.
8147 function OrderedMap:iter ()
8148 local i = 0
8149 local keys = self._keys
8150 local idx
8151 return function()
8152 i = i + 1
8153 if i > #keys then return nil end
8154 idx = keys[i]
8155 return idx,self[idx]
8156 end
8157 end
8158
8159 --- iterate over an ordered map (5.2).
8160 -- @within metamethods
8161 -- @function OrderedMap:__pairs
8162 OrderedMap.__pairs = OrderedMap.iter
8163
8164 --- string representation of an ordered map.
8165 -- @within metamethods
8166 function OrderedMap:__tostring ()
8167 local res = {}
8168 for i,v in ipairs(self._keys) do
8169 local val = self[v]
8170 local vs = tostring(val)
8171 if type(val) ~= 'number' then
8172 vs = '"'..vs..'"'
8173 end
8174 res[i] = tostring(v)..'='..vs
8175 end
8176 return '{'..concat(res,',')..'}'
8177 end
8178
8179 return OrderedMap
8180
8181
8182
8183
8184 end,
8185
8186 ["pl.path"] = function()
8187 --------------------
8188 -- Module: 'pl.path'
8189 --------------------
8190 --- Path manipulation and file queries.
8191 --
8192 -- This is modelled after Python's os.path library (10.1); see @{04-paths.md|the Guide}.
8193 --
8194 -- NOTE: the functions assume the paths being dealt with to originate
8195 -- from the OS the application is running on. Windows drive letters are not
8196 -- to be used when running on a Unix system for example. The one exception
8197 -- is Windows paths to allow both forward and backward slashes (since Lua
8198 -- also accepts those)
8199 --
8200 -- Dependencies: `pl.utils`, `lfs`
8201 -- @module pl.path
8202
8203 -- imports and locals
8204 local _G = _G
8205 local sub = string.sub
8206 local getenv = os.getenv
8207 local tmpnam = os.tmpname
8208 local package = package
8209 local append, concat, remove = table.insert, table.concat, table.remove
8210 local utils = require 'pl.utils'
8211 local assert_string,raise = utils.assert_string,utils.raise
8212
8213 local res,lfs = _G.pcall(_G.require,'lfs')
8214 if not res then
8215 error("pl.path requires LuaFileSystem")
8216 end
8217
8218 local attrib = lfs.attributes
8219 local currentdir = lfs.currentdir
8220 local link_attrib = lfs.symlinkattributes
8221
8222 local path = {}
8223
8224 local function err_func(name, param, err, code)
8225 local ret = ("%s failed"):format(tostring(name))
8226 if param ~= nil then
8227 ret = ret .. (" for '%s'"):format(tostring(param))
8228 end
8229 ret = ret .. (": %s"):format(tostring(err))
8230 if code ~= nil then
8231 ret = ret .. (" (code %s)"):format(tostring(code))
8232 end
8233 return ret
8234 end
8235
8236 --- Lua iterator over the entries of a given directory.
8237 -- Implicit link to [`luafilesystem.dir`](https://lunarmodules.github.io/luafilesystem/manual.html#dir)
8238 -- @function dir
8239 path.dir = lfs.dir
8240
8241 --- Creates a directory.
8242 -- Implicit link to [`luafilesystem.mkdir`](https://lunarmodules.github.io/luafilesystem/manual.html#mkdir)
8243 -- @function mkdir
8244 path.mkdir = function(d)
8245 local ok, err, code = lfs.mkdir(d)
8246 if not ok then
8247 return ok, err_func("mkdir", d, err, code), code
8248 end
8249 return ok, err, code
8250 end
8251
8252 --- Removes a directory.
8253 -- Implicit link to [`luafilesystem.rmdir`](https://lunarmodules.github.io/luafilesystem/manual.html#rmdir)
8254 -- @function rmdir
8255 path.rmdir = function(d)
8256 local ok, err, code = lfs.rmdir(d)
8257 if not ok then
8258 return ok, err_func("rmdir", d, err, code), code
8259 end
8260 return ok, err, code
8261 end
8262
8263 --- Gets attributes.
8264 -- Implicit link to [`luafilesystem.attributes`](https://lunarmodules.github.io/luafilesystem/manual.html#attributes)
8265 -- @function attrib
8266 path.attrib = function(d, r)
8267 local ok, err, code = attrib(d, r)
8268 if not ok then
8269 return ok, err_func("attrib", d, err, code), code
8270 end
8271 return ok, err, code
8272 end
8273
8274 --- Get the working directory.
8275 -- Implicit link to [`luafilesystem.currentdir`](https://lunarmodules.github.io/luafilesystem/manual.html#currentdir)
8276 -- @function currentdir
8277 path.currentdir = function()
8278 local ok, err, code = currentdir()
8279 if not ok then
8280 return ok, err_func("currentdir", nil, err, code), code
8281 end
8282 return ok, err, code
8283 end
8284
8285 --- Gets symlink attributes.
8286 -- Implicit link to [`luafilesystem.symlinkattributes`](https://lunarmodules.github.io/luafilesystem/manual.html#symlinkattributes)
8287 -- @function link_attrib
8288 path.link_attrib = function(d, r)
8289 local ok, err, code = link_attrib(d, r)
8290 if not ok then
8291 return ok, err_func("link_attrib", d, err, code), code
8292 end
8293 return ok, err, code
8294 end
8295
8296 --- Changes the working directory.
8297 -- On Windows, if a drive is specified, it also changes the current drive. If
8298 -- only specifying the drive, it will only switch drive, but not modify the path.
8299 -- Implicit link to [`luafilesystem.chdir`](https://lunarmodules.github.io/luafilesystem/manual.html#chdir)
8300 -- @function chdir
8301 path.chdir = function(d)
8302 local ok, err, code = lfs.chdir(d)
8303 if not ok then
8304 return ok, err_func("chdir", d, err, code), code
8305 end
8306 return ok, err, code
8307 end
8308
8309 --- is this a directory?
8310 -- @string P A file path
8311 function path.isdir(P)
8312 assert_string(1,P)
8313 return attrib(P,'mode') == 'directory'
8314 end
8315
8316 --- is this a file?
8317 -- @string P A file path
8318 function path.isfile(P)
8319 assert_string(1,P)
8320 return attrib(P,'mode') == 'file'
8321 end
8322
8323 -- is this a symbolic link?
8324 -- @string P A file path
8325 function path.islink(P)
8326 assert_string(1,P)
8327 if link_attrib then
8328 return link_attrib(P,'mode')=='link'
8329 else
8330 return false
8331 end
8332 end
8333
8334 --- return size of a file.
8335 -- @string P A file path
8336 function path.getsize(P)
8337 assert_string(1,P)
8338 return attrib(P,'size')
8339 end
8340
8341 --- does a path exist?
8342 -- @string P A file path
8343 -- @return the file path if it exists (either as file, directory, socket, etc), false otherwise
8344 function path.exists(P)
8345 assert_string(1,P)
8346 return attrib(P,'mode') ~= nil and P
8347 end
8348
8349 --- Return the time of last access as the number of seconds since the epoch.
8350 -- @string P A file path
8351 function path.getatime(P)
8352 assert_string(1,P)
8353 return attrib(P,'access')
8354 end
8355
8356 --- Return the time of last modification as the number of seconds since the epoch.
8357 -- @string P A file path
8358 function path.getmtime(P)
8359 assert_string(1,P)
8360 return attrib(P,'modification')
8361 end
8362
8363 ---Return the system's ctime as the number of seconds since the epoch.
8364 -- @string P A file path
8365 function path.getctime(P)
8366 assert_string(1,P)
8367 return path.attrib(P,'change')
8368 end
8369
8370
8371 local function at(s,i)
8372 return sub(s,i,i)
8373 end
8374
8375 path.is_windows = utils.is_windows
8376
8377 local sep, other_sep, seps
8378 -- constant sep is the directory separator for this platform.
8379 -- constant dirsep is the separator in the PATH environment variable
8380 if path.is_windows then
8381 path.sep = '\\'; other_sep = '/'
8382 path.dirsep = ';'
8383 seps = { ['/'] = true, ['\\'] = true }
8384 else
8385 path.sep = '/'
8386 path.dirsep = ':'
8387 seps = { ['/'] = true }
8388 end
8389 sep = path.sep
8390
8391 --- are we running Windows?
8392 -- @class field
8393 -- @name path.is_windows
8394
8395 --- path separator for this platform.
8396 -- @class field
8397 -- @name path.sep
8398
8399 --- separator for PATH for this platform
8400 -- @class field
8401 -- @name path.dirsep
8402
8403 --- given a path, return the directory part and a file part.
8404 -- if there's no directory part, the first value will be empty
8405 -- @string P A file path
8406 -- @return directory part
8407 -- @return file part
8408 -- @usage
8409 -- local dir, file = path.splitpath("some/dir/myfile.txt")
8410 -- assert(dir == "some/dir")
8411 -- assert(file == "myfile.txt")
8412 --
8413 -- local dir, file = path.splitpath("some/dir/")
8414 -- assert(dir == "some/dir")
8415 -- assert(file == "")
8416 --
8417 -- local dir, file = path.splitpath("some_dir")
8418 -- assert(dir == "")
8419 -- assert(file == "some_dir")
8420 function path.splitpath(P)
8421 assert_string(1,P)
8422 local i = #P
8423 local ch = at(P,i)
8424 while i > 0 and ch ~= sep and ch ~= other_sep do
8425 i = i - 1
8426 ch = at(P,i)
8427 end
8428 if i == 0 then
8429 return '',P
8430 else
8431 return sub(P,1,i-1), sub(P,i+1)
8432 end
8433 end
8434
8435 --- return an absolute path.
8436 -- @string P A file path
8437 -- @string[opt] pwd optional start path to use (default is current dir)
8438 function path.abspath(P,pwd)
8439 assert_string(1,P)
8440 local use_pwd = pwd ~= nil
8441 if use_pwd then assert_string(2,pwd) end
8442 if not use_pwd and not currentdir() then return P end
8443 P = P:gsub('[\\/]$','')
8444 pwd = pwd or currentdir()
8445 if not path.isabs(P) then
8446 P = path.join(pwd,P)
8447 elseif path.is_windows and not use_pwd and at(P,2) ~= ':' and at(P,2) ~= '\\' then
8448 P = pwd:sub(1,2)..P -- attach current drive to path like '\\fred.txt'
8449 end
8450 return path.normpath(P)
8451 end
8452
8453 --- given a path, return the root part and the extension part.
8454 -- if there's no extension part, the second value will be empty
8455 -- @string P A file path
8456 -- @treturn string root part (everything upto the "."", maybe empty)
8457 -- @treturn string extension part (including the ".", maybe empty)
8458 -- @usage
8459 -- local file_path, ext = path.splitext("/bonzo/dog_stuff/cat.txt")
8460 -- assert(file_path == "/bonzo/dog_stuff/cat")
8461 -- assert(ext == ".txt")
8462 --
8463 -- local file_path, ext = path.splitext("")
8464 -- assert(file_path == "")
8465 -- assert(ext == "")
8466 function path.splitext(P)
8467 assert_string(1,P)
8468 local i = #P
8469 local ch = at(P,i)
8470 while i > 0 and ch ~= '.' do
8471 if seps[ch] then
8472 return P,''
8473 end
8474 i = i - 1
8475 ch = at(P,i)
8476 end
8477 if i == 0 then
8478 return P,''
8479 else
8480 return sub(P,1,i-1),sub(P,i)
8481 end
8482 end
8483
8484 --- return the directory part of a path
8485 -- @string P A file path
8486 -- @treturn string everything before the last dir-separator
8487 -- @see splitpath
8488 -- @usage
8489 -- path.dirname("/some/path/file.txt") -- "/some/path"
8490 -- path.dirname("file.txt") -- "" (empty string)
8491 function path.dirname(P)
8492 assert_string(1,P)
8493 local p1 = path.splitpath(P)
8494 return p1
8495 end
8496
8497 --- return the file part of a path
8498 -- @string P A file path
8499 -- @treturn string
8500 -- @see splitpath
8501 -- @usage
8502 -- path.basename("/some/path/file.txt") -- "file.txt"
8503 -- path.basename("/some/path/file/") -- "" (empty string)
8504 function path.basename(P)
8505 assert_string(1,P)
8506 local _,p2 = path.splitpath(P)
8507 return p2
8508 end
8509
8510 --- get the extension part of a path.
8511 -- @string P A file path
8512 -- @treturn string
8513 -- @see splitext
8514 -- @usage
8515 -- path.extension("/some/path/file.txt") -- ".txt"
8516 -- path.extension("/some/path/file_txt") -- "" (empty string)
8517 function path.extension(P)
8518 assert_string(1,P)
8519 local _,p2 = path.splitext(P)
8520 return p2
8521 end
8522
8523 --- is this an absolute path?
8524 -- @string P A file path
8525 -- @usage
8526 -- path.isabs("hello/path") -- false
8527 -- path.isabs("/hello/path") -- true
8528 -- -- Windows;
8529 -- path.isabs("hello\path") -- false
8530 -- path.isabs("\hello\path") -- true
8531 -- path.isabs("C:\hello\path") -- true
8532 -- path.isabs("C:hello\path") -- false
8533 function path.isabs(P)
8534 assert_string(1,P)
8535 if path.is_windows and at(P,2) == ":" then
8536 return seps[at(P,3)] ~= nil
8537 end
8538 return seps[at(P,1)] ~= nil
8539 end
8540
8541 --- return the path resulting from combining the individual paths.
8542 -- if the second (or later) path is absolute, we return the last absolute path (joined with any non-absolute paths following).
8543 -- empty elements (except the last) will be ignored.
8544 -- @string p1 A file path
8545 -- @string p2 A file path
8546 -- @string ... more file paths
8547 -- @treturn string the combined path
8548 -- @usage
8549 -- path.join("/first","second","third") -- "/first/second/third"
8550 -- path.join("first","second/third") -- "first/second/third"
8551 -- path.join("/first","/second","third") -- "/second/third"
8552 function path.join(p1,p2,...)
8553 assert_string(1,p1)
8554 assert_string(2,p2)
8555 if select('#',...) > 0 then
8556 local p = path.join(p1,p2)
8557 local args = {...}
8558 for i = 1,#args do
8559 assert_string(i,args[i])
8560 p = path.join(p,args[i])
8561 end
8562 return p
8563 end
8564 if path.isabs(p2) then return p2 end
8565 local endc = at(p1,#p1)
8566 if endc ~= path.sep and endc ~= other_sep and endc ~= "" then
8567 p1 = p1..path.sep
8568 end
8569 return p1..p2
8570 end
8571
8572 --- normalize the case of a pathname. On Unix, this returns the path unchanged,
8573 -- for Windows it converts;
8574 --
8575 -- * the path to lowercase
8576 -- * forward slashes to backward slashes
8577 -- @string P A file path
8578 -- @usage path.normcase("/Some/Path/File.txt")
8579 -- -- Windows: "\some\path\file.txt"
8580 -- -- Others : "/Some/Path/File.txt"
8581 function path.normcase(P)
8582 assert_string(1,P)
8583 if path.is_windows then
8584 return P:gsub('/','\\'):lower()
8585 else
8586 return P
8587 end
8588 end
8589
8590 --- normalize a path name.
8591 -- `A//B`, `A/./B`, and `A/foo/../B` all become `A/B`.
8592 --
8593 -- An empty path results in '.'.
8594 -- @string P a file path
8595 function path.normpath(P)
8596 assert_string(1,P)
8597 -- Split path into anchor and relative path.
8598 local anchor = ''
8599 if path.is_windows then
8600 if P:match '^\\\\' then -- UNC
8601 anchor = '\\\\'
8602 P = P:sub(3)
8603 elseif seps[at(P, 1)] then
8604 anchor = '\\'
8605 P = P:sub(2)
8606 elseif at(P, 2) == ':' then
8607 anchor = P:sub(1, 2)
8608 P = P:sub(3)
8609 if seps[at(P, 1)] then
8610 anchor = anchor..'\\'
8611 P = P:sub(2)
8612 end
8613 end
8614 P = P:gsub('/','\\')
8615 else
8616 -- According to POSIX, in path start '//' and '/' are distinct,
8617 -- but '///+' is equivalent to '/'.
8618 if P:match '^//' and at(P, 3) ~= '/' then
8619 anchor = '//'
8620 P = P:sub(3)
8621 elseif at(P, 1) == '/' then
8622 anchor = '/'
8623 P = P:match '^/*(.*)$'
8624 end
8625 end
8626 local parts = {}
8627 for part in P:gmatch('[^'..sep..']+') do
8628 if part == '..' then
8629 if #parts ~= 0 and parts[#parts] ~= '..' then
8630 remove(parts)
8631 else
8632 append(parts, part)
8633 end
8634 elseif part ~= '.' then
8635 append(parts, part)
8636 end
8637 end
8638 P = anchor..concat(parts, sep)
8639 if P == '' then P = '.' end
8640 return P
8641 end
8642
8643 --- relative path from current directory or optional start point
8644 -- @string P a path
8645 -- @string[opt] start optional start point (default current directory)
8646 function path.relpath (P,start)
8647 assert_string(1,P)
8648 if start then assert_string(2,start) end
8649 local split,min,append = utils.split, math.min, table.insert
8650 P = path.abspath(P,start)
8651 start = start or currentdir()
8652 local compare
8653 if path.is_windows then
8654 P = P:gsub("/","\\")
8655 start = start:gsub("/","\\")
8656 compare = function(v) return v:lower() end
8657 else
8658 compare = function(v) return v end
8659 end
8660 local startl, Pl = split(start,sep), split(P,sep)
8661 local n = min(#startl,#Pl)
8662 if path.is_windows and n > 0 and at(Pl[1],2) == ':' and Pl[1] ~= startl[1] then
8663 return P
8664 end
8665 local k = n+1 -- default value if this loop doesn't bail out!
8666 for i = 1,n do
8667 if compare(startl[i]) ~= compare(Pl[i]) then
8668 k = i
8669 break
8670 end
8671 end
8672 local rell = {}
8673 for i = 1, #startl-k+1 do rell[i] = '..' end
8674 if k <= #Pl then
8675 for i = k,#Pl do append(rell,Pl[i]) end
8676 end
8677 return table.concat(rell,sep)
8678 end
8679
8680
8681 --- Replace a starting '~' with the user's home directory.
8682 -- In windows, if HOME isn't set, then USERPROFILE is used in preference to
8683 -- HOMEDRIVE HOMEPATH. This is guaranteed to be writeable on all versions of Windows.
8684 -- @string P A file path
8685 -- @treturn[1] string The file path with the `~` prefix substituted, or the input path if it had no prefix.
8686 -- @treturn[2] nil
8687 -- @treturn[2] string Error message if the environment variables were unavailable.
8688 function path.expanduser(P)
8689 assert_string(1,P)
8690 if P:sub(1,1) ~= '~' then
8691 return P
8692 end
8693
8694 local home = getenv('HOME')
8695 if (not home) and (not path.is_windows) then
8696 -- no more options to try on Nix
8697 return nil, "failed to expand '~' (HOME not set)"
8698 end
8699
8700 if (not home) then
8701 -- try alternatives on Windows
8702 home = getenv 'USERPROFILE'
8703 if not home then
8704 local hd = getenv 'HOMEDRIVE'
8705 local hp = getenv 'HOMEPATH'
8706 if not (hd and hp) then
8707 return nil, "failed to expand '~' (HOME, USERPROFILE, and HOMEDRIVE and/or HOMEPATH not set)"
8708 end
8709 home = hd..hp
8710 end
8711 end
8712
8713 return home..sub(P,2)
8714 end
8715
8716
8717 ---Return a suitable full path to a new temporary file name.
8718 -- unlike os.tmpname(), it always gives you a writeable path (uses TEMP environment variable on Windows)
8719 function path.tmpname ()
8720 local res = tmpnam()
8721 -- On Windows if Lua is compiled using MSVC14 os.tmpname
8722 -- already returns an absolute path within TEMP env variable directory,
8723 -- no need to prepend it.
8724 if path.is_windows and not res:find(':') then
8725 res = getenv('TEMP')..res
8726 end
8727 return res
8728 end
8729
8730 --- return the largest common prefix path of two paths.
8731 -- @string path1 a file path
8732 -- @string path2 a file path
8733 -- @return the common prefix (Windows: separators will be normalized, casing will be original)
8734 function path.common_prefix (path1,path2)
8735 assert_string(1,path1)
8736 assert_string(2,path2)
8737 -- get them in order!
8738 if #path1 > #path2 then path2,path1 = path1,path2 end
8739 local compare
8740 if path.is_windows then
8741 path1 = path1:gsub("/", "\\")
8742 path2 = path2:gsub("/", "\\")
8743 compare = function(v) return v:lower() end
8744 else
8745 compare = function(v) return v end
8746 end
8747 for i = 1,#path1 do
8748 if compare(at(path1,i)) ~= compare(at(path2,i)) then
8749 local cp = path1:sub(1,i-1)
8750 if at(path1,i-1) ~= sep then
8751 cp = path.dirname(cp)
8752 end
8753 return cp
8754 end
8755 end
8756 if at(path2,#path1+1) ~= sep then path1 = path.dirname(path1) end
8757 return path1
8758 --return ''
8759 end
8760
8761 --- return the full path where a particular Lua module would be found.
8762 -- Both package.path and package.cpath is searched, so the result may
8763 -- either be a Lua file or a shared library.
8764 -- @string mod name of the module
8765 -- @return on success: path of module, lua or binary
8766 -- @return on error: nil, error string listing paths tried
8767 function path.package_path(mod)
8768 assert_string(1,mod)
8769 local res, err1, err2
8770 res, err1 = package.searchpath(mod,package.path)
8771 if res then return res,true end
8772 res, err2 = package.searchpath(mod,package.cpath)
8773 if res then return res,false end
8774 return raise ('cannot find module on path\n' .. err1 .. "\n" .. err2)
8775 end
8776
8777
8778 ---- finis -----
8779 return path
8780
8781 end,
8782
8783 ["pl.permute"] = function()
8784 --------------------
8785 -- Module: 'pl.permute'
8786 --------------------
8787 --- Permutation operations.
8788 --
8789 -- Dependencies: `pl.utils`, `pl.tablex`
8790 -- @module pl.permute
8791 local tablex = require 'pl.tablex'
8792 local utils = require 'pl.utils'
8793 local copy = tablex.deepcopy
8794 local append = table.insert
8795 local assert_arg = utils.assert_arg
8796
8797
8798 local permute = {}
8799
8800
8801 --- an iterator over all order-permutations of the elements of a list.
8802 -- Please note that the same list is returned each time, so do not keep references!
8803 -- @param a list-like table
8804 -- @return an iterator which provides the next permutation as a list
8805 function permute.order_iter(a)
8806 assert_arg(1,a,'table')
8807
8808 local t = #a
8809 local stack = { 1 }
8810 local function iter()
8811 local h = #stack
8812 local n = t - h + 1
8813
8814 local i = stack[h]
8815 if i > t then
8816 return
8817 end
8818
8819 if n == 0 then
8820 table.remove(stack)
8821 h = h - 1
8822
8823 stack[h] = stack[h] + 1
8824 return a
8825
8826 elseif i <= n then
8827
8828 -- put i-th element as the last one
8829 a[n], a[i] = a[i], a[n]
8830
8831 -- generate all permutations of the other elements
8832 table.insert(stack, 1)
8833
8834 else
8835
8836 table.remove(stack)
8837 h = h - 1
8838
8839 n = n + 1
8840 i = stack[h]
8841
8842 -- restore i-th element
8843 a[n], a[i] = a[i], a[n]
8844
8845 stack[h] = stack[h] + 1
8846 end
8847 return iter() -- tail-call
8848 end
8849
8850 return iter
8851 end
8852
8853
8854 --- construct a table containing all the order-permutations of a list.
8855 -- @param a list-like table
8856 -- @return a table of tables
8857 -- @usage permute.order_table {1,2,3} --> {{2,3,1},{3,2,1},{3,1,2},{1,3,2},{2,1,3},{1,2,3}}
8858 function permute.order_table (a)
8859 assert_arg(1,a,'table')
8860 local res = {}
8861 for t in permute.iter(a) do
8862 append(res,copy(t))
8863 end
8864 return res
8865 end
8866
8867
8868
8869 --- an iterator over all permutations of the elements of the given lists.
8870 -- @param ... list-like tables, they are nil-safe if a length-field `n` is provided (see `utils.pack`)
8871 -- @return an iterator which provides the next permutation as return values in the same order as the provided lists, preceded by an index
8872 -- @usage
8873 -- local strs = utils.pack("one", nil, "three") -- adds an 'n' field for nil-safety
8874 -- local bools = utils.pack(true, false)
8875 -- local iter = permute.list_iter(strs, bools)
8876 --
8877 -- print(iter()) --> 1, one, true
8878 -- print(iter()) --> 2, nil, true
8879 -- print(iter()) --> 3, three, true
8880 -- print(iter()) --> 4, one, false
8881 -- print(iter()) --> 5, nil, false
8882 -- print(iter()) --> 6, three, false
8883 function permute.list_iter(...)
8884 local elements = {...}
8885 local pointers = {}
8886 local sizes = {}
8887 local size = #elements
8888 for i, list in ipairs(elements) do
8889 assert_arg(i,list,'table')
8890 pointers[i] = 1
8891 sizes[i] = list.n or #list
8892 end
8893 local count = 0
8894
8895 return function()
8896 if pointers[size] > sizes[size] then return end -- we're done
8897 count = count + 1
8898 local r = { n = #elements }
8899 local cascade_up = true
8900 for i = 1, size do
8901 r[i] = elements[i][pointers[i]]
8902 if cascade_up then
8903 pointers[i] = pointers[i] + 1
8904 if pointers[i] <= sizes[i] then
8905 -- this list is not done yet, stop cascade
8906 cascade_up = false
8907 else
8908 -- this list is done
8909 if i ~= size then
8910 -- reset pointer
8911 pointers[i] = 1
8912 end
8913 end
8914 end
8915 end
8916 return count, utils.unpack(r)
8917 end
8918 end
8919
8920
8921
8922 --- construct a table containing all the permutations of a set of lists.
8923 -- @param ... list-like tables, they are nil-safe if a length-field `n` is provided
8924 -- @return a list of lists, the sub-lists have an 'n' field for nil-safety
8925 -- @usage
8926 -- local strs = utils.pack("one", nil, "three") -- adds an 'n' field for nil-safety
8927 -- local bools = utils.pack(true, false)
8928 -- local results = permute.list_table(strs, bools)
8929 -- -- results = {
8930 -- -- { "one, true, n = 2 }
8931 -- -- { nil, true, n = 2 },
8932 -- -- { "three, true, n = 2 },
8933 -- -- { "one, false, n = 2 },
8934 -- -- { nil, false, n = 2 },
8935 -- -- { "three", false, n = 2 },
8936 -- -- }
8937 function permute.list_table(...)
8938 local iter = permute.list_iter(...)
8939 local results = {}
8940 local i = 1
8941 while true do
8942 local values = utils.pack(iter())
8943 if values[1] == nil then return results end
8944 for i = 1, values.n do values[i] = values[i+1] end
8945 values.n = values.n - 1
8946 results[i] = values
8947 i = i + 1
8948 end
8949 end
8950
8951
8952 -- backward compat, to be deprecated
8953
8954 --- deprecated.
8955 -- @param ...
8956 -- @see permute.order_iter
8957 function permute.iter(...)
8958 utils.raise_deprecation {
8959 source = "Penlight " .. utils._VERSION,
8960 message = "function 'iter' was renamed to 'order_iter'",
8961 version_removed = "2.0.0",
8962 deprecated_after = "1.9.2",
8963 }
8964
8965 return permute.order_iter(...)
8966 end
8967
8968 --- deprecated.
8969 -- @param ...
8970 -- @see permute.order_iter
8971 function permute.table(...)
8972 utils.raise_deprecation {
8973 source = "Penlight " .. utils._VERSION,
8974 message = "function 'table' was renamed to 'order_table'",
8975 version_removed = "2.0.0",
8976 deprecated_after = "1.9.2",
8977 }
8978
8979 return permute.order_table(...)
8980 end
8981
8982 return permute
8983
8984 end,
8985
8986 ["pl.pretty"] = function()
8987 --------------------
8988 -- Module: 'pl.pretty'
8989 --------------------
8990 --- Pretty-printing Lua tables.
8991 -- Also provides a sandboxed Lua table reader and
8992 -- a function to present large numbers in human-friendly format.
8993 --
8994 -- Dependencies: `pl.utils`, `pl.lexer`, `pl.stringx`, `debug`
8995 -- @module pl.pretty
8996
8997 local append = table.insert
8998 local concat = table.concat
8999 local mfloor, mhuge = math.floor, math.huge
9000 local mtype = math.type
9001 local utils = require 'pl.utils'
9002 local lexer = require 'pl.lexer'
9003 local debug = require 'debug'
9004 local quote_string = require'pl.stringx'.quote_string
9005 local assert_arg = utils.assert_arg
9006
9007 local original_tostring = tostring
9008
9009 -- Calculate min and max integer supported by lua_Number
9010 -- Assumptions:
9011 -- 1. max_int = 2 ^ n - 1
9012 -- 2. min_int = -max_int
9013 -- 3. if n > max_int versions with integer support will have
9014 -- integer overflow and versions without integers will lose least significant bit
9015 -- Note: if lua_Integer is smaller than lua_Number mantissa string.format('%d')
9016 -- can throw runtime error
9017 local max_int, min_int
9018 local next_cand = 1
9019 while next_cand > 0 and next_cand % 2 == 1 do
9020 max_int = next_cand
9021 min_int = -next_cand
9022 next_cand = next_cand * 2 + 1
9023 end
9024
9025 local function is_integer(value)
9026 if _VERSION == "Lua 5.3" or _VERSION == "Lua 5.4" then
9027 return mtype(value) == "integer"
9028 end
9029 if value < min_int or value > max_int then
9030 return false
9031 end
9032 return math.floor(value) == value
9033 end
9034
9035 local function is_float(value)
9036 if _VERSION == "Lua 5.3" or _VERSION == "Lua 5.4" then
9037 return mtype(value) == "float"
9038 end
9039 if value < min_int or value > max_int then
9040 return true
9041 end
9042 return mfloor(value) == value
9043 end
9044
9045 -- Patch tostring to format numbers with better precision
9046 -- and to produce cross-platform results for
9047 -- infinite values and NaN.
9048 local function tostring(value)
9049 if type(value) ~= "number" then
9050 return original_tostring(value)
9051 elseif value ~= value then
9052 return "NaN"
9053 elseif value == mhuge then
9054 return "Inf"
9055 elseif value == -mhuge then
9056 return "-Inf"
9057 elseif is_integer(value) then
9058 return ("%d"):format(value)
9059 else
9060 local res = ("%.14g"):format(value)
9061 if is_float(value) and not res:find("%.") then
9062 -- Number is internally a float but looks like an integer.
9063 -- Insert ".0" after first run of digits.
9064 res = res:gsub("%d+", "%0.0", 1)
9065 end
9066 return res
9067 end
9068 end
9069
9070 local pretty = {}
9071
9072 local function save_global_env()
9073 local env = {}
9074 env.hook, env.mask, env.count = debug.gethook()
9075
9076 -- env.hook is "external hook" if is a C hook function
9077 if env.hook~="external hook" then
9078 debug.sethook()
9079 end
9080
9081 env.string_mt = getmetatable("")
9082 debug.setmetatable("", nil)
9083 return env
9084 end
9085
9086 local function restore_global_env(env)
9087 if env then
9088 debug.setmetatable("", env.string_mt)
9089 if env.hook~="external hook" then
9090 debug.sethook(env.hook, env.mask, env.count)
9091 end
9092 end
9093 end
9094
9095 --- Read a string representation of a Lua table.
9096 -- This function loads and runs the string as Lua code, but bails out
9097 -- if it contains a function definition.
9098 -- Loaded string is executed in an empty environment.
9099 -- @string s string to read in `{...}` format, possibly with some whitespace
9100 -- before or after the curly braces. A single line comment may be present
9101 -- at the beginning.
9102 -- @return a table in case of success.
9103 -- If loading the string failed, return `nil` and error message.
9104 -- If executing loaded string failed, return `nil` and the error it raised.
9105 function pretty.read(s)
9106 assert_arg(1,s,'string')
9107 if s:find '^%s*%-%-' then -- may start with a comment..
9108 s = s:gsub('%-%-.-\n','')
9109 end
9110 if not s:find '^%s*{' then return nil,"not a Lua table" end
9111 if s:find '[^\'"%w_]function[^\'"%w_]' then
9112 local tok = lexer.lua(s)
9113 for t,v in tok do
9114 if t == 'keyword' and v == 'function' then
9115 return nil,"cannot have functions in table definition"
9116 end
9117 end
9118 end
9119 s = 'return '..s
9120 local chunk,err = utils.load(s,'tbl','t',{})
9121 if not chunk then return nil,err end
9122 local global_env = save_global_env()
9123 local ok,ret = pcall(chunk)
9124 restore_global_env(global_env)
9125 if ok then return ret
9126 else
9127 return nil,ret
9128 end
9129 end
9130
9131 --- Read a Lua chunk.
9132 -- @string s Lua code.
9133 -- @tab[opt] env environment used to run the code, empty by default.
9134 -- @bool[opt] paranoid abort loading if any looping constructs a found in the code
9135 -- and disable string methods.
9136 -- @return the environment in case of success or `nil` and syntax or runtime error
9137 -- if something went wrong.
9138 function pretty.load (s, env, paranoid)
9139 env = env or {}
9140 if paranoid then
9141 local tok = lexer.lua(s)
9142 for t,v in tok do
9143 if t == 'keyword'
9144 and (v == 'for' or v == 'repeat' or v == 'function' or v == 'goto')
9145 then
9146 return nil,"looping not allowed"
9147 end
9148 end
9149 end
9150 local chunk,err = utils.load(s,'tbl','t',env)
9151 if not chunk then return nil,err end
9152 local global_env = paranoid and save_global_env()
9153 local ok,err = pcall(chunk)
9154 restore_global_env(global_env)
9155 if not ok then return nil,err end
9156 return env
9157 end
9158
9159 local function quote_if_necessary (v)
9160 if not v then return ''
9161 else
9162 --AAS
9163 if v:find ' ' then v = quote_string(v) end
9164 end
9165 return v
9166 end
9167
9168 local keywords
9169
9170 local function is_identifier (s)
9171 return type(s) == 'string' and s:find('^[%a_][%w_]*$') and not keywords[s]
9172 end
9173
9174 local function quote (s)
9175 if type(s) == 'table' then
9176 return pretty.write(s,'')
9177 else
9178 --AAS
9179 return quote_string(s)-- ('%q'):format(tostring(s))
9180 end
9181 end
9182
9183 local function index (numkey,key)
9184 --AAS
9185 if not numkey then
9186 key = quote(key)
9187 key = key:find("^%[") and (" " .. key .. " ") or key
9188 end
9189 return '['..key..']'
9190 end
9191
9192
9193 --- Create a string representation of a Lua table.
9194 -- This function never fails, but may complain by returning an
9195 -- extra value. Normally puts out one item per line, using
9196 -- the provided indent; set the second parameter to an empty string
9197 -- if you want output on one line.
9198 --
9199 -- *NOTE:* this is NOT a serialization function, not a full blown
9200 -- debug function. Checkout out respectively the
9201 -- [serpent](https://github.com/pkulchenko/serpent)
9202 -- or [inspect](https://github.com/kikito/inspect.lua)
9203 -- Lua modules for that if you need them.
9204 -- @tab tbl Table to serialize to a string.
9205 -- @string[opt] space The indent to use.
9206 -- Defaults to two spaces; pass an empty string for no indentation.
9207 -- @bool[opt] not_clever Pass `true` for plain output, e.g `{['key']=1}`.
9208 -- Defaults to `false`.
9209 -- @return a string
9210 -- @return an optional error message
9211 function pretty.write (tbl,space,not_clever)
9212 if type(tbl) ~= 'table' then
9213 local res = tostring(tbl)
9214 if type(tbl) == 'string' then return quote(tbl) end
9215 return res, 'not a table'
9216 end
9217 if not keywords then
9218 keywords = lexer.get_keywords()
9219 end
9220 local set = ' = '
9221 if space == '' then set = '=' end
9222 space = space or ' '
9223 local lines = {}
9224 local line = ''
9225 local tables = {}
9226
9227
9228 local function put(s)
9229 if #s > 0 then
9230 line = line..s
9231 end
9232 end
9233
9234 local function putln (s)
9235 if #line > 0 then
9236 line = line..s
9237 append(lines,line)
9238 line = ''
9239 else
9240 append(lines,s)
9241 end
9242 end
9243
9244 local function eat_last_comma ()
9245 local n = #lines
9246 local lastch = lines[n]:sub(-1,-1)
9247 if lastch == ',' then
9248 lines[n] = lines[n]:sub(1,-2)
9249 end
9250 end
9251
9252
9253 -- safe versions for iterators since 5.3+ honors metamethods that can throw
9254 -- errors
9255 local ipairs = function(t)
9256 local i = 0
9257 local ok, v
9258 local getter = function() return t[i] end
9259 return function()
9260 i = i + 1
9261 ok, v = pcall(getter)
9262 if v == nil or not ok then return end
9263 return i, t[i]
9264 end
9265 end
9266 local pairs = function(t)
9267 local k, v, ok
9268 local getter = function() return next(t, k) end
9269 return function()
9270 ok, k, v = pcall(getter)
9271 if not ok then return end
9272 return k, v
9273 end
9274 end
9275
9276 local writeit
9277 writeit = function (t,oldindent,indent)
9278 local tp = type(t)
9279 if tp ~= 'string' and tp ~= 'table' then
9280 putln(quote_if_necessary(tostring(t))..',')
9281 elseif tp == 'string' then
9282 -- if t:find('\n') then
9283 -- putln('[[\n'..t..']],')
9284 -- else
9285 -- putln(quote(t)..',')
9286 -- end
9287 --AAS
9288 putln(quote_string(t) ..",")
9289 elseif tp == 'table' then
9290 if tables[t] then
9291 putln('<cycle>,')
9292 return
9293 end
9294 tables[t] = true
9295 local newindent = indent..space
9296 putln('{')
9297 local used = {}
9298 if not not_clever then
9299 for i,val in ipairs(t) do
9300 put(indent)
9301 writeit(val,indent,newindent)
9302 used[i] = true
9303 end
9304 end
9305 local ordered_keys = {}
9306 for k,v in pairs(t) do
9307 if type(k) ~= 'number' then
9308 ordered_keys[#ordered_keys + 1] = k
9309 end
9310 end
9311 table.sort(ordered_keys, function (a, b)
9312 if type(a) == type(b) then
9313 return tostring(a) < tostring(b)
9314 else
9315 return type(a) < type(b)
9316 end
9317 end)
9318 local function write_entry (key, val)
9319 local tkey = type(key)
9320 local numkey = tkey == 'number'
9321 if not_clever then
9322 key = tostring(key)
9323 put(indent..index(numkey,key)..set)
9324 writeit(val,indent,newindent)
9325 else
9326 if not numkey or not used[key] then -- non-array indices
9327 if tkey ~= 'string' then
9328 key = tostring(key)
9329 end
9330 if numkey or not is_identifier(key) then
9331 key = index(numkey,key)
9332 end
9333 put(indent..key..set)
9334 writeit(val,indent,newindent)
9335 end
9336 end
9337 end
9338 for i = 1, #ordered_keys do
9339 local key = ordered_keys[i]
9340 local val = t[key]
9341 write_entry(key, val)
9342 end
9343 for key,val in pairs(t) do
9344 if type(key) == 'number' then
9345 write_entry(key, val)
9346 end
9347 end
9348 tables[t] = nil
9349 eat_last_comma()
9350 putln(oldindent..'},')
9351 else
9352 putln(tostring(t)..',')
9353 end
9354 end
9355 writeit(tbl,'',space)
9356 eat_last_comma()
9357 return concat(lines,#space > 0 and '\n' or '')
9358 end
9359
9360 --- Dump a Lua table out to a file or stdout.
9361 -- @tab t The table to write to a file or stdout.
9362 -- @string[opt] filename File name to write too. Defaults to writing
9363 -- to stdout.
9364 function pretty.dump (t, filename)
9365 if not filename then
9366 print(pretty.write(t))
9367 return true
9368 else
9369 return utils.writefile(filename, pretty.write(t))
9370 end
9371 end
9372
9373 --- Dump a series of arguments to stdout for debug purposes.
9374 -- This function is attached to the module table `__call` method, to make it
9375 -- extra easy to access. So the full:
9376 --
9377 -- print(require("pl.pretty").write({...}))
9378 --
9379 -- Can be shortened to:
9380 --
9381 -- require"pl.pretty" (...)
9382 --
9383 -- Any `nil` entries will be printed as `"<nil>"` to make them explicit.
9384 -- @param ... the parameters to dump to stdout.
9385 -- @usage
9386 -- -- example debug output
9387 -- require"pl.pretty" ("hello", nil, "world", { bye = "world", true} )
9388 --
9389 -- -- output:
9390 -- {
9391 -- ["arg 1"] = "hello",
9392 -- ["arg 2"] = "<nil>",
9393 -- ["arg 3"] = "world",
9394 -- ["arg 4"] = {
9395 -- true,
9396 -- bye = "world"
9397 -- }
9398 -- }
9399 function pretty.debug(...)
9400 local n = select("#", ...)
9401 local t = { ... }
9402 for i = 1, n do
9403 local value = t[i]
9404 if value == nil then
9405 value = "<nil>"
9406 end
9407 t[i] = nil
9408 t["arg " .. i] = value
9409 end
9410
9411 print(pretty.write(t))
9412 return true
9413 end
9414
9415
9416 local memp,nump = {'B','KiB','MiB','GiB'},{'','K','M','B'}
9417
9418 local function comma (val)
9419 local thou = math.floor(val/1000)
9420 if thou > 0 then return comma(thou)..','.. tostring(val % 1000)
9421 else return tostring(val) end
9422 end
9423
9424 --- Format large numbers nicely for human consumption.
9425 -- @number num a number.
9426 -- @string[opt] kind one of `'M'` (memory in `KiB`, `MiB`, etc.),
9427 -- `'N'` (postfixes are `'K'`, `'M'` and `'B'`),
9428 -- or `'T'` (use commas as thousands separator), `'N'` by default.
9429 -- @int[opt] prec number of digits to use for `'M'` and `'N'`, `1` by default.
9430 function pretty.number (num,kind,prec)
9431 local fmt = '%.'..(prec or 1)..'f%s'
9432 if kind == 'T' then
9433 return comma(num)
9434 else
9435 local postfixes, fact
9436 if kind == 'M' then
9437 fact = 1024
9438 postfixes = memp
9439 else
9440 fact = 1000
9441 postfixes = nump
9442 end
9443 local div = fact
9444 local k = 1
9445 while num >= div and k <= #postfixes do
9446 div = div * fact
9447 k = k + 1
9448 end
9449 div = div / fact
9450 if k > #postfixes then k = k - 1; div = div/fact end
9451 if k > 1 then
9452 return fmt:format(num/div,postfixes[k] or 'duh')
9453 else
9454 return num..postfixes[1]
9455 end
9456 end
9457 end
9458
9459 return setmetatable(pretty, {
9460 __call = function(self, ...)
9461 return self.debug(...)
9462 end
9463 })
9464
9465 end,
9466
9467 ["pl.seq"] = function()
9468 --------------------
9469 -- Module: 'pl.seq'
9470 --------------------
9471 --- Manipulating iterators as sequences.
9472 -- See @{07-functional.md.Sequences|The Guide}
9473 --
9474 -- Dependencies: `pl.utils`, `pl.types`, `debug`
9475 -- @module pl.seq
9476
9477 local next,assert,pairs,tonumber,type,setmetatable = next,assert,pairs,tonumber,type,setmetatable
9478 local strfind,format = string.find,string.format
9479 local mrandom = math.random
9480 local tsort,tappend = table.sort,table.insert
9481 local io = io
9482 local utils = require 'pl.utils'
9483 local callable = require 'pl.types'.is_callable
9484 local function_arg = utils.function_arg
9485 local assert_arg = utils.assert_arg
9486 local debug = require 'debug'
9487
9488 local seq = {}
9489
9490 -- given a number, return a function(y) which returns true if y > x
9491 -- @param x a number
9492 function seq.greater_than(x)
9493 return function(v)
9494 return tonumber(v) > x
9495 end
9496 end
9497
9498 -- given a number, returns a function(y) which returns true if y < x
9499 -- @param x a number
9500 function seq.less_than(x)
9501 return function(v)
9502 return tonumber(v) < x
9503 end
9504 end
9505
9506 -- given any value, return a function(y) which returns true if y == x
9507 -- @param x a value
9508 function seq.equal_to(x)
9509 if type(x) == "number" then
9510 return function(v)
9511 return tonumber(v) == x
9512 end
9513 else
9514 return function(v)
9515 return v == x
9516 end
9517 end
9518 end
9519
9520 --- given a string, return a function(y) which matches y against the string.
9521 -- @param s a string
9522 function seq.matching(s)
9523 return function(v)
9524 return strfind(v,s)
9525 end
9526 end
9527
9528 local nexti
9529
9530 --- sequence adaptor for a table. Note that if any generic function is
9531 -- passed a table, it will automatically use seq.list()
9532 -- @param t a list-like table
9533 -- @usage sum(list(t)) is the sum of all elements of t
9534 -- @usage for x in list(t) do...end
9535 function seq.list(t)
9536 assert_arg(1,t,'table')
9537 if not nexti then
9538 nexti = ipairs{}
9539 end
9540 local key,value = 0
9541 return function()
9542 key,value = nexti(t,key)
9543 return value
9544 end
9545 end
9546
9547 --- return the keys of the table.
9548 -- @param t an arbitrary table
9549 -- @return iterator over keys
9550 function seq.keys(t)
9551 assert_arg(1,t,'table')
9552 local key
9553 return function()
9554 key = next(t,key)
9555 return key
9556 end
9557 end
9558
9559 local list = seq.list
9560 local function default_iter(iter)
9561 if type(iter) == 'table' then return list(iter)
9562 else return iter end
9563 end
9564
9565 seq.iter = default_iter
9566
9567 --- create an iterator over a numerical range. Like the standard Python function xrange.
9568 -- @param start a number
9569 -- @param finish a number greater than start
9570 function seq.range(start,finish)
9571 local i = start - 1
9572 return function()
9573 i = i + 1
9574 if i > finish then return nil
9575 else return i end
9576 end
9577 end
9578
9579 -- count the number of elements in the sequence which satisfy the predicate
9580 -- @param iter a sequence
9581 -- @param condn a predicate function (must return either true or false)
9582 -- @param optional argument to be passed to predicate as second argument.
9583 -- @return count
9584 function seq.count(iter,condn,arg)
9585 local i = 0
9586 seq.foreach(iter,function(val)
9587 if condn(val,arg) then i = i + 1 end
9588 end)
9589 return i
9590 end
9591
9592 --- return the minimum and the maximum value of the sequence.
9593 -- @param iter a sequence
9594 -- @return minimum value
9595 -- @return maximum value
9596 function seq.minmax(iter)
9597 local vmin,vmax = 1e70,-1e70
9598 for v in default_iter(iter) do
9599 v = tonumber(v)
9600 if v < vmin then vmin = v end
9601 if v > vmax then vmax = v end
9602 end
9603 return vmin,vmax
9604 end
9605
9606 --- return the sum and element count of the sequence.
9607 -- @param iter a sequence
9608 -- @param fn an optional function to apply to the values
9609 function seq.sum(iter,fn)
9610 local s = 0
9611 local i = 0
9612 for v in default_iter(iter) do
9613 if fn then v = fn(v) end
9614 s = s + v
9615 i = i + 1
9616 end
9617 return s,i
9618 end
9619
9620 --- create a table from the sequence. (This will make the result a List.)
9621 -- @param iter a sequence
9622 -- @return a List
9623 -- @usage copy(list(ls)) is equal to ls
9624 -- @usage copy(list {1,2,3}) == List{1,2,3}
9625 function seq.copy(iter)
9626 local res,k = {},1
9627 for v in default_iter(iter) do
9628 res[k] = v
9629 k = k + 1
9630 end
9631 setmetatable(res, require('pl.List'))
9632 return res
9633 end
9634
9635 --- create a table of pairs from the double-valued sequence.
9636 -- @param iter a double-valued sequence
9637 -- @param i1 used to capture extra iterator values
9638 -- @param i2 as with pairs & ipairs
9639 -- @usage copy2(ipairs{10,20,30}) == {{1,10},{2,20},{3,30}}
9640 -- @return a list-like table
9641 function seq.copy2 (iter,i1,i2)
9642 local res,k = {},1
9643 for v1,v2 in iter,i1,i2 do
9644 res[k] = {v1,v2}
9645 k = k + 1
9646 end
9647 return res
9648 end
9649
9650 --- create a table of 'tuples' from a multi-valued sequence.
9651 -- A generalization of copy2 above
9652 -- @param iter a multiple-valued sequence
9653 -- @return a list-like table
9654 function seq.copy_tuples (iter)
9655 iter = default_iter(iter)
9656 local res = {}
9657 local row = {iter()}
9658 while #row > 0 do
9659 tappend(res,row)
9660 row = {iter()}
9661 end
9662 return res
9663 end
9664
9665 --- return an iterator of random numbers.
9666 -- @param n the length of the sequence
9667 -- @param l same as the first optional argument to math.random
9668 -- @param u same as the second optional argument to math.random
9669 -- @return a sequence
9670 function seq.random(n,l,u)
9671 local rand
9672 assert(type(n) == 'number')
9673 if u then
9674 rand = function() return mrandom(l,u) end
9675 elseif l then
9676 rand = function() return mrandom(l) end
9677 else
9678 rand = mrandom
9679 end
9680
9681 return function()
9682 if n == 0 then return nil
9683 else
9684 n = n - 1
9685 return rand()
9686 end
9687 end
9688 end
9689
9690 --- return an iterator to the sorted elements of a sequence.
9691 -- @param iter a sequence
9692 -- @param comp an optional comparison function (comp(x,y) is true if x < y)
9693 function seq.sort(iter,comp)
9694 local t = seq.copy(iter)
9695 tsort(t,comp)
9696 return list(t)
9697 end
9698
9699 --- return an iterator which returns elements of two sequences.
9700 -- @param iter1 a sequence
9701 -- @param iter2 a sequence
9702 -- @usage for x,y in seq.zip(ls1,ls2) do....end
9703 function seq.zip(iter1,iter2)
9704 iter1 = default_iter(iter1)
9705 iter2 = default_iter(iter2)
9706 return function()
9707 return iter1(),iter2()
9708 end
9709 end
9710
9711 --- Makes a table where the key/values are the values and value counts of the sequence.
9712 -- This version works with 'hashable' values like strings and numbers.
9713 -- `pl.tablex.count_map` is more general.
9714 -- @param iter a sequence
9715 -- @return a map-like table
9716 -- @return a table
9717 -- @see pl.tablex.count_map
9718 function seq.count_map(iter)
9719 local t = {}
9720 local v
9721 for s in default_iter(iter) do
9722 v = t[s]
9723 if v then t[s] = v + 1
9724 else t[s] = 1 end
9725 end
9726 return setmetatable(t, require('pl.Map'))
9727 end
9728
9729 -- given a sequence, return all the unique values in that sequence.
9730 -- @param iter a sequence
9731 -- @param returns_table true if we return a table, not a sequence
9732 -- @return a sequence or a table; defaults to a sequence.
9733 function seq.unique(iter,returns_table)
9734 local t = seq.count_map(iter)
9735 local res,k = {},1
9736 for key in pairs(t) do res[k] = key; k = k + 1 end
9737 table.sort(res)
9738 if returns_table then
9739 return res
9740 else
9741 return list(res)
9742 end
9743 end
9744
9745 --- print out a sequence iter with a separator.
9746 -- @param iter a sequence
9747 -- @param sep the separator (default space)
9748 -- @param nfields maximum number of values per line (default 7)
9749 -- @param fmt optional format function for each value
9750 function seq.printall(iter,sep,nfields,fmt)
9751 local write = io.write
9752 if not sep then sep = ' ' end
9753 if not nfields then
9754 if sep == '\n' then nfields = 1e30
9755 else nfields = 7 end
9756 end
9757 if fmt then
9758 local fstr = fmt
9759 fmt = function(v) return format(fstr,v) end
9760 end
9761 local k = 1
9762 for v in default_iter(iter) do
9763 if fmt then v = fmt(v) end
9764 if k < nfields then
9765 write(v,sep)
9766 k = k + 1
9767 else
9768 write(v,'\n')
9769 k = 1
9770 end
9771 end
9772 write '\n'
9773 end
9774
9775 -- return an iterator running over every element of two sequences (concatenation).
9776 -- @param iter1 a sequence
9777 -- @param iter2 a sequence
9778 function seq.splice(iter1,iter2)
9779 iter1 = default_iter(iter1)
9780 iter2 = default_iter(iter2)
9781 local iter = iter1
9782 return function()
9783 local ret = iter()
9784 if ret == nil then
9785 if iter == iter1 then
9786 iter = iter2
9787 return iter()
9788 else return nil end
9789 else
9790 return ret
9791 end
9792 end
9793 end
9794
9795 --- return a sequence where every element of a sequence has been transformed
9796 -- by a function. If you don't supply an argument, then the function will
9797 -- receive both values of a double-valued sequence, otherwise behaves rather like
9798 -- tablex.map.
9799 -- @param fn a function to apply to elements; may take two arguments
9800 -- @param iter a sequence of one or two values
9801 -- @param arg optional argument to pass to function.
9802 function seq.map(fn,iter,arg)
9803 fn = function_arg(1,fn)
9804 iter = default_iter(iter)
9805 return function()
9806 local v1,v2 = iter()
9807 if v1 == nil then return nil end
9808 return fn(v1,arg or v2) or false
9809 end
9810 end
9811
9812 --- filter a sequence using a predicate function.
9813 -- @param iter a sequence of one or two values
9814 -- @param pred a boolean function; may take two arguments
9815 -- @param arg optional argument to pass to function.
9816 function seq.filter (iter,pred,arg)
9817 pred = function_arg(2,pred)
9818 return function ()
9819 local v1,v2
9820 while true do
9821 v1,v2 = iter()
9822 if v1 == nil then return nil end
9823 if pred(v1,arg or v2) then return v1,v2 end
9824 end
9825 end
9826 end
9827
9828 --- 'reduce' a sequence using a binary function.
9829 -- @func fn a function of two arguments
9830 -- @param iter a sequence
9831 -- @param initval optional initial value
9832 -- @usage seq.reduce(operator.add,seq.list{1,2,3,4}) == 10
9833 -- @usage seq.reduce('-',{1,2,3,4,5}) == -13
9834 function seq.reduce (fn,iter,initval)
9835 fn = function_arg(1,fn)
9836 iter = default_iter(iter)
9837 local val = initval or iter()
9838 if val == nil then return nil end
9839 for v in iter do
9840 val = fn(val,v)
9841 end
9842 return val
9843 end
9844
9845 --- take the first n values from the sequence.
9846 -- @param iter a sequence of one or two values
9847 -- @param n number of items to take
9848 -- @return a sequence of at most n items
9849 function seq.take (iter,n)
9850 iter = default_iter(iter)
9851 return function()
9852 if n < 1 then return end
9853 local val1,val2 = iter()
9854 if not val1 then return end
9855 n = n - 1
9856 return val1,val2
9857 end
9858 end
9859
9860 --- skip the first n values of a sequence
9861 -- @param iter a sequence of one or more values
9862 -- @param n number of items to skip
9863 function seq.skip (iter,n)
9864 n = n or 1
9865 for i = 1,n do
9866 if iter() == nil then return list{} end
9867 end
9868 return iter
9869 end
9870
9871 --- a sequence with a sequence count and the original value.
9872 -- enum(copy(ls)) is a roundabout way of saying ipairs(ls).
9873 -- @param iter a single or double valued sequence
9874 -- @return sequence of (i,v), i = 1..n and v is from iter.
9875 function seq.enum (iter)
9876 local i = 0
9877 iter = default_iter(iter)
9878 return function ()
9879 local val1,val2 = iter()
9880 if not val1 then return end
9881 i = i + 1
9882 return i,val1,val2
9883 end
9884 end
9885
9886 --- map using a named method over a sequence.
9887 -- @param iter a sequence
9888 -- @param name the method name
9889 -- @param arg1 optional first extra argument
9890 -- @param arg2 optional second extra argument
9891 function seq.mapmethod (iter,name,arg1,arg2)
9892 iter = default_iter(iter)
9893 return function()
9894 local val = iter()
9895 if not val then return end
9896 local fn = val[name]
9897 if not fn then error(type(val).." does not have method "..name) end
9898 return fn(val,arg1,arg2)
9899 end
9900 end
9901
9902 --- a sequence of (last,current) values from another sequence.
9903 -- This will return S(i-1),S(i) if given S(i)
9904 -- @param iter a sequence
9905 function seq.last (iter)
9906 iter = default_iter(iter)
9907 local val, l = iter(), nil
9908 if val == nil then return list{} end
9909 return function ()
9910 val,l = iter(),val
9911 if val == nil then return nil end
9912 return val,l
9913 end
9914 end
9915
9916 --- call the function on each element of the sequence.
9917 -- @param iter a sequence with up to 3 values
9918 -- @param fn a function
9919 function seq.foreach(iter,fn)
9920 fn = function_arg(2,fn)
9921 for i1,i2,i3 in default_iter(iter) do fn(i1,i2,i3) end
9922 end
9923
9924 ---------------------- Sequence Adapters ---------------------
9925
9926 local SMT
9927
9928 local function SW (iter,...)
9929 if callable(iter) then
9930 return setmetatable({iter=iter},SMT)
9931 else
9932 return iter,...
9933 end
9934 end
9935
9936
9937 -- can't directly look these up in seq because of the wrong argument order...
9938 local map,reduce,mapmethod = seq.map, seq.reduce, seq.mapmethod
9939 local overrides = {
9940 map = function(self,fun,arg)
9941 return map(fun,self,arg)
9942 end,
9943 reduce = function(self,fun,initval)
9944 return reduce(fun,self,initval)
9945 end
9946 }
9947
9948 SMT = {
9949 __index = function (tbl,key)
9950 local fn = overrides[key] or seq[key]
9951 if fn then
9952 return function(sw,...) return SW(fn(sw.iter,...)) end
9953 else
9954 return function(sw,...) return SW(mapmethod(sw.iter,key,...)) end
9955 end
9956 end,
9957 __call = function (sw)
9958 return sw.iter()
9959 end,
9960 }
9961
9962 setmetatable(seq,{
9963 __call = function(tbl,iter,extra)
9964 if not callable(iter) then
9965 if type(iter) == 'table' then iter = seq.list(iter)
9966 else return iter
9967 end
9968 end
9969 if extra then
9970 return setmetatable({iter=function()
9971 return iter(extra)
9972 end},SMT)
9973 else
9974 return setmetatable({iter=iter},SMT)
9975 end
9976 end
9977 })
9978
9979 --- create a wrapped iterator over all lines in the file.
9980 -- @param f either a filename, file-like object, or 'STDIN' (for standard input)
9981 -- @param ... for Lua 5.2 only, optional format specifiers, as in `io.read`.
9982 -- @return a sequence wrapper
9983 function seq.lines (f,...)
9984 local iter,obj
9985 if f == 'STDIN' then
9986 f = io.stdin
9987 elseif type(f) == 'string' then
9988 iter,obj = io.lines(f,...)
9989 elseif not f.read then
9990 error("Pass either a string or a file-like object",2)
9991 end
9992 if not iter then
9993 iter,obj = f:lines(...)
9994 end
9995 if obj then -- LuaJIT version returns a function operating on a file
9996 local lines,file = iter,obj
9997 iter = function() return lines(file) end
9998 end
9999 return SW(iter)
10000 end
10001
10002 function seq.import ()
10003 debug.setmetatable(function() end,{
10004 __index = function(tbl,key)
10005 local s = overrides[key] or seq[key]
10006 if s then return s
10007 else
10008 return function(s,...) return seq.mapmethod(s,key,...) end
10009 end
10010 end
10011 })
10012 end
10013
10014 return seq
10015
10016 end,
10017
10018 ["pl.Set"] = function()
10019 --------------------
10020 -- Module: 'pl.Set'
10021 --------------------
10022 --- A Set class.
10023 --
10024 -- > Set = require 'pl.Set'
10025 -- > = Set{'one','two'} == Set{'two','one'}
10026 -- true
10027 -- > fruit = Set{'apple','banana','orange'}
10028 -- > = fruit['banana']
10029 -- true
10030 -- > = fruit['hazelnut']
10031 -- nil
10032 -- > colours = Set{'red','orange','green','blue'}
10033 -- > = fruit,colours
10034 -- [apple,orange,banana] [blue,green,orange,red]
10035 -- > = fruit+colours
10036 -- [blue,green,apple,red,orange,banana]
10037 -- [orange]
10038 -- > more_fruits = fruit + 'apricot'
10039 -- > = fruit*colours
10040 -- > = more_fruits, fruit
10041 -- [banana,apricot,apple,orange] [banana,apple,orange]
10042 --
10043 -- Dependencies: `pl.utils`, `pl.tablex`, `pl.class`, `pl.Map`, (`pl.List` if __tostring is used)
10044 -- @classmod pl.Set
10045
10046 local tablex = require 'pl.tablex'
10047 local utils = require 'pl.utils'
10048 local array_tostring, concat = utils.array_tostring, table.concat
10049 local merge,difference = tablex.merge,tablex.difference
10050 local Map = require 'pl.Map'
10051 local class = require 'pl.class'
10052 local stdmt = utils.stdmt
10053 local Set = stdmt.Set
10054
10055 -- the Set class --------------------
10056 class(Map,nil,Set)
10057
10058 -- note: Set has _no_ methods!
10059 Set.__index = nil
10060
10061 local function makeset (t)
10062 return setmetatable(t,Set)
10063 end
10064
10065 --- create a set. <br>
10066 -- @param t may be a Set, Map or list-like table.
10067 -- @class function
10068 -- @name Set
10069 function Set:_init (t)
10070 t = t or {}
10071 local mt = getmetatable(t)
10072 if mt == Set or mt == Map then
10073 for k in pairs(t) do self[k] = true end
10074 else
10075 for _,v in ipairs(t) do self[v] = true end
10076 end
10077 end
10078
10079 --- string representation of a set.
10080 -- @within metamethods
10081 function Set:__tostring ()
10082 return '['..concat(array_tostring(Set.values(self)),',')..']'
10083 end
10084
10085 --- get a list of the values in a set.
10086 -- @param self a Set
10087 -- @function Set.values
10088 -- @return a list
10089 Set.values = Map.keys
10090
10091 --- map a function over the values of a set.
10092 -- @param self a Set
10093 -- @param fn a function
10094 -- @param ... extra arguments to pass to the function.
10095 -- @return a new set
10096 function Set.map (self,fn,...)
10097 fn = utils.function_arg(1,fn)
10098 local res = {}
10099 for k in pairs(self) do
10100 res[fn(k,...)] = true
10101 end
10102 return makeset(res)
10103 end
10104
10105 --- union of two sets (also +).
10106 -- @param self a Set
10107 -- @param set another set
10108 -- @return a new set
10109 function Set.union (self,set)
10110 return merge(self,set,true)
10111 end
10112
10113 --- modifies '+' operator to allow addition of non-Set elements
10114 --- Preserves +/- semantics - does not modify first argument.
10115 local function setadd(self,other)
10116 local mt = getmetatable(other)
10117 if mt == Set or mt == Map then
10118 return Set.union(self,other)
10119 else
10120 local new = Set(self)
10121 new[other] = true
10122 return new
10123 end
10124 end
10125
10126 --- union of sets.
10127 -- @within metamethods
10128 -- @function Set.__add
10129
10130 Set.__add = setadd
10131
10132 --- intersection of two sets (also *).
10133 -- @param self a Set
10134 -- @param set another set
10135 -- @return a new set
10136 -- @usage
10137 -- > s = Set{10,20,30}
10138 -- > t = Set{20,30,40}
10139 -- > = t
10140 -- [20,30,40]
10141 -- > = Set.intersection(s,t)
10142 -- [30,20]
10143 -- > = s*t
10144 -- [30,20]
10145
10146 function Set.intersection (self,set)
10147 return merge(self,set,false)
10148 end
10149
10150 --- intersection of sets.
10151 -- @within metamethods
10152 -- @function Set.__mul
10153 Set.__mul = Set.intersection
10154
10155 --- new set with elements in the set that are not in the other (also -).
10156 -- @param self a Set
10157 -- @param set another set
10158 -- @return a new set
10159 function Set.difference (self,set)
10160 return difference(self,set,false)
10161 end
10162
10163 --- modifies "-" operator to remove non-Set values from set.
10164 --- Preserves +/- semantics - does not modify first argument.
10165 local function setminus (self,other)
10166 local mt = getmetatable(other)
10167 if mt == Set or mt == Map then
10168 return Set.difference(self,other)
10169 else
10170 local new = Set(self)
10171 new[other] = nil
10172 return new
10173 end
10174 end
10175
10176 --- difference of sets.
10177 -- @within metamethods
10178 -- @function Set.__sub
10179 Set.__sub = setminus
10180
10181 -- a new set with elements in _either_ the set _or_ other but not both (also ^).
10182 -- @param self a Set
10183 -- @param set another set
10184 -- @return a new set
10185 function Set.symmetric_difference (self,set)
10186 return difference(self,set,true)
10187 end
10188
10189 --- symmetric difference of sets.
10190 -- @within metamethods
10191 -- @function Set.__pow
10192 Set.__pow = Set.symmetric_difference
10193
10194 --- is the first set a subset of the second (also <)?.
10195 -- @param self a Set
10196 -- @param set another set
10197 -- @return true or false
10198 function Set.issubset (self,set)
10199 for k in pairs(self) do
10200 if not set[k] then return false end
10201 end
10202 return true
10203 end
10204
10205 --- first set subset of second?
10206 -- @within metamethods
10207 -- @function Set.__lt
10208 Set.__lt = Set.issubset
10209
10210 --- is the set empty?.
10211 -- @param self a Set
10212 -- @return true or false
10213 function Set.isempty (self)
10214 return next(self) == nil
10215 end
10216
10217 --- are the sets disjoint? (no elements in common).
10218 -- Uses naive definition, i.e. that intersection is empty
10219 -- @param s1 a Set
10220 -- @param s2 another set
10221 -- @return true or false
10222 function Set.isdisjoint (s1,s2)
10223 return Set.isempty(Set.intersection(s1,s2))
10224 end
10225
10226 --- size of this set (also # for 5.2).
10227 -- @param s a Set
10228 -- @return size
10229 -- @function Set.len
10230 Set.len = tablex.size
10231
10232 --- cardinality of set (5.2).
10233 -- @within metamethods
10234 -- @function Set.__len
10235 Set.__len = Set.len
10236
10237 --- equality between sets.
10238 -- @within metamethods
10239 function Set.__eq (s1,s2)
10240 return Set.issubset(s1,s2) and Set.issubset(s2,s1)
10241 end
10242
10243 return Set
10244
10245 end,
10246
10247 ["pl.sip"] = function()
10248 --------------------
10249 -- Module: 'pl.sip'
10250 --------------------
10251 --- Simple Input Patterns (SIP).
10252 -- SIP patterns start with '$', then a
10253 -- one-letter type, and then an optional variable in curly braces.
10254 --
10255 -- sip.match('$v=$q','name="dolly"',res)
10256 -- ==> res=={'name','dolly'}
10257 -- sip.match('($q{first},$q{second})','("john","smith")',res)
10258 -- ==> res=={second='smith',first='john'}
10259 --
10260 -- Type names:
10261 --
10262 -- v identifier
10263 -- i integer
10264 -- f floating-point
10265 -- q quoted string
10266 -- ([{< match up to closing bracket
10267 --
10268 -- See @{08-additional.md.Simple_Input_Patterns|the Guide}
10269 --
10270 -- @module pl.sip
10271
10272 local loadstring = rawget(_G,'loadstring') or load
10273 local unpack = rawget(_G,'unpack') or rawget(table,'unpack')
10274
10275 local append,concat = table.insert,table.concat
10276 local ipairs,type = ipairs,type
10277 local io,_G = io,_G
10278 local print,rawget = print,rawget
10279
10280 local patterns = {
10281 FLOAT = '[%+%-%d]%d*%.?%d*[eE]?[%+%-]?%d*',
10282 INTEGER = '[+%-%d]%d*',
10283 IDEN = '[%a_][%w_]*',
10284 OPTION = '[%a_][%w_%-]*',
10285 }
10286
10287 local function assert_arg(idx,val,tp)
10288 if type(val) ~= tp then
10289 error("argument "..idx.." must be "..tp, 2)
10290 end
10291 end
10292
10293 local sip = {}
10294
10295 local brackets = {['<'] = '>', ['('] = ')', ['{'] = '}', ['['] = ']' }
10296 local stdclasses = {a=1,c=0,d=1,l=1,p=0,u=1,w=1,x=1,s=0}
10297
10298 local function group(s)
10299 return '('..s..')'
10300 end
10301
10302 -- escape all magic characters except $, which has special meaning
10303 -- Also, un-escape any characters after $, so $( and $[ passes through as is.
10304 local function escape (spec)
10305 return (spec:gsub('[%-%.%+%[%]%(%)%^%%%?%*]','%%%0'):gsub('%$%%(%S)','$%1'))
10306 end
10307
10308 -- Most spaces within patterns can match zero or more spaces.
10309 -- Spaces between alphanumeric characters or underscores or between
10310 -- patterns that can match these characters, however, must match at least
10311 -- one space. Otherwise '$v $v' would match 'abcd' as {'abc', 'd'}.
10312 -- This function replaces continuous spaces within a pattern with either
10313 -- '%s*' or '%s+' according to this rule. The pattern has already
10314 -- been stripped of pattern names by now.
10315 local function compress_spaces(patt)
10316 return (patt:gsub("()%s+()", function(i1, i2)
10317 local before = patt:sub(i1 - 2, i1 - 1)
10318 if before:match('%$[vifadxlu]') or before:match('^[^%$]?[%w_]$') then
10319 local after = patt:sub(i2, i2 + 1)
10320 if after:match('%$[vifadxlu]') or after:match('^[%w_]') then
10321 return '%s+'
10322 end
10323 end
10324 return '%s*'
10325 end))
10326 end
10327
10328 local pattern_map = {
10329 v = group(patterns.IDEN),
10330 i = group(patterns.INTEGER),
10331 f = group(patterns.FLOAT),
10332 o = group(patterns.OPTION),
10333 r = '(%S.*)',
10334 p = '([%a]?[:]?[\\/%.%w_]+)'
10335 }
10336
10337 function sip.custom_pattern(flag,patt)
10338 pattern_map[flag] = patt
10339 end
10340
10341 --- convert a SIP pattern into the equivalent Lua string pattern.
10342 -- @param spec a SIP pattern
10343 -- @param options a table; only the <code>at_start</code> field is
10344 -- currently meaningful and ensures that the pattern is anchored
10345 -- at the start of the string.
10346 -- @return a Lua string pattern.
10347 function sip.create_pattern (spec,options)
10348 assert_arg(1,spec,'string')
10349 local fieldnames,fieldtypes = {},{}
10350
10351 if type(spec) == 'string' then
10352 spec = escape(spec)
10353 else
10354 local res = {}
10355 for i,s in ipairs(spec) do
10356 res[i] = escape(s)
10357 end
10358 spec = concat(res,'.-')
10359 end
10360
10361 local kount = 1
10362
10363 local function addfield (name,type)
10364 name = name or kount
10365 append(fieldnames,name)
10366 fieldtypes[name] = type
10367 kount = kount + 1
10368 end
10369
10370 local named_vars = spec:find('{%a+}')
10371
10372 if options and options.at_start then
10373 spec = '^'..spec
10374 end
10375 if spec:sub(-1,-1) == '$' then
10376 spec = spec:sub(1,-2)..'$r'
10377 if named_vars then spec = spec..'{rest}' end
10378 end
10379
10380 local names
10381
10382 if named_vars then
10383 names = {}
10384 spec = spec:gsub('{(%a+)}',function(name)
10385 append(names,name)
10386 return ''
10387 end)
10388 end
10389 spec = compress_spaces(spec)
10390
10391 local k = 1
10392 local err
10393 local r = (spec:gsub('%$%S',function(s)
10394 local type,name
10395 type = s:sub(2,2)
10396 if names then name = names[k]; k=k+1 end
10397 -- this kludge is necessary because %q generates two matches, and
10398 -- we want to ignore the first. Not a problem for named captures.
10399 if not names and type == 'q' then
10400 addfield(nil,'Q')
10401 else
10402 addfield(name,type)
10403 end
10404 local res
10405 if pattern_map[type] then
10406 res = pattern_map[type]
10407 elseif type == 'q' then
10408 -- some Lua pattern matching voodoo; we want to match '...' as
10409 -- well as "...", and can use the fact that %n will match a
10410 -- previous capture. Adding the extra field above comes from needing
10411 -- to accommodate the extra spurious match (which is either ' or ")
10412 addfield(name,type)
10413 res = '(["\'])(.-)%'..(kount-2)
10414 else
10415 local endbracket = brackets[type]
10416 if endbracket then
10417 res = '(%b'..type..endbracket..')'
10418 elseif stdclasses[type] or stdclasses[type:lower()] then
10419 res = '(%'..type..'+)'
10420 else
10421 err = "unknown format type or character class"
10422 end
10423 end
10424 return res
10425 end))
10426
10427 if err then
10428 return nil,err
10429 else
10430 return r,fieldnames,fieldtypes
10431 end
10432 end
10433
10434
10435 local function tnumber (s)
10436 return s == 'd' or s == 'i' or s == 'f'
10437 end
10438
10439 function sip.create_spec_fun(spec,options)
10440 local fieldtypes,fieldnames
10441 local ls = {}
10442 spec,fieldnames,fieldtypes = sip.create_pattern(spec,options)
10443 if not spec then return spec,fieldnames end
10444 local named_vars = type(fieldnames[1]) == 'string'
10445 for i = 1,#fieldnames do
10446 append(ls,'mm'..i)
10447 end
10448 ls[1] = ls[1] or "mm1" -- behave correctly if there are no patterns
10449 local fun = ('return (function(s,res)\n\tlocal %s = s:match(%q)\n'):format(concat(ls,','),spec)
10450 fun = fun..'\tif not mm1 then return false end\n'
10451 local k=1
10452 for i,f in ipairs(fieldnames) do
10453 if f ~= '_' then
10454 local var = 'mm'..i
10455 if tnumber(fieldtypes[f]) then
10456 var = 'tonumber('..var..')'
10457 elseif brackets[fieldtypes[f]] then
10458 var = var..':sub(2,-2)'
10459 end
10460 if named_vars then
10461 fun = ('%s\tres.%s = %s\n'):format(fun,f,var)
10462 else
10463 if fieldtypes[f] ~= 'Q' then -- we skip the string-delim capture
10464 fun = ('%s\tres[%d] = %s\n'):format(fun,k,var)
10465 k = k + 1
10466 end
10467 end
10468 end
10469 end
10470 return fun..'\treturn true\nend)\n', named_vars
10471 end
10472
10473 --- convert a SIP pattern into a matching function.
10474 -- The returned function takes two arguments, the line and an empty table.
10475 -- If the line matched the pattern, then this function returns true
10476 -- and the table is filled with field-value pairs.
10477 -- @param spec a SIP pattern
10478 -- @param options optional table; {at_start=true} ensures that the pattern
10479 -- is anchored at the start of the string.
10480 -- @return a function if successful, or nil,error
10481 function sip.compile(spec,options)
10482 assert_arg(1,spec,'string')
10483 local fun,names = sip.create_spec_fun(spec,options)
10484 if not fun then return nil,names end
10485 if rawget(_G,'_DEBUG') then print(fun) end
10486 local chunk,err = loadstring(fun,'tmp')
10487 if err then return nil,err end
10488 return chunk(),names
10489 end
10490
10491 local cache = {}
10492
10493 --- match a SIP pattern against a string.
10494 -- @param spec a SIP pattern
10495 -- @param line a string
10496 -- @param res a table to receive values
10497 -- @param options (optional) option table
10498 -- @return true or false
10499 function sip.match (spec,line,res,options)
10500 assert_arg(1,spec,'string')
10501 assert_arg(2,line,'string')
10502 assert_arg(3,res,'table')
10503 if not cache[spec] then
10504 cache[spec] = sip.compile(spec,options)
10505 end
10506 return cache[spec](line,res)
10507 end
10508
10509 --- match a SIP pattern against the start of a string.
10510 -- @param spec a SIP pattern
10511 -- @param line a string
10512 -- @param res a table to receive values
10513 -- @return true or false
10514 function sip.match_at_start (spec,line,res)
10515 return sip.match(spec,line,res,{at_start=true})
10516 end
10517
10518 --- given a pattern and a file object, return an iterator over the results
10519 -- @param spec a SIP pattern
10520 -- @param f a file-like object.
10521 function sip.fields (spec,f)
10522 assert_arg(1,spec,'string')
10523 if not f then return nil,"no file object" end
10524 local fun,err = sip.compile(spec)
10525 if not fun then return nil,err end
10526 local res = {}
10527 return function()
10528 while true do
10529 local line = f:read()
10530 if not line then return end
10531 if fun(line,res) then
10532 local values = res
10533 res = {}
10534 return unpack(values)
10535 end
10536 end
10537 end
10538 end
10539
10540 local read_patterns = {}
10541
10542 --- register a match which will be used in the read function.
10543 -- @string spec a SIP pattern
10544 -- @func fun a function to be called with the results of the match
10545 -- @see read
10546 function sip.pattern (spec,fun)
10547 assert_arg(1,spec,'string')
10548 local pat,named = sip.compile(spec)
10549 append(read_patterns,{pat=pat,named=named,callback=fun})
10550 end
10551
10552 --- enter a loop which applies all registered matches to the input file.
10553 -- @param f a file-like object
10554 -- @array matches optional list of `{spec,fun}` pairs, as for `pattern` above.
10555 function sip.read (f,matches)
10556 local owned,err
10557 if not f then return nil,"no file object" end
10558 if type(f) == 'string' then
10559 f,err = io.open(f)
10560 if not f then return nil,err end
10561 owned = true
10562 end
10563 if matches then
10564 for _,p in ipairs(matches) do
10565 sip.pattern(p[1],p[2])
10566 end
10567 end
10568 local res = {}
10569 for line in f:lines() do
10570 for _,item in ipairs(read_patterns) do
10571 if item.pat(line,res) then
10572 if item.callback then
10573 if item.named then
10574 item.callback(res)
10575 else
10576 item.callback(unpack(res))
10577 end
10578 end
10579 res = {}
10580 break
10581 end
10582 end
10583 end
10584 if owned then f:close() end
10585 end
10586
10587 return sip
10588
10589 end,
10590
10591 ["pl.strict"] = function()
10592 --------------------
10593 -- Module: 'pl.strict'
10594 --------------------
10595 --- Checks uses of undeclared global variables.
10596 -- All global variables must be 'declared' through a regular assignment
10597 -- (even assigning `nil` will do) in a main chunk before being used
10598 -- anywhere or assigned to inside a function. Existing metatables `__newindex` and `__index`
10599 -- metamethods are respected.
10600 --
10601 -- You can set any table to have strict behaviour using `strict.module`. Creating a new
10602 -- module with `strict.closed_module` makes the module immune to monkey-patching, if
10603 -- you don't wish to encourage monkey business.
10604 --
10605 -- If the global `PENLIGHT_NO_GLOBAL_STRICT` is defined, then this module won't make the
10606 -- global environment strict - if you just want to explicitly set table strictness.
10607 --
10608 -- @module pl.strict
10609
10610 require 'debug' -- for Lua 5.2
10611 local getinfo, error, rawset, rawget = debug.getinfo, error, rawset, rawget
10612 local strict = {}
10613
10614 local function what ()
10615 local d = getinfo(3, "S")
10616 return d and d.what or "C"
10617 end
10618
10619 --- make an existing table strict.
10620 -- @string[opt] name name of table
10621 -- @tab[opt] mod the table to protect - if `nil` then we'll return a new table
10622 -- @tab[opt] predeclared - table of variables that are to be considered predeclared.
10623 -- @return the given table, or a new table
10624 -- @usage
10625 -- local M = { hello = "world" }
10626 -- strict.module ("Awesome_Module", M, {
10627 -- Lua = true, -- defines allowed keys
10628 -- })
10629 --
10630 -- assert(M.hello == "world")
10631 -- assert(M.Lua == nil) -- access allowed, but has no value yet
10632 -- M.Lua = "Rocks"
10633 -- assert(M.Lua == "Rocks")
10634 -- M.not_allowed = "bad boy" -- throws an error
10635 function strict.module (name,mod,predeclared)
10636 local mt, old_newindex, old_index, old_index_type, global
10637 if predeclared then
10638 global = predeclared.__global
10639 end
10640 if type(mod) == 'table' then
10641 mt = getmetatable(mod)
10642 if mt and rawget(mt,'__declared') then return end -- already patched...
10643 else
10644 mod = {}
10645 end
10646 if mt == nil then
10647 mt = {}
10648 setmetatable(mod, mt)
10649 else
10650 old_newindex = mt.__newindex
10651 old_index = mt.__index
10652 old_index_type = type(old_index)
10653 end
10654 mt.__declared = predeclared or {}
10655 mt.__newindex = function(t, n, v)
10656 if old_newindex then
10657 old_newindex(t, n, v)
10658 if rawget(t,n)~=nil then return end
10659 end
10660 if not mt.__declared[n] then
10661 if global then
10662 local w = what()
10663 if w ~= "main" and w ~= "C" then
10664 error("assign to undeclared global '"..n.."'", 2)
10665 end
10666 end
10667 mt.__declared[n] = true
10668 end
10669 rawset(t, n, v)
10670 end
10671 mt.__index = function(t,n)
10672 if not mt.__declared[n] and what() ~= "C" then
10673 if old_index then
10674 if old_index_type == "table" then
10675 local fallback = old_index[n]
10676 if fallback ~= nil then
10677 return fallback
10678 end
10679 else
10680 local res = old_index(t, n)
10681 if res ~= nil then
10682 return res
10683 end
10684 end
10685 end
10686 local msg = "variable '"..n.."' is not declared"
10687 if name then
10688 msg = msg .. " in '"..tostring(name).."'"
10689 end
10690 error(msg, 2)
10691 end
10692 return rawget(t, n)
10693 end
10694 return mod
10695 end
10696
10697 --- make all tables in a table strict.
10698 -- So `strict.make_all_strict(_G)` prevents monkey-patching
10699 -- of any global table
10700 -- @tab T the table containing the tables to protect. Table `T` itself will NOT be protected.
10701 function strict.make_all_strict (T)
10702 for k,v in pairs(T) do
10703 if type(v) == 'table' and v ~= T then
10704 strict.module(k,v)
10705 end
10706 end
10707 end
10708
10709 --- make a new module table which is closed to further changes.
10710 -- @tab mod module table
10711 -- @string name module name
10712 function strict.closed_module (mod,name)
10713 -- No clue to what this is useful for? see tests
10714 -- Deprecate this and remove???
10715 local M = {}
10716 mod = mod or {}
10717 local mt = getmetatable(mod)
10718 if not mt then
10719 mt = {}
10720 setmetatable(mod,mt)
10721 end
10722 mt.__newindex = function(t,k,v)
10723 M[k] = v
10724 end
10725 return strict.module(name,M)
10726 end
10727
10728 if not rawget(_G,'PENLIGHT_NO_GLOBAL_STRICT') then
10729 strict.module(nil,_G,{_PROMPT=true,_PROMPT2=true,__global=true})
10730 end
10731
10732 return strict
10733
10734 end,
10735
10736 ["pl.stringio"] = function()
10737 --------------------
10738 -- Module: 'pl.stringio'
10739 --------------------
10740 --- Reading and writing strings using file-like objects. <br>
10741 --
10742 -- f = stringio.open(text)
10743 -- l1 = f:read() -- read first line
10744 -- n,m = f:read ('*n','*n') -- read two numbers
10745 -- for line in f:lines() do print(line) end -- iterate over all lines
10746 -- f = stringio.create()
10747 -- f:write('hello')
10748 -- f:write('dolly')
10749 -- assert(f:value(),'hellodolly')
10750 --
10751 -- See @{03-strings.md.File_style_I_O_on_Strings|the Guide}.
10752 -- @module pl.stringio
10753
10754 local unpack = rawget(_G,'unpack') or rawget(table,'unpack')
10755 local tonumber = tonumber
10756 local concat,append = table.concat,table.insert
10757
10758 local stringio = {}
10759
10760 -- Writer class
10761 local SW = {}
10762 SW.__index = SW
10763
10764 local function xwrite(self,...)
10765 local args = {...} --arguments may not be nil!
10766 for i = 1, #args do
10767 append(self.tbl,args[i])
10768 end
10769 end
10770
10771 function SW:write(arg1,arg2,...)
10772 if arg2 then
10773 xwrite(self,arg1,arg2,...)
10774 else
10775 append(self.tbl,arg1)
10776 end
10777 end
10778
10779 function SW:writef(fmt,...)
10780 self:write(fmt:format(...))
10781 end
10782
10783 function SW:value()
10784 return concat(self.tbl)
10785 end
10786
10787 function SW:__tostring()
10788 return self:value()
10789 end
10790
10791 function SW:close() -- for compatibility only
10792 end
10793
10794 function SW:seek()
10795 end
10796
10797 -- Reader class
10798 local SR = {}
10799 SR.__index = SR
10800
10801 function SR:_read(fmt)
10802 local i,str = self.i,self.str
10803 local sz = #str
10804 if i > sz then return nil end
10805 local res
10806 if fmt == '*l' or fmt == '*L' then
10807 local idx = str:find('\n',i) or (sz+1)
10808 res = str:sub(i,fmt == '*l' and idx-1 or idx)
10809 self.i = idx+1
10810 elseif fmt == '*a' then
10811 res = str:sub(i)
10812 self.i = sz
10813 elseif fmt == '*n' then
10814 local _,i2,idx
10815 _,idx = str:find ('%s*%d+',i)
10816 _,i2 = str:find ('^%.%d+',idx+1)
10817 if i2 then idx = i2 end
10818 _,i2 = str:find ('^[eE][%+%-]*%d+',idx+1)
10819 if i2 then idx = i2 end
10820 local val = str:sub(i,idx)
10821 res = tonumber(val)
10822 self.i = idx+1
10823 elseif type(fmt) == 'number' then
10824 res = str:sub(i,i+fmt-1)
10825 self.i = i + fmt
10826 else
10827 error("bad read format",2)
10828 end
10829 return res
10830 end
10831
10832 function SR:read(...)
10833 if select('#',...) == 0 then
10834 return self:_read('*l')
10835 else
10836 local res, fmts = {},{...}
10837 for i = 1, #fmts do
10838 res[i] = self:_read(fmts[i])
10839 end
10840 return unpack(res)
10841 end
10842 end
10843
10844 function SR:seek(whence,offset)
10845 local base
10846 whence = whence or 'cur'
10847 offset = offset or 0
10848 if whence == 'set' then
10849 base = 1
10850 elseif whence == 'cur' then
10851 base = self.i
10852 elseif whence == 'end' then
10853 base = #self.str
10854 end
10855 self.i = base + offset
10856 return self.i
10857 end
10858
10859 function SR:lines(...)
10860 local n, args = select('#',...)
10861 if n > 0 then
10862 args = {...}
10863 end
10864 return function()
10865 if n == 0 then
10866 return self:_read '*l'
10867 else
10868 return self:read(unpack(args))
10869 end
10870 end
10871 end
10872
10873 function SR:close() -- for compatibility only
10874 end
10875
10876 --- create a file-like object which can be used to construct a string.
10877 -- The resulting object has an extra `value()` method for
10878 -- retrieving the string value. Implements `file:write`, `file:seek`, `file:lines`,
10879 -- plus an extra `writef` method which works like `utils.printf`.
10880 -- @usage f = create(); f:write('hello, dolly\n'); print(f:value())
10881 function stringio.create()
10882 return setmetatable({tbl={}},SW)
10883 end
10884
10885 --- create a file-like object for reading from a given string.
10886 -- Implements `file:read`.
10887 -- @string s The input string.
10888 -- @usage fs = open '20 10'; x,y = f:read ('*n','*n'); assert(x == 20 and y == 10)
10889 function stringio.open(s)
10890 return setmetatable({str=s,i=1},SR)
10891 end
10892
10893 function stringio.lines(s,...)
10894 return stringio.open(s):lines(...)
10895 end
10896
10897 return stringio
10898
10899 end,
10900
10901 ["pl.stringx"] = function()
10902 --------------------
10903 -- Module: 'pl.stringx'
10904 --------------------
10905 --- Python-style extended string library.
10906 --
10907 -- see 3.6.1 of the Python reference.
10908 -- If you want to make these available as string methods, then say
10909 -- `stringx.import()` to bring them into the standard `string` table.
10910 --
10911 -- See @{03-strings.md|the Guide}
10912 --
10913 -- Dependencies: `pl.utils`, `pl.types`
10914 -- @module pl.stringx
10915 local utils = require 'pl.utils'
10916 local is_callable = require 'pl.types'.is_callable
10917 local string = string
10918 local find = string.find
10919 local type,setmetatable,ipairs = type,setmetatable,ipairs
10920 local error = error
10921 local gsub = string.gsub
10922 local rep = string.rep
10923 local sub = string.sub
10924 local reverse = string.reverse
10925 local concat = table.concat
10926 local append = table.insert
10927 local remove = table.remove
10928 local escape = utils.escape
10929 local ceil, max = math.ceil, math.max
10930 local assert_arg,usplit = utils.assert_arg,utils.split
10931 local lstrip
10932 local unpack = utils.unpack
10933 local pack = utils.pack
10934
10935 local function assert_string (n,s)
10936 assert_arg(n,s,'string')
10937 end
10938
10939 local function non_empty(s)
10940 return #s > 0
10941 end
10942
10943 local function assert_nonempty_string(n,s)
10944 assert_arg(n,s,'string',non_empty,'must be a non-empty string')
10945 end
10946
10947 local function makelist(l)
10948 return setmetatable(l, require('pl.List'))
10949 end
10950
10951 local stringx = {}
10952
10953 ------------------
10954 -- String Predicates
10955 -- @section predicates
10956
10957 --- does s only contain alphabetic characters?
10958 -- @string s a string
10959 function stringx.isalpha(s)
10960 assert_string(1,s)
10961 return find(s,'^%a+$') == 1
10962 end
10963
10964 --- does s only contain digits?
10965 -- @string s a string
10966 function stringx.isdigit(s)
10967 assert_string(1,s)
10968 return find(s,'^%d+$') == 1
10969 end
10970
10971 --- does s only contain alphanumeric characters?
10972 -- @string s a string
10973 function stringx.isalnum(s)
10974 assert_string(1,s)
10975 return find(s,'^%w+$') == 1
10976 end
10977
10978 --- does s only contain whitespace?
10979 -- Matches on pattern '%s' so matches space, newline, tabs, etc.
10980 -- @string s a string
10981 function stringx.isspace(s)
10982 assert_string(1,s)
10983 return find(s,'^%s+$') == 1
10984 end
10985
10986 --- does s only contain lower case characters?
10987 -- @string s a string
10988 function stringx.islower(s)
10989 assert_string(1,s)
10990 return find(s,'^[%l%s]+$') == 1
10991 end
10992
10993 --- does s only contain upper case characters?
10994 -- @string s a string
10995 function stringx.isupper(s)
10996 assert_string(1,s)
10997 return find(s,'^[%u%s]+$') == 1
10998 end
10999
11000 local function raw_startswith(s, prefix)
11001 return find(s,prefix,1,true) == 1
11002 end
11003
11004 local function raw_endswith(s, suffix)
11005 return #s >= #suffix and find(s, suffix, #s-#suffix+1, true) and true or false
11006 end
11007
11008 local function test_affixes(s, affixes, fn)
11009 if type(affixes) == 'string' then
11010 return fn(s,affixes)
11011 elseif type(affixes) == 'table' then
11012 for _,affix in ipairs(affixes) do
11013 if fn(s,affix) then return true end
11014 end
11015 return false
11016 else
11017 error(("argument #2 expected a 'string' or a 'table', got a '%s'"):format(type(affixes)))
11018 end
11019 end
11020
11021 --- does s start with prefix or one of prefixes?
11022 -- @string s a string
11023 -- @param prefix a string or an array of strings
11024 function stringx.startswith(s,prefix)
11025 assert_string(1,s)
11026 return test_affixes(s,prefix,raw_startswith)
11027 end
11028
11029 --- does s end with suffix or one of suffixes?
11030 -- @string s a string
11031 -- @param suffix a string or an array of strings
11032 function stringx.endswith(s,suffix)
11033 assert_string(1,s)
11034 return test_affixes(s,suffix,raw_endswith)
11035 end
11036
11037 --- Strings and Lists
11038 -- @section lists
11039
11040 --- concatenate the strings using this string as a delimiter.
11041 -- Note that the arguments are reversed from `string.concat`.
11042 -- @string s the string
11043 -- @param seq a table of strings or numbers
11044 -- @usage stringx.join(' ', {1,2,3}) == '1 2 3'
11045 function stringx.join(s,seq)
11046 assert_string(1,s)
11047 return concat(seq,s)
11048 end
11049
11050 --- Split a string into a list of lines.
11051 -- `"\r"`, `"\n"`, and `"\r\n"` are considered line ends.
11052 -- They are not included in the lines unless `keepends` is passed.
11053 -- Terminal line end does not produce an extra line.
11054 -- Splitting an empty string results in an empty list.
11055 -- @string s the string.
11056 -- @bool[opt] keep_ends include line ends.
11057 -- @return List of lines
11058 function stringx.splitlines(s, keep_ends)
11059 assert_string(1, s)
11060 local res = {}
11061 local pos = 1
11062 while true do
11063 local line_end_pos = find(s, '[\r\n]', pos)
11064 if not line_end_pos then
11065 break
11066 end
11067
11068 local line_end = sub(s, line_end_pos, line_end_pos)
11069 if line_end == '\r' and sub(s, line_end_pos + 1, line_end_pos + 1) == '\n' then
11070 line_end = '\r\n'
11071 end
11072
11073 local line = sub(s, pos, line_end_pos - 1)
11074 if keep_ends then
11075 line = line .. line_end
11076 end
11077 append(res, line)
11078
11079 pos = line_end_pos + #line_end
11080 end
11081
11082 if pos <= #s then
11083 append(res, sub(s, pos))
11084 end
11085 return makelist(res)
11086 end
11087
11088 --- split a string into a list of strings using a delimiter.
11089 -- @function split
11090 -- @string s the string
11091 -- @string[opt] re a delimiter (defaults to whitespace)
11092 -- @int[opt] n maximum number of results
11093 -- @return List
11094 -- @usage #(stringx.split('one two')) == 2
11095 -- @usage stringx.split('one,two,three', ',') == List{'one','two','three'}
11096 -- @usage stringx.split('one,two,three', ',', 2) == List{'one','two,three'}
11097 function stringx.split(s,re,n)
11098 assert_string(1,s)
11099 local plain = true
11100 if not re then -- default spaces
11101 s = lstrip(s)
11102 plain = false
11103 end
11104 local res = usplit(s,re,plain,n)
11105 if re and re ~= '' and
11106 find(s,re,-#re,true) and
11107 (n or math.huge) > #res then
11108 res[#res+1] = ""
11109 end
11110 return makelist(res)
11111 end
11112
11113 --- replace all tabs in s with tabsize spaces. If not specified, tabsize defaults to 8.
11114 -- Tab stops will be honored.
11115 -- @string s the string
11116 -- @int tabsize[opt=8] number of spaces to expand each tab
11117 -- @return expanded string
11118 -- @usage stringx.expandtabs('\tone,two,three', 4) == ' one,two,three'
11119 -- @usage stringx.expandtabs(' \tone,two,three', 4) == ' one,two,three'
11120 function stringx.expandtabs(s,tabsize)
11121 assert_string(1,s)
11122 tabsize = tabsize or 8
11123 return (s:gsub("([^\t\r\n]*)\t", function(before_tab)
11124 if tabsize == 0 then
11125 return before_tab
11126 else
11127 return before_tab .. (" "):rep(tabsize - #before_tab % tabsize)
11128 end
11129 end))
11130 end
11131
11132 --- Finding and Replacing
11133 -- @section find
11134
11135 local function _find_all(s,sub,first,last,allow_overlap)
11136 first = first or 1
11137 last = last or #s
11138 if sub == '' then return last+1,last-first+1 end
11139 local i1,i2 = find(s,sub,first,true)
11140 local res
11141 local k = 0
11142 while i1 do
11143 if last and i2 > last then break end
11144 res = i1
11145 k = k + 1
11146 if allow_overlap then
11147 i1,i2 = find(s,sub,i1+1,true)
11148 else
11149 i1,i2 = find(s,sub,i2+1,true)
11150 end
11151 end
11152 return res,k
11153 end
11154
11155 --- find index of first instance of sub in s from the left.
11156 -- @string s the string
11157 -- @string sub substring
11158 -- @int[opt] first first index
11159 -- @int[opt] last last index
11160 -- @return start index, or nil if not found
11161 function stringx.lfind(s,sub,first,last)
11162 assert_string(1,s)
11163 assert_string(2,sub)
11164 local i1, i2 = find(s,sub,first,true)
11165
11166 if i1 and (not last or i2 <= last) then
11167 return i1
11168 else
11169 return nil
11170 end
11171 end
11172
11173 --- find index of first instance of sub in s from the right.
11174 -- @string s the string
11175 -- @string sub substring
11176 -- @int[opt] first first index
11177 -- @int[opt] last last index
11178 -- @return start index, or nil if not found
11179 function stringx.rfind(s,sub,first,last)
11180 assert_string(1,s)
11181 assert_string(2,sub)
11182 return (_find_all(s,sub,first,last,true))
11183 end
11184
11185 --- replace up to n instances of old by new in the string s.
11186 -- If n is not present, replace all instances.
11187 -- @string s the string
11188 -- @string old the target substring
11189 -- @string new the substitution
11190 -- @int[opt] n optional maximum number of substitutions
11191 -- @return result string
11192 function stringx.replace(s,old,new,n)
11193 assert_string(1,s)
11194 assert_string(2,old)
11195 assert_string(3,new)
11196 return (gsub(s,escape(old),new:gsub('%%','%%%%'),n))
11197 end
11198
11199 --- count all instances of substring in string.
11200 -- @string s the string
11201 -- @string sub substring
11202 -- @bool[opt] allow_overlap allow matches to overlap
11203 -- @usage
11204 -- assert(stringx.count('banana', 'ana') == 1)
11205 -- assert(stringx.count('banana', 'ana', true) == 2)
11206 function stringx.count(s,sub,allow_overlap)
11207 assert_string(1,s)
11208 local _,k = _find_all(s,sub,1,false,allow_overlap)
11209 return k
11210 end
11211
11212 --- Stripping and Justifying
11213 -- @section strip
11214
11215 local function _just(s,w,ch,left,right)
11216 local n = #s
11217 if w > n then
11218 if not ch then ch = ' ' end
11219 local f1,f2
11220 if left and right then
11221 local rn = ceil((w-n)/2)
11222 local ln = w - n - rn
11223 f1 = rep(ch,ln)
11224 f2 = rep(ch,rn)
11225 elseif right then
11226 f1 = rep(ch,w-n)
11227 f2 = ''
11228 else
11229 f2 = rep(ch,w-n)
11230 f1 = ''
11231 end
11232 return f1..s..f2
11233 else
11234 return s
11235 end
11236 end
11237
11238 --- left-justify s with width w.
11239 -- @string s the string
11240 -- @int w width of justification
11241 -- @string[opt=' '] ch padding character
11242 -- @usage stringx.ljust('hello', 10, '*') == '*****hello'
11243 function stringx.ljust(s,w,ch)
11244 assert_string(1,s)
11245 assert_arg(2,w,'number')
11246 return _just(s,w,ch,true,false)
11247 end
11248
11249 --- right-justify s with width w.
11250 -- @string s the string
11251 -- @int w width of justification
11252 -- @string[opt=' '] ch padding character
11253 -- @usage stringx.rjust('hello', 10, '*') == 'hello*****'
11254 function stringx.rjust(s,w,ch)
11255 assert_string(1,s)
11256 assert_arg(2,w,'number')
11257 return _just(s,w,ch,false,true)
11258 end
11259
11260 --- center-justify s with width w.
11261 -- @string s the string
11262 -- @int w width of justification
11263 -- @string[opt=' '] ch padding character
11264 -- @usage stringx.center('hello', 10, '*') == '**hello***'
11265 function stringx.center(s,w,ch)
11266 assert_string(1,s)
11267 assert_arg(2,w,'number')
11268 return _just(s,w,ch,true,true)
11269 end
11270
11271 local function _strip(s,left,right,chrs)
11272 if not chrs then
11273 chrs = '%s'
11274 else
11275 chrs = '['..escape(chrs)..']'
11276 end
11277 local f = 1
11278 local t
11279 if left then
11280 local i1,i2 = find(s,'^'..chrs..'*')
11281 if i2 >= i1 then
11282 f = i2+1
11283 end
11284 end
11285 if right then
11286 if #s < 200 then
11287 local i1,i2 = find(s,chrs..'*$',f)
11288 if i2 >= i1 then
11289 t = i1-1
11290 end
11291 else
11292 local rs = reverse(s)
11293 local i1,i2 = find(rs, '^'..chrs..'*')
11294 if i2 >= i1 then
11295 t = -i2-1
11296 end
11297 end
11298 end
11299 return sub(s,f,t)
11300 end
11301
11302 --- trim any characters on the left of s.
11303 -- @string s the string
11304 -- @string[opt='%s'] chrs default any whitespace character,
11305 -- but can be a string of characters to be trimmed
11306 function stringx.lstrip(s,chrs)
11307 assert_string(1,s)
11308 return _strip(s,true,false,chrs)
11309 end
11310 lstrip = stringx.lstrip
11311
11312 --- trim any characters on the right of s.
11313 -- @string s the string
11314 -- @string[opt='%s'] chrs default any whitespace character,
11315 -- but can be a string of characters to be trimmed
11316 function stringx.rstrip(s,chrs)
11317 assert_string(1,s)
11318 return _strip(s,false,true,chrs)
11319 end
11320
11321 --- trim any characters on both left and right of s.
11322 -- @string s the string
11323 -- @string[opt='%s'] chrs default any whitespace character,
11324 -- but can be a string of characters to be trimmed
11325 -- @usage stringx.strip(' --== Hello ==-- ', "- =") --> 'Hello'
11326 function stringx.strip(s,chrs)
11327 assert_string(1,s)
11328 return _strip(s,true,true,chrs)
11329 end
11330
11331 --- Partitioning Strings
11332 -- @section partitioning
11333
11334 --- split a string using a pattern. Note that at least one value will be returned!
11335 -- @string s the string
11336 -- @string[opt='%s'] re a Lua string pattern (defaults to whitespace)
11337 -- @return the parts of the string
11338 -- @usage a,b = line:splitv('=')
11339 -- @see utils.splitv
11340 function stringx.splitv(s,re)
11341 assert_string(1,s)
11342 return utils.splitv(s,re)
11343 end
11344
11345 -- The partition functions split a string using a delimiter into three parts:
11346 -- the part before, the delimiter itself, and the part afterwards
11347 local function _partition(p,delim,fn)
11348 local i1,i2 = fn(p,delim)
11349 if not i1 or i1 == -1 then
11350 return p,'',''
11351 else
11352 if not i2 then i2 = i1 end
11353 return sub(p,1,i1-1),sub(p,i1,i2),sub(p,i2+1)
11354 end
11355 end
11356
11357 --- partition the string using first occurrence of a delimiter
11358 -- @string s the string
11359 -- @string ch delimiter (match as plain string, no patterns)
11360 -- @return part before ch
11361 -- @return ch
11362 -- @return part after ch
11363 -- @usage {stringx.partition('a,b,c', ','))} == {'a', ',', 'b,c'}
11364 -- @usage {stringx.partition('abc', 'x'))} == {'abc', '', ''}
11365 function stringx.partition(s,ch)
11366 assert_string(1,s)
11367 assert_nonempty_string(2,ch)
11368 return _partition(s,ch,stringx.lfind)
11369 end
11370
11371 --- partition the string p using last occurrence of a delimiter
11372 -- @string s the string
11373 -- @string ch delimiter (match as plain string, no patterns)
11374 -- @return part before ch
11375 -- @return ch
11376 -- @return part after ch
11377 -- @usage {stringx.rpartition('a,b,c', ','))} == {'a,b', ',', 'c'}
11378 -- @usage {stringx.rpartition('abc', 'x'))} == {'', '', 'abc'}
11379 function stringx.rpartition(s,ch)
11380 assert_string(1,s)
11381 assert_nonempty_string(2,ch)
11382 local a,b,c = _partition(s,ch,stringx.rfind)
11383 if a == s then -- no match found
11384 return c,b,a
11385 end
11386 return a,b,c
11387 end
11388
11389 --- return the 'character' at the index.
11390 -- @string s the string
11391 -- @int idx an index (can be negative)
11392 -- @return a substring of length 1 if successful, empty string otherwise.
11393 function stringx.at(s,idx)
11394 assert_string(1,s)
11395 assert_arg(2,idx,'number')
11396 return sub(s,idx,idx)
11397 end
11398
11399
11400 --- Text handling
11401 -- @section text
11402
11403
11404 --- indent a multiline string.
11405 -- @tparam string s the (multiline) string
11406 -- @tparam integer n the size of the indent
11407 -- @tparam[opt=' '] string ch the character to use when indenting
11408 -- @return indented string
11409 function stringx.indent (s,n,ch)
11410 assert_arg(1,s,'string')
11411 assert_arg(2,n,'number')
11412 local lines = usplit(s ,'\n')
11413 local prefix = string.rep(ch or ' ',n)
11414 for i, line in ipairs(lines) do
11415 lines[i] = prefix..line
11416 end
11417 return concat(lines,'\n')..'\n'
11418 end
11419
11420
11421 --- dedent a multiline string by removing any initial indent.
11422 -- useful when working with [[..]] strings.
11423 -- Empty lines are ignored.
11424 -- @tparam string s the (multiline) string
11425 -- @return a string with initial indent zero.
11426 -- @usage
11427 -- local s = dedent [[
11428 -- One
11429 --
11430 -- Two
11431 --
11432 -- Three
11433 -- ]]
11434 -- assert(s == [[
11435 -- One
11436 --
11437 -- Two
11438 --
11439 -- Three
11440 -- ]])
11441 function stringx.dedent (s)
11442 assert_arg(1,s,'string')
11443 local lst = usplit(s,'\n')
11444 if #lst>0 then
11445 local ind_size = math.huge
11446 for i, line in ipairs(lst) do
11447 local i1, i2 = lst[i]:find('^%s*[^%s]')
11448 if i1 and i2 < ind_size then
11449 ind_size = i2
11450 end
11451 end
11452 for i, line in ipairs(lst) do
11453 lst[i] = lst[i]:sub(ind_size, -1)
11454 end
11455 end
11456 return concat(lst,'\n')..'\n'
11457 end
11458
11459
11460
11461 do
11462 local buildline = function(words, size, breaklong)
11463 -- if overflow is set, a word longer than size, will overflow the size
11464 -- otherwise it will be chopped in line-length pieces
11465 local line = {}
11466 if #words[1] > size then
11467 -- word longer than line
11468 if not breaklong then
11469 line[1] = words[1]
11470 remove(words, 1)
11471 else
11472 line[1] = words[1]:sub(1, size)
11473 words[1] = words[1]:sub(size + 1, -1)
11474 end
11475 else
11476 local len = 0
11477 while words[1] and (len + #words[1] <= size) or
11478 (len == 0 and #words[1] == size) do
11479 if words[1] ~= "" then
11480 line[#line+1] = words[1]
11481 len = len + #words[1] + 1
11482 end
11483 remove(words, 1)
11484 end
11485 end
11486 return stringx.strip(concat(line, " ")), words
11487 end
11488
11489 --- format a paragraph into lines so that they fit into a line width.
11490 -- It will not break long words by default, so lines can be over the length
11491 -- to that extent.
11492 -- @tparam string s the string to format
11493 -- @tparam[opt=70] integer width the margin width
11494 -- @tparam[opt=false] boolean breaklong if truthy, words longer than the width given will be forced split.
11495 -- @return a list of lines (List object), use `fill` to return a string instead of a `List`.
11496 -- @see pl.List
11497 -- @see fill
11498 stringx.wrap = function(s, width, breaklong)
11499 s = s:gsub('\n',' ') -- remove line breaks
11500 s = stringx.strip(s) -- remove leading/trailing whitespace
11501 if s == "" then
11502 return { "" }
11503 end
11504 width = width or 70
11505 local out = {}
11506 local words = usplit(s, "%s")
11507 while words[1] do
11508 out[#out+1], words = buildline(words, width, breaklong)
11509 end
11510 return makelist(out)
11511 end
11512 end
11513
11514 --- format a paragraph so that it fits into a line width.
11515 -- @tparam string s the string to format
11516 -- @tparam[opt=70] integer width the margin width
11517 -- @tparam[opt=false] boolean breaklong if truthy, words longer than the width given will be forced split.
11518 -- @return a string, use `wrap` to return a list of lines instead of a string.
11519 -- @see wrap
11520 function stringx.fill (s,width,breaklong)
11521 return concat(stringx.wrap(s,width,breaklong),'\n') .. '\n'
11522 end
11523
11524 --- Template
11525 -- @section Template
11526
11527
11528 local function _substitute(s,tbl,safe)
11529 local subst
11530 if is_callable(tbl) then
11531 subst = tbl
11532 else
11533 function subst(f)
11534 local s = tbl[f]
11535 if not s then
11536 if safe then
11537 return f
11538 else
11539 error("not present in table "..f)
11540 end
11541 else
11542 return s
11543 end
11544 end
11545 end
11546 local res = gsub(s,'%${([%w_]+)}',subst)
11547 return (gsub(res,'%$([%w_]+)',subst))
11548 end
11549
11550
11551
11552 local Template = {}
11553 stringx.Template = Template
11554 Template.__index = Template
11555 setmetatable(Template, {
11556 __call = function(obj,tmpl)
11557 return Template.new(tmpl)
11558 end
11559 })
11560
11561 --- Creates a new Template class.
11562 -- This is a shortcut to `Template.new(tmpl)`.
11563 -- @tparam string tmpl the template string
11564 -- @function Template
11565 -- @treturn Template
11566 function Template.new(tmpl)
11567 assert_arg(1,tmpl,'string')
11568 local res = {}
11569 res.tmpl = tmpl
11570 setmetatable(res,Template)
11571 return res
11572 end
11573
11574 --- substitute values into a template, throwing an error.
11575 -- This will throw an error if no name is found.
11576 -- @tparam table tbl a table of name-value pairs.
11577 -- @return string with place holders substituted
11578 function Template:substitute(tbl)
11579 assert_arg(1,tbl,'table')
11580 return _substitute(self.tmpl,tbl,false)
11581 end
11582
11583 --- substitute values into a template.
11584 -- This version just passes unknown names through.
11585 -- @tparam table tbl a table of name-value pairs.
11586 -- @return string with place holders substituted
11587 function Template:safe_substitute(tbl)
11588 assert_arg(1,tbl,'table')
11589 return _substitute(self.tmpl,tbl,true)
11590 end
11591
11592 --- substitute values into a template, preserving indentation. <br>
11593 -- If the value is a multiline string _or_ a template, it will insert
11594 -- the lines at the correct indentation. <br>
11595 -- Furthermore, if a template, then that template will be substituted
11596 -- using the same table.
11597 -- @tparam table tbl a table of name-value pairs.
11598 -- @return string with place holders substituted
11599 function Template:indent_substitute(tbl)
11600 assert_arg(1,tbl,'table')
11601 if not self.strings then
11602 self.strings = usplit(self.tmpl,'\n')
11603 end
11604
11605 -- the idea is to substitute line by line, grabbing any spaces as
11606 -- well as the $var. If the value to be substituted contains newlines,
11607 -- then we split that into lines and adjust the indent before inserting.
11608 local function subst(line)
11609 return line:gsub('(%s*)%$([%w_]+)',function(sp,f)
11610 local subtmpl
11611 local s = tbl[f]
11612 if not s then error("not present in table "..f) end
11613 if getmetatable(s) == Template then
11614 subtmpl = s
11615 s = s.tmpl
11616 else
11617 s = tostring(s)
11618 end
11619 if s:find '\n' then
11620 local lines = usplit(s, '\n')
11621 for i, line in ipairs(lines) do
11622 lines[i] = sp..line
11623 end
11624 s = concat(lines, '\n') .. '\n'
11625 end
11626 if subtmpl then
11627 return _substitute(s, tbl)
11628 else
11629 return s
11630 end
11631 end)
11632 end
11633
11634 local lines = {}
11635 for i, line in ipairs(self.strings) do
11636 lines[i] = subst(line)
11637 end
11638 return concat(lines,'\n')..'\n'
11639 end
11640
11641
11642
11643 --- Miscellaneous
11644 -- @section misc
11645
11646 --- return an iterator over all lines in a string
11647 -- @string s the string
11648 -- @return an iterator
11649 -- @usage
11650 -- local line_no = 1
11651 -- for line in stringx.lines(some_text) do
11652 -- print(line_no, line)
11653 -- line_no = line_no + 1
11654 -- end
11655 function stringx.lines(s)
11656 assert_string(1,s)
11657 if not s:find '\n$' then s = s..'\n' end
11658 return s:gmatch('([^\n]*)\n')
11659 end
11660
11661 --- initial word letters uppercase ('title case').
11662 -- Here 'words' mean chunks of non-space characters.
11663 -- @string s the string
11664 -- @return a string with each word's first letter uppercase
11665 -- @usage stringx.title("hello world") == "Hello World")
11666 function stringx.title(s)
11667 assert_string(1,s)
11668 return (s:gsub('(%S)(%S*)',function(f,r)
11669 return f:upper()..r:lower()
11670 end))
11671 end
11672
11673 stringx.capitalize = stringx.title
11674
11675 do
11676 local ellipsis = '...'
11677 local n_ellipsis = #ellipsis
11678
11679 --- Return a shortened version of a string.
11680 -- Fits string within w characters. Removed characters are marked with ellipsis.
11681 -- @string s the string
11682 -- @int w the maximum size allowed
11683 -- @bool tail true if we want to show the end of the string (head otherwise)
11684 -- @usage ('1234567890'):shorten(8) == '12345...'
11685 -- @usage ('1234567890'):shorten(8, true) == '...67890'
11686 -- @usage ('1234567890'):shorten(20) == '1234567890'
11687 function stringx.shorten(s,w,tail)
11688 assert_string(1,s)
11689 if #s > w then
11690 if w < n_ellipsis then return ellipsis:sub(1,w) end
11691 if tail then
11692 local i = #s - w + 1 + n_ellipsis
11693 return ellipsis .. s:sub(i)
11694 else
11695 return s:sub(1,w-n_ellipsis) .. ellipsis
11696 end
11697 end
11698 return s
11699 end
11700 end
11701
11702
11703 do
11704 -- Utility function that finds any patterns that match a long string's an open or close.
11705 -- Note that having this function use the least number of equal signs that is possible is a harder algorithm to come up with.
11706 -- Right now, it simply returns the greatest number of them found.
11707 -- @param s The string
11708 -- @return 'nil' if not found. If found, the maximum number of equal signs found within all matches.
11709 local function has_lquote(s)
11710 local lstring_pat = '([%[%]])(=*)%1'
11711 local equals, new_equals, _
11712 local finish = 1
11713 repeat
11714 _, finish, _, new_equals = s:find(lstring_pat, finish)
11715 if new_equals then
11716 equals = max(equals or 0, #new_equals)
11717 end
11718 until not new_equals
11719
11720 return equals
11721 end
11722
11723 --- Quote the given string and preserve any control or escape characters, such that reloading the string in Lua returns the same result.
11724 -- @param s The string to be quoted.
11725 -- @return The quoted string.
11726 function stringx.quote_string(s)
11727 assert_string(1,s)
11728 -- Find out if there are any embedded long-quote sequences that may cause issues.
11729 -- This is important when strings are embedded within strings, like when serializing.
11730 -- Append a closing bracket to catch unfinished long-quote sequences at the end of the string.
11731 local equal_signs = has_lquote(s .. "]")
11732
11733 -- Note that strings containing "\r" can't be quoted using long brackets
11734 -- as Lua lexer converts all newlines to "\n" within long strings.
11735 if (s:find("\n") or equal_signs) and not s:find("\r") then
11736 -- If there is an embedded sequence that matches a long quote, then
11737 -- find the one with the maximum number of = signs and add one to that number.
11738 equal_signs = ("="):rep((equal_signs or -1) + 1)
11739 -- Long strings strip out leading newline. We want to retain that, when quoting.
11740 if s:find("^\n") then s = "\n" .. s end
11741 local lbracket, rbracket =
11742 "[" .. equal_signs .. "[",
11743 "]" .. equal_signs .. "]"
11744 s = lbracket .. s .. rbracket
11745 else
11746 -- Escape funny stuff. Lua 5.1 does not handle "\r" correctly.
11747 s = ("%q"):format(s):gsub("\r", "\\r")
11748 end
11749 return s
11750 end
11751 end
11752
11753
11754 --- Python-style formatting operator.
11755 -- Calling `text.format_operator()` overloads the % operator for strings to give
11756 -- Python/Ruby style formatted output.
11757 -- This is extended to also do template-like substitution for map-like data.
11758 --
11759 -- Note this goes further than the original, and will allow these cases:
11760 --
11761 -- 1. a single value
11762 -- 2. a list of values
11763 -- 3. a map of var=value pairs
11764 -- 4. a function, as in gsub
11765 --
11766 -- For the second two cases, it uses $-variable substitution.
11767 --
11768 -- When called, this function will monkey-patch the global `string` metatable by
11769 -- adding a `__mod` method.
11770 --
11771 -- See <a href="http://lua-users.org/wiki/StringInterpolation">the lua-users wiki</a>
11772 --
11773 -- @usage
11774 -- require 'pl.text'.format_operator()
11775 -- local out1 = '%s = %5.3f' % {'PI',math.pi} --> 'PI = 3.142'
11776 -- local out2 = '$name = $value' % {name='dog',value='Pluto'} --> 'dog = Pluto'
11777 function stringx.format_operator()
11778
11779 local format = string.format
11780
11781 -- a more forgiving version of string.format, which applies
11782 -- tostring() to any value with a %s format.
11783 local function formatx (fmt,...)
11784 local args = pack(...)
11785 local i = 1
11786 for p in fmt:gmatch('%%.') do
11787 if p == '%s' and type(args[i]) ~= 'string' then
11788 args[i] = tostring(args[i])
11789 end
11790 i = i + 1
11791 end
11792 return format(fmt,unpack(args))
11793 end
11794
11795 local function basic_subst(s,t)
11796 return (s:gsub('%$([%w_]+)',t))
11797 end
11798
11799 getmetatable("").__mod = function(a, b)
11800 if b == nil then
11801 return a
11802 elseif type(b) == "table" and getmetatable(b) == nil then
11803 if #b == 0 then -- assume a map-like table
11804 return _substitute(a,b,true)
11805 else
11806 return formatx(a,unpack(b))
11807 end
11808 elseif type(b) == 'function' then
11809 return basic_subst(a,b)
11810 else
11811 return formatx(a,b)
11812 end
11813 end
11814 end
11815
11816 --- import the stringx functions into the global string (meta)table
11817 function stringx.import()
11818 utils.import(stringx,string)
11819 end
11820
11821 return stringx
11822
11823 end,
11824
11825 ["pl.tablex"] = function()
11826 --------------------
11827 -- Module: 'pl.tablex'
11828 --------------------
11829 --- Extended operations on Lua tables.
11830 --
11831 -- See @{02-arrays.md.Useful_Operations_on_Tables|the Guide}
11832 --
11833 -- Dependencies: `pl.utils`, `pl.types`
11834 -- @module pl.tablex
11835 local utils = require ('pl.utils')
11836 local types = require ('pl.types')
11837 local getmetatable,setmetatable,require = getmetatable,setmetatable,require
11838 local tsort,append,remove = table.sort,table.insert,table.remove
11839 local min = math.min
11840 local pairs,type,unpack,select,tostring = pairs,type,utils.unpack,select,tostring
11841 local function_arg = utils.function_arg
11842 local assert_arg = utils.assert_arg
11843
11844 local tablex = {}
11845
11846 -- generally, functions that make copies of tables try to preserve the metatable.
11847 -- However, when the source has no obvious type, then we attach appropriate metatables
11848 -- like List, Map, etc to the result.
11849 local function setmeta (res,tbl,pl_class)
11850 local mt = getmetatable(tbl) or pl_class and require('pl.' .. pl_class)
11851 return mt and setmetatable(res, mt) or res
11852 end
11853
11854 local function makelist(l)
11855 return setmetatable(l, require('pl.List'))
11856 end
11857
11858 local function makemap(m)
11859 return setmetatable(m, require('pl.Map'))
11860 end
11861
11862 local function complain (idx,msg)
11863 error(('argument %d is not %s'):format(idx,msg),3)
11864 end
11865
11866 local function assert_arg_indexable (idx,val)
11867 if not types.is_indexable(val) then
11868 complain(idx,"indexable")
11869 end
11870 end
11871
11872 local function assert_arg_iterable (idx,val)
11873 if not types.is_iterable(val) then
11874 complain(idx,"iterable")
11875 end
11876 end
11877
11878 local function assert_arg_writeable (idx,val)
11879 if not types.is_writeable(val) then
11880 complain(idx,"writeable")
11881 end
11882 end
11883
11884 --- copy a table into another, in-place.
11885 -- @within Copying
11886 -- @tab t1 destination table
11887 -- @tab t2 source (actually any iterable object)
11888 -- @return first table
11889 function tablex.update (t1,t2)
11890 assert_arg_writeable(1,t1)
11891 assert_arg_iterable(2,t2)
11892 for k,v in pairs(t2) do
11893 t1[k] = v
11894 end
11895 return t1
11896 end
11897
11898 --- total number of elements in this table.
11899 -- Note that this is distinct from `#t`, which is the number
11900 -- of values in the array part; this value will always
11901 -- be greater or equal. The difference gives the size of
11902 -- the hash part, for practical purposes. Works for any
11903 -- object with a __pairs metamethod.
11904 -- @tab t a table
11905 -- @return the size
11906 function tablex.size (t)
11907 assert_arg_iterable(1,t)
11908 local i = 0
11909 for k in pairs(t) do i = i + 1 end
11910 return i
11911 end
11912
11913 --- make a shallow copy of a table
11914 -- @within Copying
11915 -- @tab t an iterable source
11916 -- @return new table
11917 function tablex.copy (t)
11918 assert_arg_iterable(1,t)
11919 local res = {}
11920 for k,v in pairs(t) do
11921 res[k] = v
11922 end
11923 return res
11924 end
11925
11926 local function cycle_aware_copy(t, cache)
11927 if type(t) ~= 'table' then return t end
11928 if cache[t] then return cache[t] end
11929 assert_arg_iterable(1,t)
11930 local res = {}
11931 cache[t] = res
11932 local mt = getmetatable(t)
11933 for k,v in pairs(t) do
11934 k = cycle_aware_copy(k, cache)
11935 v = cycle_aware_copy(v, cache)
11936 res[k] = v
11937 end
11938 setmetatable(res,mt)
11939 return res
11940 end
11941
11942 --- make a deep copy of a table, recursively copying all the keys and fields.
11943 -- This supports cycles in tables; cycles will be reproduced in the copy.
11944 -- This will also set the copied table's metatable to that of the original.
11945 -- @within Copying
11946 -- @tab t A table
11947 -- @return new table
11948 function tablex.deepcopy(t)
11949 return cycle_aware_copy(t,{})
11950 end
11951
11952 local abs = math.abs
11953
11954 local function cycle_aware_compare(t1,t2,ignore_mt,eps,cache)
11955 if cache[t1] and cache[t1][t2] then return true end
11956 local ty1 = type(t1)
11957 local ty2 = type(t2)
11958 if ty1 ~= ty2 then return false end
11959 -- non-table types can be directly compared
11960 if ty1 ~= 'table' then
11961 if ty1 == 'number' and eps then return abs(t1-t2) < eps end
11962 return t1 == t2
11963 end
11964 -- as well as tables which have the metamethod __eq
11965 local mt = getmetatable(t1)
11966 if not ignore_mt and mt and mt.__eq then return t1 == t2 end
11967 for k1 in pairs(t1) do
11968 if t2[k1]==nil then return false end
11969 end
11970 for k2 in pairs(t2) do
11971 if t1[k2]==nil then return false end
11972 end
11973 cache[t1] = cache[t1] or {}
11974 cache[t1][t2] = true
11975 for k1,v1 in pairs(t1) do
11976 local v2 = t2[k1]
11977 if not cycle_aware_compare(v1,v2,ignore_mt,eps,cache) then return false end
11978 end
11979 return true
11980 end
11981
11982 --- compare two values.
11983 -- if they are tables, then compare their keys and fields recursively.
11984 -- @within Comparing
11985 -- @param t1 A value
11986 -- @param t2 A value
11987 -- @bool[opt] ignore_mt if true, ignore __eq metamethod (default false)
11988 -- @number[opt] eps if defined, then used for any number comparisons
11989 -- @return true or false
11990 function tablex.deepcompare(t1,t2,ignore_mt,eps)
11991 return cycle_aware_compare(t1,t2,ignore_mt,eps,{})
11992 end
11993
11994 --- compare two arrays using a predicate.
11995 -- @within Comparing
11996 -- @array t1 an array
11997 -- @array t2 an array
11998 -- @func cmp A comparison function; `bool = cmp(t1_value, t2_value)`
11999 -- @return true or false
12000 -- @usage
12001 -- assert(tablex.compare({ 1, 2, 3 }, { 1, 2, 3 }, "=="))
12002 --
12003 -- assert(tablex.compare(
12004 -- {1,2,3, hello = "world"}, -- fields are not compared!
12005 -- {1,2,3}, function(v1, v2) return v1 == v2 end)
12006 function tablex.compare (t1,t2,cmp)
12007 assert_arg_indexable(1,t1)
12008 assert_arg_indexable(2,t2)
12009 if #t1 ~= #t2 then return false end
12010 cmp = function_arg(3,cmp)
12011 for k = 1,#t1 do
12012 if not cmp(t1[k],t2[k]) then return false end
12013 end
12014 return true
12015 end
12016
12017 --- compare two list-like tables using an optional predicate, without regard for element order.
12018 -- @within Comparing
12019 -- @array t1 a list-like table
12020 -- @array t2 a list-like table
12021 -- @param cmp A comparison function (may be nil)
12022 function tablex.compare_no_order (t1,t2,cmp)
12023 assert_arg_indexable(1,t1)
12024 assert_arg_indexable(2,t2)
12025 if cmp then cmp = function_arg(3,cmp) end
12026 if #t1 ~= #t2 then return false end
12027 local visited = {}
12028 for i = 1,#t1 do
12029 local val = t1[i]
12030 local gotcha
12031 for j = 1,#t2 do
12032 if not visited[j] then
12033 local match
12034 if cmp then match = cmp(val,t2[j]) else match = val == t2[j] end
12035 if match then
12036 gotcha = j
12037 break
12038 end
12039 end
12040 end
12041 if not gotcha then return false end
12042 visited[gotcha] = true
12043 end
12044 return true
12045 end
12046
12047
12048 --- return the index of a value in a list.
12049 -- Like string.find, there is an optional index to start searching,
12050 -- which can be negative.
12051 -- @within Finding
12052 -- @array t A list-like table
12053 -- @param val A value
12054 -- @int idx index to start; -1 means last element,etc (default 1)
12055 -- @return index of value or nil if not found
12056 -- @usage find({10,20,30},20) == 2
12057 -- @usage find({'a','b','a','c'},'a',2) == 3
12058 function tablex.find(t,val,idx)
12059 assert_arg_indexable(1,t)
12060 idx = idx or 1
12061 if idx < 0 then idx = #t + idx + 1 end
12062 for i = idx,#t do
12063 if t[i] == val then return i end
12064 end
12065 return nil
12066 end
12067
12068 --- return the index of a value in a list, searching from the end.
12069 -- Like string.find, there is an optional index to start searching,
12070 -- which can be negative.
12071 -- @within Finding
12072 -- @array t A list-like table
12073 -- @param val A value
12074 -- @param idx index to start; -1 means last element,etc (default `#t`)
12075 -- @return index of value or nil if not found
12076 -- @usage rfind({10,10,10},10) == 3
12077 function tablex.rfind(t,val,idx)
12078 assert_arg_indexable(1,t)
12079 idx = idx or #t
12080 if idx < 0 then idx = #t + idx + 1 end
12081 for i = idx,1,-1 do
12082 if t[i] == val then return i end
12083 end
12084 return nil
12085 end
12086
12087
12088 --- return the index (or key) of a value in a table using a comparison function.
12089 --
12090 -- *NOTE*: the 2nd return value of this function, the value returned
12091 -- by the comparison function, has a limitation that it cannot be `false`.
12092 -- Because if it is, then it indicates the comparison failed, and the
12093 -- function will continue the search. See examples.
12094 -- @within Finding
12095 -- @tab t A table
12096 -- @func cmp A comparison function
12097 -- @param arg an optional second argument to the function
12098 -- @return index of value, or nil if not found
12099 -- @return value returned by comparison function (cannot be `false`!)
12100 -- @usage
12101 -- -- using an operator
12102 -- local lst = { "Rudolph", true, false, 15 }
12103 -- local idx, cmp_result = tablex.rfind(lst, "==", "Rudolph")
12104 -- assert(idx == 1)
12105 -- assert(cmp_result == true)
12106 --
12107 -- local idx, cmp_result = tablex.rfind(lst, "==", false)
12108 -- assert(idx == 3)
12109 -- assert(cmp_result == true) -- looking up 'false' works!
12110 --
12111 -- -- using a function returning the value looked up
12112 -- local cmp = function(v1, v2) return v1 == v2 and v2 end
12113 -- local idx, cmp_result = tablex.rfind(lst, cmp, "Rudolph")
12114 -- assert(idx == 1)
12115 -- assert(cmp_result == "Rudolph") -- the value is returned
12116 --
12117 -- -- NOTE: this fails, since 'false' cannot be returned!
12118 -- local idx, cmp_result = tablex.rfind(lst, cmp, false)
12119 -- assert(idx == nil) -- looking up 'false' failed!
12120 -- assert(cmp_result == nil)
12121 function tablex.find_if(t,cmp,arg)
12122 assert_arg_iterable(1,t)
12123 cmp = function_arg(2,cmp)
12124 for k,v in pairs(t) do
12125 local c = cmp(v,arg)
12126 if c then return k,c end
12127 end
12128 return nil
12129 end
12130
12131 --- return a list of all values in a table indexed by another list.
12132 -- @tab tbl a table
12133 -- @array idx an index table (a list of keys)
12134 -- @return a list-like table
12135 -- @usage index_by({10,20,30,40},{2,4}) == {20,40}
12136 -- @usage index_by({one=1,two=2,three=3},{'one','three'}) == {1,3}
12137 function tablex.index_by(tbl,idx)
12138 assert_arg_indexable(1,tbl)
12139 assert_arg_indexable(2,idx)
12140 local res = {}
12141 for i = 1,#idx do
12142 res[i] = tbl[idx[i]]
12143 end
12144 return setmeta(res,tbl,'List')
12145 end
12146
12147 --- apply a function to all values of a table.
12148 -- This returns a table of the results.
12149 -- Any extra arguments are passed to the function.
12150 -- @within MappingAndFiltering
12151 -- @func fun A function that takes at least one argument
12152 -- @tab t A table
12153 -- @param ... optional arguments
12154 -- @usage map(function(v) return v*v end, {10,20,30,fred=2}) is {100,400,900,fred=4}
12155 function tablex.map(fun,t,...)
12156 assert_arg_iterable(1,t)
12157 fun = function_arg(1,fun)
12158 local res = {}
12159 for k,v in pairs(t) do
12160 res[k] = fun(v,...)
12161 end
12162 return setmeta(res,t)
12163 end
12164
12165 --- apply a function to all values of a list.
12166 -- This returns a table of the results.
12167 -- Any extra arguments are passed to the function.
12168 -- @within MappingAndFiltering
12169 -- @func fun A function that takes at least one argument
12170 -- @array t a table (applies to array part)
12171 -- @param ... optional arguments
12172 -- @return a list-like table
12173 -- @usage imap(function(v) return v*v end, {10,20,30,fred=2}) is {100,400,900}
12174 function tablex.imap(fun,t,...)
12175 assert_arg_indexable(1,t)
12176 fun = function_arg(1,fun)
12177 local res = {}
12178 for i = 1,#t do
12179 res[i] = fun(t[i],...) or false
12180 end
12181 return setmeta(res,t,'List')
12182 end
12183
12184 --- apply a named method to values from a table.
12185 -- @within MappingAndFiltering
12186 -- @string name the method name
12187 -- @array t a list-like table
12188 -- @param ... any extra arguments to the method
12189 -- @return a `List` with the results of the method (1st result only)
12190 -- @usage
12191 -- local Car = {}
12192 -- Car.__index = Car
12193 -- function Car.new(car)
12194 -- return setmetatable(car or {}, Car)
12195 -- end
12196 -- Car.speed = 0
12197 -- function Car:faster(increase)
12198 -- self.speed = self.speed + increase
12199 -- return self.speed
12200 -- end
12201 --
12202 -- local ferrari = Car.new{ name = "Ferrari" }
12203 -- local lamborghini = Car.new{ name = "Lamborghini", speed = 50 }
12204 -- local cars = { ferrari, lamborghini }
12205 --
12206 -- assert(ferrari.speed == 0)
12207 -- assert(lamborghini.speed == 50)
12208 -- tablex.map_named_method("faster", cars, 10)
12209 -- assert(ferrari.speed == 10)
12210 -- assert(lamborghini.speed == 60)
12211 function tablex.map_named_method (name,t,...)
12212 utils.assert_string(1,name)
12213 assert_arg_indexable(2,t)
12214 local res = {}
12215 for i = 1,#t do
12216 local val = t[i]
12217 local fun = val[name]
12218 res[i] = fun(val,...)
12219 end
12220 return setmeta(res,t,'List')
12221 end
12222
12223 --- apply a function to all values of a table, in-place.
12224 -- Any extra arguments are passed to the function.
12225 -- @func fun A function that takes at least one argument
12226 -- @tab t a table
12227 -- @param ... extra arguments passed to `fun`
12228 -- @see tablex.foreach
12229 function tablex.transform (fun,t,...)
12230 assert_arg_iterable(1,t)
12231 fun = function_arg(1,fun)
12232 for k,v in pairs(t) do
12233 t[k] = fun(v,...)
12234 end
12235 end
12236
12237 --- generate a table of all numbers in a range.
12238 -- This is consistent with a numerical for loop.
12239 -- @int start number
12240 -- @int finish number
12241 -- @int[opt=1] step make this negative for start < finish
12242 function tablex.range (start,finish,step)
12243 local res
12244 step = step or 1
12245 if start == finish then
12246 res = {start}
12247 elseif (start > finish and step > 0) or (finish > start and step < 0) then
12248 res = {}
12249 else
12250 local k = 1
12251 res = {}
12252 for i=start,finish,step do res[k]=i; k=k+1 end
12253 end
12254 return makelist(res)
12255 end
12256
12257 --- apply a function to values from two tables.
12258 -- @within MappingAndFiltering
12259 -- @func fun a function of at least two arguments
12260 -- @tab t1 a table
12261 -- @tab t2 a table
12262 -- @param ... extra arguments
12263 -- @return a table
12264 -- @usage map2('+',{1,2,3,m=4},{10,20,30,m=40}) is {11,22,23,m=44}
12265 function tablex.map2 (fun,t1,t2,...)
12266 assert_arg_iterable(1,t1)
12267 assert_arg_iterable(2,t2)
12268 fun = function_arg(1,fun)
12269 local res = {}
12270 for k,v in pairs(t1) do
12271 res[k] = fun(v,t2[k],...)
12272 end
12273 return setmeta(res,t1,'List')
12274 end
12275
12276 --- apply a function to values from two arrays.
12277 -- The result will be the length of the shortest array.
12278 -- @within MappingAndFiltering
12279 -- @func fun a function of at least two arguments
12280 -- @array t1 a list-like table
12281 -- @array t2 a list-like table
12282 -- @param ... extra arguments
12283 -- @usage imap2('+',{1,2,3,m=4},{10,20,30,m=40}) is {11,22,23}
12284 function tablex.imap2 (fun,t1,t2,...)
12285 assert_arg_indexable(2,t1)
12286 assert_arg_indexable(3,t2)
12287 fun = function_arg(1,fun)
12288 local res,n = {},math.min(#t1,#t2)
12289 for i = 1,n do
12290 res[i] = fun(t1[i],t2[i],...)
12291 end
12292 return res
12293 end
12294
12295 --- 'reduce' a list using a binary function.
12296 -- @func fun a function of two arguments
12297 -- @array t a list-like table
12298 -- @array memo optional initial memo value. Defaults to first value in table.
12299 -- @return the result of the function
12300 -- @usage reduce('+',{1,2,3,4}) == 10
12301 function tablex.reduce (fun,t,memo)
12302 assert_arg_indexable(2,t)
12303 fun = function_arg(1,fun)
12304 local n = #t
12305 if n == 0 then
12306 return memo
12307 end
12308 local res = memo and fun(memo, t[1]) or t[1]
12309 for i = 2,n do
12310 res = fun(res,t[i])
12311 end
12312 return res
12313 end
12314
12315 --- apply a function to all elements of a table.
12316 -- The arguments to the function will be the value,
12317 -- the key and _finally_ any extra arguments passed to this function.
12318 -- Note that the Lua 5.0 function table.foreach passed the _key_ first.
12319 -- @within Iterating
12320 -- @tab t a table
12321 -- @func fun a function on the elements; `function(value, key, ...)`
12322 -- @param ... extra arguments passed to `fun`
12323 -- @see tablex.transform
12324 function tablex.foreach(t,fun,...)
12325 assert_arg_iterable(1,t)
12326 fun = function_arg(2,fun)
12327 for k,v in pairs(t) do
12328 fun(v,k,...)
12329 end
12330 end
12331
12332 --- apply a function to all elements of a list-like table in order.
12333 -- The arguments to the function will be the value,
12334 -- the index and _finally_ any extra arguments passed to this function
12335 -- @within Iterating
12336 -- @array t a table
12337 -- @func fun a function with at least one argument
12338 -- @param ... optional arguments
12339 function tablex.foreachi(t,fun,...)
12340 assert_arg_indexable(1,t)
12341 fun = function_arg(2,fun)
12342 for i = 1,#t do
12343 fun(t[i],i,...)
12344 end
12345 end
12346
12347 --- Apply a function to a number of tables.
12348 -- A more general version of map
12349 -- The result is a table containing the result of applying that function to the
12350 -- ith value of each table. Length of output list is the minimum length of all the lists
12351 -- @within MappingAndFiltering
12352 -- @func fun a function of n arguments
12353 -- @tab ... n tables
12354 -- @usage mapn(function(x,y,z) return x+y+z end, {1,2,3},{10,20,30},{100,200,300}) is {111,222,333}
12355 -- @usage mapn(math.max, {1,20,300},{10,2,3},{100,200,100}) is {100,200,300}
12356 -- @param fun A function that takes as many arguments as there are tables
12357 function tablex.mapn(fun,...)
12358 fun = function_arg(1,fun)
12359 local res = {}
12360 local lists = {...}
12361 local minn = 1e40
12362 for i = 1,#lists do
12363 minn = min(minn,#(lists[i]))
12364 end
12365 for i = 1,minn do
12366 local args,k = {},1
12367 for j = 1,#lists do
12368 args[k] = lists[j][i]
12369 k = k + 1
12370 end
12371 res[#res+1] = fun(unpack(args))
12372 end
12373 return res
12374 end
12375
12376 --- call the function with the key and value pairs from a table.
12377 -- The function can return a value and a key (note the order!). If both
12378 -- are not nil, then this pair is inserted into the result: if the key already exists, we convert the value for that
12379 -- key into a table and append into it. If only value is not nil, then it is appended to the result.
12380 -- @within MappingAndFiltering
12381 -- @func fun A function which will be passed each key and value as arguments, plus any extra arguments to pairmap.
12382 -- @tab t A table
12383 -- @param ... optional arguments
12384 -- @usage pairmap(function(k,v) return v end,{fred=10,bonzo=20}) is {10,20} _or_ {20,10}
12385 -- @usage pairmap(function(k,v) return {k,v},k end,{one=1,two=2}) is {one={'one',1},two={'two',2}}
12386 function tablex.pairmap(fun,t,...)
12387 assert_arg_iterable(1,t)
12388 fun = function_arg(1,fun)
12389 local res = {}
12390 for k,v in pairs(t) do
12391 local rv,rk = fun(k,v,...)
12392 if rk then
12393 if res[rk] then
12394 if type(res[rk]) == 'table' then
12395 table.insert(res[rk],rv)
12396 else
12397 res[rk] = {res[rk], rv}
12398 end
12399 else
12400 res[rk] = rv
12401 end
12402 else
12403 res[#res+1] = rv
12404 end
12405 end
12406 return res
12407 end
12408
12409 local function keys_op(i,v) return i end
12410
12411 --- return all the keys of a table in arbitrary order.
12412 -- @within Extraction
12413 -- @tab t A list-like table where the values are the keys of the input table
12414 function tablex.keys(t)
12415 assert_arg_iterable(1,t)
12416 return makelist(tablex.pairmap(keys_op,t))
12417 end
12418
12419 local function values_op(i,v) return v end
12420
12421 --- return all the values of the table in arbitrary order
12422 -- @within Extraction
12423 -- @tab t A list-like table where the values are the values of the input table
12424 function tablex.values(t)
12425 assert_arg_iterable(1,t)
12426 return makelist(tablex.pairmap(values_op,t))
12427 end
12428
12429 local function index_map_op (i,v) return i,v end
12430
12431 --- create an index map from a list-like table. The original values become keys,
12432 -- and the associated values are the indices into the original list.
12433 -- @array t a list-like table
12434 -- @return a map-like table
12435 function tablex.index_map (t)
12436 assert_arg_indexable(1,t)
12437 return makemap(tablex.pairmap(index_map_op,t))
12438 end
12439
12440 local function set_op(i,v) return true,v end
12441
12442 --- create a set from a list-like table. A set is a table where the original values
12443 -- become keys, and the associated values are all true.
12444 -- @array t a list-like table
12445 -- @return a set (a map-like table)
12446 function tablex.makeset (t)
12447 assert_arg_indexable(1,t)
12448 return setmetatable(tablex.pairmap(set_op,t),require('pl.Set'))
12449 end
12450
12451 --- combine two tables, either as union or intersection. Corresponds to
12452 -- set operations for sets () but more general. Not particularly
12453 -- useful for list-like tables.
12454 -- @within Merging
12455 -- @tab t1 a table
12456 -- @tab t2 a table
12457 -- @bool dup true for a union, false for an intersection.
12458 -- @usage merge({alice=23,fred=34},{bob=25,fred=34}) is {fred=34}
12459 -- @usage merge({alice=23,fred=34},{bob=25,fred=34},true) is {bob=25,fred=34,alice=23}
12460 -- @see tablex.index_map
12461 function tablex.merge (t1,t2,dup)
12462 assert_arg_iterable(1,t1)
12463 assert_arg_iterable(2,t2)
12464 local res = {}
12465 for k,v in pairs(t1) do
12466 if dup or t2[k] then res[k] = v end
12467 end
12468 if dup then
12469 for k,v in pairs(t2) do
12470 res[k] = v
12471 end
12472 end
12473 return setmeta(res,t1,'Map')
12474 end
12475
12476 --- the union of two map-like tables.
12477 -- If there are duplicate keys, the second table wins.
12478 -- @tab t1 a table
12479 -- @tab t2 a table
12480 -- @treturn tab
12481 -- @see tablex.merge
12482 function tablex.union(t1, t2)
12483 return tablex.merge(t1, t2, true)
12484 end
12485
12486 --- the intersection of two map-like tables.
12487 -- @tab t1 a table
12488 -- @tab t2 a table
12489 -- @treturn tab
12490 -- @see tablex.merge
12491 function tablex.intersection(t1, t2)
12492 return tablex.merge(t1, t2, false)
12493 end
12494
12495 --- a new table which is the difference of two tables.
12496 -- With sets (where the values are all true) this is set difference and
12497 -- symmetric difference depending on the third parameter.
12498 -- @within Merging
12499 -- @tab s1 a map-like table or set
12500 -- @tab s2 a map-like table or set
12501 -- @bool symm symmetric difference (default false)
12502 -- @return a map-like table or set
12503 function tablex.difference (s1,s2,symm)
12504 assert_arg_iterable(1,s1)
12505 assert_arg_iterable(2,s2)
12506 local res = {}
12507 for k,v in pairs(s1) do
12508 if s2[k] == nil then res[k] = v end
12509 end
12510 if symm then
12511 for k,v in pairs(s2) do
12512 if s1[k] == nil then res[k] = v end
12513 end
12514 end
12515 return setmeta(res,s1,'Map')
12516 end
12517
12518 --- A table where the key/values are the values and value counts of the table.
12519 -- @array t a list-like table
12520 -- @func cmp a function that defines equality (otherwise uses ==)
12521 -- @return a map-like table
12522 -- @see seq.count_map
12523 function tablex.count_map (t,cmp)
12524 assert_arg_indexable(1,t)
12525 local res,mask = {},{}
12526 cmp = function_arg(2,cmp or '==')
12527 local n = #t
12528 for i = 1,#t do
12529 local v = t[i]
12530 if not mask[v] then
12531 mask[v] = true
12532 -- check this value against all other values
12533 res[v] = 1 -- there's at least one instance
12534 for j = i+1,n do
12535 local w = t[j]
12536 local ok = cmp(v,w)
12537 if ok then
12538 res[v] = res[v] + 1
12539 mask[w] = true
12540 end
12541 end
12542 end
12543 end
12544 return makemap(res)
12545 end
12546
12547 --- filter an array's values using a predicate function
12548 -- @within MappingAndFiltering
12549 -- @array t a list-like table
12550 -- @func pred a boolean function
12551 -- @param arg optional argument to be passed as second argument of the predicate
12552 function tablex.filter (t,pred,arg)
12553 assert_arg_indexable(1,t)
12554 pred = function_arg(2,pred)
12555 local res,k = {},1
12556 for i = 1,#t do
12557 local v = t[i]
12558 if pred(v,arg) then
12559 res[k] = v
12560 k = k + 1
12561 end
12562 end
12563 return setmeta(res,t,'List')
12564 end
12565
12566 --- return a table where each element is a table of the ith values of an arbitrary
12567 -- number of tables. It is equivalent to a matrix transpose.
12568 -- @within Merging
12569 -- @usage zip({10,20,30},{100,200,300}) is {{10,100},{20,200},{30,300}}
12570 -- @array ... arrays to be zipped
12571 function tablex.zip(...)
12572 return tablex.mapn(function(...) return {...} end,...)
12573 end
12574
12575 local _copy
12576 function _copy (dest,src,idest,isrc,nsrc,clean_tail)
12577 idest = idest or 1
12578 isrc = isrc or 1
12579 local iend
12580 if not nsrc then
12581 nsrc = #src
12582 iend = #src
12583 else
12584 iend = isrc + min(nsrc-1,#src-isrc)
12585 end
12586 if dest == src then -- special case
12587 if idest > isrc and iend >= idest then -- overlapping ranges
12588 src = tablex.sub(src,isrc,nsrc)
12589 isrc = 1; iend = #src
12590 end
12591 end
12592 for i = isrc,iend do
12593 dest[idest] = src[i]
12594 idest = idest + 1
12595 end
12596 if clean_tail then
12597 tablex.clear(dest,idest)
12598 end
12599 return dest
12600 end
12601
12602 --- copy an array into another one, clearing `dest` after `idest+nsrc`, if necessary.
12603 -- @within Copying
12604 -- @array dest a list-like table
12605 -- @array src a list-like table
12606 -- @int[opt=1] idest where to start copying values into destination
12607 -- @int[opt=1] isrc where to start copying values from source
12608 -- @int[opt=#src] nsrc number of elements to copy from source
12609 function tablex.icopy (dest,src,idest,isrc,nsrc)
12610 assert_arg_indexable(1,dest)
12611 assert_arg_indexable(2,src)
12612 return _copy(dest,src,idest,isrc,nsrc,true)
12613 end
12614
12615 --- copy an array into another one.
12616 -- @within Copying
12617 -- @array dest a list-like table
12618 -- @array src a list-like table
12619 -- @int[opt=1] idest where to start copying values into destination
12620 -- @int[opt=1] isrc where to start copying values from source
12621 -- @int[opt=#src] nsrc number of elements to copy from source
12622 function tablex.move (dest,src,idest,isrc,nsrc)
12623 assert_arg_indexable(1,dest)
12624 assert_arg_indexable(2,src)
12625 return _copy(dest,src,idest,isrc,nsrc,false)
12626 end
12627
12628 function tablex._normalize_slice(self,first,last)
12629 local sz = #self
12630 if not first then first=1 end
12631 if first<0 then first=sz+first+1 end
12632 -- make the range _inclusive_!
12633 if not last then last=sz end
12634 if last < 0 then last=sz+1+last end
12635 return first,last
12636 end
12637
12638 --- Extract a range from a table, like 'string.sub'.
12639 -- If first or last are negative then they are relative to the end of the list
12640 -- eg. sub(t,-2) gives last 2 entries in a list, and
12641 -- sub(t,-4,-2) gives from -4th to -2nd
12642 -- @within Extraction
12643 -- @array t a list-like table
12644 -- @int first An index
12645 -- @int last An index
12646 -- @return a new List
12647 function tablex.sub(t,first,last)
12648 assert_arg_indexable(1,t)
12649 first,last = tablex._normalize_slice(t,first,last)
12650 local res={}
12651 for i=first,last do append(res,t[i]) end
12652 return setmeta(res,t,'List')
12653 end
12654
12655 --- set an array range to a value. If it's a function we use the result
12656 -- of applying it to the indices.
12657 -- @array t a list-like table
12658 -- @param val a value
12659 -- @int[opt=1] i1 start range
12660 -- @int[opt=#t] i2 end range
12661 function tablex.set (t,val,i1,i2)
12662 assert_arg_indexable(1,t)
12663 i1,i2 = i1 or 1,i2 or #t
12664 if types.is_callable(val) then
12665 for i = i1,i2 do
12666 t[i] = val(i)
12667 end
12668 else
12669 for i = i1,i2 do
12670 t[i] = val
12671 end
12672 end
12673 end
12674
12675 --- create a new array of specified size with initial value.
12676 -- @int n size
12677 -- @param val initial value (can be `nil`, but don't expect `#` to work!)
12678 -- @return the table
12679 function tablex.new (n,val)
12680 local res = {}
12681 tablex.set(res,val,1,n)
12682 return res
12683 end
12684
12685 --- clear out the contents of a table.
12686 -- @array t a list
12687 -- @param istart optional start position
12688 function tablex.clear(t,istart)
12689 istart = istart or 1
12690 for i = istart,#t do remove(t) end
12691 end
12692
12693 --- insert values into a table.
12694 -- similar to `table.insert` but inserts values from given table `values`,
12695 -- not the object itself, into table `t` at position `pos`.
12696 -- @within Copying
12697 -- @array t the list
12698 -- @int[opt] position (default is at end)
12699 -- @array values
12700 function tablex.insertvalues(t, ...)
12701 assert_arg(1,t,'table')
12702 local pos, values
12703 if select('#', ...) == 1 then
12704 pos,values = #t+1, ...
12705 else
12706 pos,values = ...
12707 end
12708 if #values > 0 then
12709 for i=#t,pos,-1 do
12710 t[i+#values] = t[i]
12711 end
12712 local offset = 1 - pos
12713 for i=pos,pos+#values-1 do
12714 t[i] = values[i + offset]
12715 end
12716 end
12717 return t
12718 end
12719
12720 --- remove a range of values from a table.
12721 -- End of range may be negative.
12722 -- @array t a list-like table
12723 -- @int i1 start index
12724 -- @int i2 end index
12725 -- @return the table
12726 function tablex.removevalues (t,i1,i2)
12727 assert_arg(1,t,'table')
12728 i1,i2 = tablex._normalize_slice(t,i1,i2)
12729 for i = i1,i2 do
12730 remove(t,i1)
12731 end
12732 return t
12733 end
12734
12735 local _find
12736 _find = function (t,value,tables)
12737 for k,v in pairs(t) do
12738 if v == value then return k end
12739 end
12740 for k,v in pairs(t) do
12741 if not tables[v] and type(v) == 'table' then
12742 tables[v] = true
12743 local res = _find(v,value,tables)
12744 if res then
12745 res = tostring(res)
12746 if type(k) ~= 'string' then
12747 return '['..k..']'..res
12748 else
12749 return k..'.'..res
12750 end
12751 end
12752 end
12753 end
12754 end
12755
12756 --- find a value in a table by recursive search.
12757 -- @within Finding
12758 -- @tab t the table
12759 -- @param value the value
12760 -- @array[opt] exclude any tables to avoid searching
12761 -- @return a fieldspec, e.g. 'a.b' or 'math.sin'
12762 -- @usage search(_G,math.sin,{package.path}) == 'math.sin'
12763 function tablex.search (t,value,exclude)
12764 assert_arg_iterable(1,t)
12765 local tables = {[t]=true}
12766 if exclude then
12767 for _,v in pairs(exclude) do tables[v] = true end
12768 end
12769 return _find(t,value,tables)
12770 end
12771
12772 --- return an iterator to a table sorted by its keys
12773 -- @within Iterating
12774 -- @tab t the table
12775 -- @func f an optional comparison function (f(x,y) is true if x < y)
12776 -- @usage for k,v in tablex.sort(t) do print(k,v) end
12777 -- @return an iterator to traverse elements sorted by the keys
12778 function tablex.sort(t,f)
12779 local keys = {}
12780 for k in pairs(t) do keys[#keys + 1] = k end
12781 tsort(keys,f)
12782 local i = 0
12783 return function()
12784 i = i + 1
12785 return keys[i], t[keys[i]]
12786 end
12787 end
12788
12789 --- return an iterator to a table sorted by its values
12790 -- @within Iterating
12791 -- @tab t the table
12792 -- @func f an optional comparison function (f(x,y) is true if x < y)
12793 -- @usage for k,v in tablex.sortv(t) do print(k,v) end
12794 -- @return an iterator to traverse elements sorted by the values
12795 function tablex.sortv(t,f)
12796 f = function_arg(2, f or '<')
12797 local keys = {}
12798 for k in pairs(t) do keys[#keys + 1] = k end
12799 tsort(keys,function(x, y) return f(t[x], t[y]) end)
12800 local i = 0
12801 return function()
12802 i = i + 1
12803 return keys[i], t[keys[i]]
12804 end
12805 end
12806
12807 --- modifies a table to be read only.
12808 -- This only offers weak protection. Tables can still be modified with
12809 -- `table.insert` and `rawset`.
12810 --
12811 -- *NOTE*: for Lua 5.1 length, pairs and ipairs will not work, since the
12812 -- equivalent metamethods are only available in Lua 5.2 and newer.
12813 -- @tab t the table
12814 -- @return the table read only (a proxy).
12815 function tablex.readonly(t)
12816 local mt = {
12817 __index=t,
12818 __newindex=function(t, k, v) error("Attempt to modify read-only table", 2) end,
12819 __pairs=function() return pairs(t) end,
12820 __ipairs=function() return ipairs(t) end,
12821 __len=function() return #t end,
12822 __metatable=false
12823 }
12824 return setmetatable({}, mt)
12825 end
12826
12827 return tablex
12828
12829 end,
12830
12831 ["pl.template"] = function()
12832 --------------------
12833 -- Module: 'pl.template'
12834 --------------------
12835 --- A template preprocessor.
12836 -- Originally by [Ricki Lake](http://lua-users.org/wiki/SlightlyLessSimpleLuaPreprocessor)
12837 --
12838 -- There are two rules:
12839 --
12840 -- * lines starting with # are Lua
12841 -- * otherwise, `$(expr)` is the result of evaluating `expr`
12842 --
12843 -- Example:
12844 --
12845 -- # for i = 1,3 do
12846 -- $(i) Hello, Word!
12847 -- # end
12848 -- ===>
12849 -- 1 Hello, Word!
12850 -- 2 Hello, Word!
12851 -- 3 Hello, Word!
12852 --
12853 -- Other escape characters can be used, when the defaults conflict
12854 -- with the output language.
12855 --
12856 -- > for _,n in pairs{'one','two','three'} do
12857 -- static int l_${n} (luaState *state);
12858 -- > end
12859 --
12860 -- See @{03-strings.md.Another_Style_of_Template|the Guide}.
12861 --
12862 -- Dependencies: `pl.utils`
12863 -- @module pl.template
12864
12865 local utils = require 'pl.utils'
12866
12867 local append, concat = table.insert, table.concat
12868 local format, strsub, strfind, strgsub, strrep = string.format, string.sub, string.find, string.gsub, string.rep
12869
12870 local APPENDER = " __R_size = __R_size + 1; __R_table[__R_size] = "
12871
12872 -- When this function returns, `pieces` is guaranteed to hold a complete Lua
12873 -- statement, meaning that new statements can be appended without creating
12874 -- invalid Lua code.
12875 local function parseDollarParen(pieces, chunk, exec_pat, newline)
12876 local s = 1
12877 for term, executed, e in chunk:gmatch(exec_pat) do
12878 executed = '(' .. strsub(executed, 2, -2) .. ')'
12879 append(pieces, APPENDER .. format("%q;", strsub(chunk, s, term - 1)))
12880 append(pieces, APPENDER .. format("__tostring(%s or '');", executed))
12881 s = e
12882 end
12883 local remainder, newlines_removed
12884 if newline then
12885 remainder, newlines_removed = strgsub(strsub(chunk, s), "\n", "")
12886 else
12887 remainder, newlines_removed = strsub(chunk, s), 0
12888 end
12889 if remainder ~= "" then
12890 append(pieces, APPENDER .. format("%q;", remainder))
12891 end
12892 if newlines_removed > 0 then
12893 append(pieces, strrep("\n", newlines_removed))
12894 end
12895 end
12896
12897 local function parseHashLines(chunk, inline_escape, brackets, esc, newline)
12898 -- Escape special characters to avoid invalid expressions
12899 inline_escape = utils.escape(inline_escape)
12900 esc = utils.escape(esc)
12901
12902 local exec_pat = "()" .. inline_escape .. "(%b" .. brackets .. ")()"
12903
12904 local esc_pat = esc .. "+([^\n]*\n?)"
12905 local esc_pat1, esc_pat2 = "^" .. esc_pat, "\n" .. esc_pat
12906 local pieces, s = {"return function() local __R_size, __R_table, __tostring = 0, {}, __tostring; "}, 1
12907 while true do
12908 local _, e, lua = strfind(chunk, esc_pat1, s)
12909 if not e then
12910 local ss
12911 ss, e, lua = strfind(chunk, esc_pat2, s)
12912 parseDollarParen(pieces, strsub(chunk, s, ss), exec_pat, newline)
12913 if not e then break end
12914 end
12915 if strsub(lua, -1, -1) ~= "\n" then lua = lua .. "\n" end -- Ensure trailing newline
12916 append(pieces, lua)
12917 -- since `lua` ends with a newline, there is no danger of subsequent
12918 -- statements being gobbled up by comments or being altered
12919 s = e + 1
12920 end
12921 append(pieces, "return __R_table; end")
12922
12923 -- let's check for a special case where there is nothing to template, but it's
12924 -- just a single static string
12925 local short = false
12926 if (#pieces == 3) and (strfind(pieces[2], APPENDER, 1, true) == 1) then
12927 pieces = { "return " .. strsub(pieces[2], #APPENDER + 1, -1) }
12928 short = true
12929 end
12930 -- if short == true, the generated function will not return a table of strings,
12931 -- but a single string
12932 return concat(pieces), short
12933 end
12934
12935 local template = {}
12936
12937 --- expand the template using the specified environment.
12938 -- This function will compile and render the template. For more performant
12939 -- recurring usage use the two step approach by using `compile` and `ct:render`.
12940 -- @string str the template string
12941 -- @tparam[opt] table env the environment. This table has the following special fields:
12942 -- @tparam[opt=nil] table env._parent continue looking up in this table (e.g. `_parent=_G`).
12943 -- @tparam[opt="()"] string env._brackets bracket pair that wraps inline Lua expressions.
12944 -- @tparam[opt="#"] string env._escape character marking Lua lines.
12945 -- @tparam[opt="$"] string env._inline_escape character marking inline Lua expression.
12946 -- @tparam[opt="TMP"] string env._chunk_name chunk name for loaded templates, used if there
12947 -- is an error in Lua code.
12948 -- @tparam[opt=false] boolean env._debug if truthy, the generated code will be printed upon a render error.
12949 -- @treturn[1] string render result
12950 -- @treturn[1] nil
12951 -- @treturn[1] string source_code (only if '`env._debug`' was truthy).
12952 -- @treturn[2] nil
12953 -- @treturn[2] string error message
12954 -- @treturn[2] string source_code (only if '`env._debug`' was truthy).
12955 function template.substitute(str, env)
12956 env = env or {}
12957 local t, err = template.compile(str, {
12958 chunk_name = rawget(env, "_chunk_name"),
12959 escape = rawget(env, "_escape"),
12960 inline_escape = rawget(env, "_inline_escape"),
12961 inline_brackets = rawget(env, "_brackets"),
12962 newline = false,
12963 debug = rawget(env, "_debug")
12964 })
12965 if not t then return t, err end
12966
12967 return t:render(env, rawget(env, "_parent"), rawget(env, "_debug"))
12968 end
12969
12970 --- executes the previously compiled template and renders it.
12971 -- @function ct:render
12972 -- @tab[opt] env the environment.
12973 -- @tab[opt] parent continue looking up in this table (e.g. `parent=_G`).
12974 -- @bool[opt] db if thruthy, it will print the code upon a render error
12975 -- (provided the template was compiled with the debug option).
12976 -- @treturn[1] string render result
12977 -- @treturn[1] nil
12978 -- @treturn[1] string source_code (only if '`env._debug`' was truthy).
12979 -- @treturn[2] nil
12980 -- @treturn[2] string error message
12981 -- @treturn[2] string source_code (only if '`env._debug`' was truthy).
12982 -- @usage
12983 -- local ct, err = template.compile(my_template)
12984 -- local rendered , err = ct:render(my_env, parent)
12985 local function render(self, env, parent, db)
12986 env = env or {}
12987 if parent then -- parent is a bit silly, but for backward compatibility retained
12988 setmetatable(env, {__index = parent})
12989 end
12990 setmetatable(self.env, {__index = env})
12991
12992 local res, out = xpcall(self.fn, debug.traceback)
12993 if not res then
12994 if self.code and db then print(self.code) end
12995 return nil, out, self.code
12996 end
12997 return concat(out), nil, self.code
12998 end
12999
13000 --- compiles the template.
13001 -- Returns an object that can repeatedly be rendered without parsing/compiling
13002 -- the template again. Preserves the line layout of the template so that line
13003 -- numbers in error messages should point to the correct lines in the source
13004 -- string.
13005 -- @tparam string str the template string
13006 -- @tparam[opt] table opts the compilation options to use. This table supports the following options:
13007 -- @tparam[opt="TMP"] string opts.chunk_name chunk name for loaded templates, used if there
13008 -- is an error in Lua code.
13009 -- @tparam[opt="#"] string opts.escape character marking Lua lines.
13010 -- @tparam[opt="$"] string opts.inline_escape character marking inline Lua expression.
13011 -- @tparam[opt="()"] string opts.inline_brackets bracket pair that wraps inline Lua expressions.
13012 -- @tparam[opt=false] boolean opts.newline if truthy, newlines will be stripped from text in the template.
13013 -- @tparam[opt=false] boolean opts.debug if truthy, the generated code will be printed upon a render error.
13014 -- @treturn[1] ct compiled template object
13015 -- @treturn[2] nil
13016 -- @treturn[2] string error message
13017 -- @treturn[2] string source_code
13018 -- @usage
13019 -- local ct, err = template.compile(my_template)
13020 -- local rendered , err = ct:render(my_env, parent)
13021 function template.compile(str, opts)
13022 opts = opts or {}
13023 local chunk_name = opts.chunk_name or 'TMP'
13024 local escape = opts.escape or '#'
13025 local inline_escape = opts.inline_escape or '$'
13026 local inline_brackets = opts.inline_brackets or '()'
13027
13028 local code, short = parseHashLines(str, inline_escape, inline_brackets, escape, opts.newline)
13029 local env = { __tostring = tostring }
13030 local fn, err = utils.load(code, chunk_name, 't', env)
13031 if not fn then return nil, err, code end
13032
13033 if short then
13034 -- the template returns a single constant string, let's optimize for that
13035 local constant_string = fn()
13036 return {
13037 fn = fn(),
13038 env = env,
13039 render = function(self) -- additional params can be ignored
13040 -- skip the metatable magic and error handling in the render
13041 -- function above for this special case
13042 return constant_string, nil, self.code
13043 end,
13044 code = opts.debug and code or nil,
13045 }
13046 end
13047
13048 return {
13049 fn = fn(),
13050 env = env,
13051 render = render,
13052 code = opts.debug and code or nil,
13053 }
13054 end
13055
13056 return template
13057
13058 end,
13059
13060 ["pl.test"] = function()
13061 --------------------
13062 -- Module: 'pl.test'
13063 --------------------
13064 --- Useful test utilities.
13065 --
13066 -- test.asserteq({1,2},{1,2}) -- can compare tables
13067 -- test.asserteq(1.2,1.19,0.02) -- compare FP numbers within precision
13068 -- T = test.tuple -- used for comparing multiple results
13069 -- test.asserteq(T(string.find(" me","me")),T(2,3))
13070 --
13071 -- Dependencies: `pl.utils`, `pl.tablex`, `pl.pretty`, `pl.path`, `debug`
13072 -- @module pl.test
13073
13074 local tablex = require 'pl.tablex'
13075 local utils = require 'pl.utils'
13076 local pretty = require 'pl.pretty'
13077 local path = require 'pl.path'
13078 local type,unpack,pack = type,utils.unpack,utils.pack
13079 local clock = os.clock
13080 local debug = require 'debug'
13081 local io = io
13082
13083 local function dump(x)
13084 if type(x) == 'table' and not (getmetatable(x) and getmetatable(x).__tostring) then
13085 return pretty.write(x,' ',true)
13086 elseif type(x) == 'string' then
13087 return '"'..x..'"'
13088 else
13089 return tostring(x)
13090 end
13091 end
13092
13093 local test = {}
13094
13095 ---- error handling for test results.
13096 -- By default, this writes to stderr and exits the program.
13097 -- Re-define this function to raise an error and/or redirect output
13098 function test.error_handler(file,line,got_text, needed_text,msg)
13099 local err = io.stderr
13100 err:write(path.basename(file)..':'..line..': assertion failed\n')
13101 err:write("got:\t",got_text,'\n')
13102 err:write("needed:\t",needed_text,'\n')
13103 utils.quit(1,msg or "these values were not equal")
13104 end
13105
13106 local function complain (x,y,msg,where)
13107 local i = debug.getinfo(3 + (where or 0))
13108 test.error_handler(i.short_src,i.currentline,dump(x),dump(y),msg)
13109 end
13110
13111 --- general test complain message.
13112 -- Useful for composing new test functions (see tests/tablex.lua for an example)
13113 -- @param x a value
13114 -- @param y value to compare first value against
13115 -- @param msg message
13116 -- @param where extra level offset for errors
13117 -- @function complain
13118 test.complain = complain
13119
13120 --- like assert, except takes two arguments that must be equal and can be tables.
13121 -- If they are plain tables, it will use tablex.deepcompare.
13122 -- @param x any value
13123 -- @param y a value equal to x
13124 -- @param eps an optional tolerance for numerical comparisons
13125 -- @param where extra level offset
13126 function test.asserteq (x,y,eps,where)
13127 local res = x == y
13128 if not res then
13129 res = tablex.deepcompare(x,y,true,eps)
13130 end
13131 if not res then
13132 complain(x,y,nil,where)
13133 end
13134 end
13135
13136 --- assert that the first string matches the second.
13137 -- @param s1 a string
13138 -- @param s2 a string
13139 -- @param where extra level offset
13140 function test.assertmatch (s1,s2,where)
13141 if not s1:match(s2) then
13142 complain (s1,s2,"these strings did not match",where)
13143 end
13144 end
13145
13146 --- assert that the function raises a particular error.
13147 -- @param fn a function or a table of the form {function,arg1,...}
13148 -- @param e a string to match the error against
13149 -- @param where extra level offset
13150 function test.assertraise(fn,e,where)
13151 local ok, err
13152 if type(fn) == 'table' then
13153 ok, err = pcall(unpack(fn))
13154 else
13155 ok, err = pcall(fn)
13156 end
13157 if ok or err:match(e)==nil then
13158 complain (err,e,"these errors did not match",where)
13159 end
13160 end
13161
13162 --- a version of asserteq that takes two pairs of values.
13163 -- <code>x1==y1 and x2==y2</code> must be true. Useful for functions that naturally
13164 -- return two values.
13165 -- @param x1 any value
13166 -- @param x2 any value
13167 -- @param y1 any value
13168 -- @param y2 any value
13169 -- @param where extra level offset
13170 function test.asserteq2 (x1,x2,y1,y2,where)
13171 if x1 ~= y1 then complain(x1,y1,nil,where) end
13172 if x2 ~= y2 then complain(x2,y2,nil,where) end
13173 end
13174
13175 -- tuple type --
13176
13177 local tuple_mt = {
13178 unpack = unpack
13179 }
13180 tuple_mt.__index = tuple_mt
13181
13182 function tuple_mt.__tostring(self)
13183 local ts = {}
13184 for i=1, self.n do
13185 local s = self[i]
13186 ts[i] = type(s) == 'string' and ('%q'):format(s) or tostring(s)
13187 end
13188 return 'tuple(' .. table.concat(ts, ', ') .. ')'
13189 end
13190
13191 function tuple_mt.__eq(a, b)
13192 if a.n ~= b.n then return false end
13193 for i=1, a.n do
13194 if a[i] ~= b[i] then return false end
13195 end
13196 return true
13197 end
13198
13199 function tuple_mt.__len(self)
13200 return self.n
13201 end
13202
13203 --- encode an arbitrary argument list as a tuple.
13204 -- This can be used to compare to other argument lists, which is
13205 -- very useful for testing functions which return a number of values.
13206 -- Unlike regular array-like tables ('sequences') they may contain nils.
13207 -- Tuples understand equality and know how to print themselves out.
13208 -- The # operator is defined to be the size, irrespecive of any nils,
13209 -- and there is an `unpack` method.
13210 -- @usage asserteq(tuple( ('ab'):find 'a'), tuple(1,1))
13211 function test.tuple(...)
13212 return setmetatable(pack(...), tuple_mt)
13213 end
13214
13215 --- Time a function. Call the function a given number of times, and report the number of seconds taken,
13216 -- together with a message. Any extra arguments will be passed to the function.
13217 -- @string msg a descriptive message
13218 -- @int n number of times to call the function
13219 -- @func fun the function
13220 -- @param ... optional arguments to fun
13221 function test.timer(msg,n,fun,...)
13222 local start = clock()
13223 for i = 1,n do fun(...) end
13224 utils.printf("%s: took %7.2f sec\n",msg,clock()-start)
13225 end
13226
13227 return test
13228
13229 end,
13230
13231 ["pl.text"] = function()
13232 --------------------
13233 -- Module: 'pl.text'
13234 --------------------
13235 --- Text processing utilities.
13236 --
13237 -- This provides a Template class (modeled after the same from the Python
13238 -- libraries, see string.Template). It also provides similar functions to those
13239 -- found in the textwrap module.
13240 --
13241 -- IMPORTANT: this module has been deprecated and will be removed in a future
13242 -- version (2.0). The contents of this module have moved to the `pl.stringx`
13243 -- module.
13244 --
13245 -- See @{03-strings.md.String_Templates|the Guide}.
13246 --
13247 -- Dependencies: `pl.stringx`, `pl.utils`
13248 -- @module pl.text
13249
13250 local utils = require("pl.utils")
13251
13252 utils.raise_deprecation {
13253 source = "Penlight " .. utils._VERSION,
13254 message = "the contents of module 'pl.text' has moved into 'pl.stringx'",
13255 version_removed = "2.0.0",
13256 deprecated_after = "1.11.0",
13257 no_trace = true,
13258 }
13259
13260 return require "pl.stringx"
13261
13262 end,
13263
13264 ["pl.types"] = function()
13265 --------------------
13266 -- Module: 'pl.types'
13267 --------------------
13268 ---- Dealing with Detailed Type Information
13269
13270 -- Dependencies `pl.utils`
13271 -- @module pl.types
13272
13273 local utils = require 'pl.utils'
13274 local math_ceil = math.ceil
13275 local assert_arg = utils.assert_arg
13276 local types = {}
13277
13278 --- is the object either a function or a callable object?.
13279 -- @param obj Object to check.
13280 function types.is_callable (obj)
13281 return type(obj) == 'function' or getmetatable(obj) and getmetatable(obj).__call and true
13282 end
13283
13284 --- is the object of the specified type?.
13285 -- If the type is a string, then use type, otherwise compare with metatable.
13286 --
13287 -- NOTE: this function is imported from `utils.is_type`.
13288 -- @param obj An object to check
13289 -- @param tp The expected type
13290 -- @function is_type
13291 -- @see utils.is_type
13292 types.is_type = utils.is_type
13293
13294 local fileMT = getmetatable(io.stdout)
13295
13296 --- a string representation of a type.
13297 -- For tables and userdata with metatables, we assume that the metatable has a `_name`
13298 -- field. If the field is not present it will return 'unknown table' or
13299 -- 'unknown userdata'.
13300 -- Lua file objects return the type 'file'.
13301 -- @param obj an object
13302 -- @return a string like 'number', 'table', 'file' or 'List'
13303 function types.type (obj)
13304 local t = type(obj)
13305 if t == 'table' or t == 'userdata' then
13306 local mt = getmetatable(obj)
13307 if mt == fileMT then
13308 return 'file'
13309 elseif mt == nil then
13310 return t
13311 else
13312 -- TODO: the "unknown" is weird, it should just return the type
13313 return mt._name or "unknown "..t
13314 end
13315 else
13316 return t
13317 end
13318 end
13319
13320 --- is this number an integer?
13321 -- @param x a number
13322 -- @raise error if x is not a number
13323 -- @return boolean
13324 function types.is_integer (x)
13325 return math_ceil(x)==x
13326 end
13327
13328 --- Check if the object is "empty".
13329 -- An object is considered empty if it is:
13330 --
13331 -- - `nil`
13332 -- - a table without any items (key-value pairs or indexes)
13333 -- - a string with no content ("")
13334 -- - not a nil/table/string
13335 -- @param o The object to check if it is empty.
13336 -- @param ignore_spaces If the object is a string and this is true the string is
13337 -- considered empty if it only contains spaces.
13338 -- @return `true` if the object is empty, otherwise a falsy value.
13339 function types.is_empty(o, ignore_spaces)
13340 if o == nil then
13341 return true
13342 elseif type(o) == "table" then
13343 return next(o) == nil
13344 elseif type(o) == "string" then
13345 return o == "" or (not not ignore_spaces and (not not o:find("^%s+$")))
13346 else
13347 return true
13348 end
13349 end
13350
13351 local function check_meta (val)
13352 if type(val) == 'table' then return true end
13353 return getmetatable(val)
13354 end
13355
13356 --- is an object 'array-like'?
13357 -- An object is array like if:
13358 --
13359 -- - it is a table, or
13360 -- - it has a metatable with `__len` and `__index` methods
13361 --
13362 -- NOTE: since `__len` is 5.2+, on 5.1 is usually returns `false` for userdata
13363 -- @param val any value.
13364 -- @return `true` if the object is array-like, otherwise a falsy value.
13365 function types.is_indexable (val)
13366 local mt = check_meta(val)
13367 if mt == true then return true end
13368 return mt and mt.__len and mt.__index and true
13369 end
13370
13371 --- can an object be iterated over with `pairs`?
13372 -- An object is iterable if:
13373 --
13374 -- - it is a table, or
13375 -- - it has a metatable with a `__pairs` meta method
13376 --
13377 -- NOTE: since `__pairs` is 5.2+, on 5.1 is usually returns `false` for userdata
13378 -- @param val any value.
13379 -- @return `true` if the object is iterable, otherwise a falsy value.
13380 function types.is_iterable (val)
13381 local mt = check_meta(val)
13382 if mt == true then return true end
13383 return mt and mt.__pairs and true
13384 end
13385
13386 --- can an object accept new key/pair values?
13387 -- An object is iterable if:
13388 --
13389 -- - it is a table, or
13390 -- - it has a metatable with a `__newindex` meta method
13391 --
13392 -- @param val any value.
13393 -- @return `true` if the object is writeable, otherwise a falsy value.
13394 function types.is_writeable (val)
13395 local mt = check_meta(val)
13396 if mt == true then return true end
13397 return mt and mt.__newindex and true
13398 end
13399
13400 -- Strings that should evaluate to true. -- TODO: add on/off ???
13401 local trues = { yes=true, y=true, ["true"]=true, t=true, ["1"]=true }
13402 -- Conditions types should evaluate to true.
13403 local true_types = {
13404 boolean=function(o, true_strs, check_objs) return o end,
13405 string=function(o, true_strs, check_objs)
13406 o = o:lower()
13407 if trues[o] then
13408 return true
13409 end
13410 -- Check alternative user provided strings.
13411 for _,v in ipairs(true_strs or {}) do
13412 if type(v) == "string" and o == v:lower() then
13413 return true
13414 end
13415 end
13416 return false
13417 end,
13418 number=function(o, true_strs, check_objs) return o ~= 0 end,
13419 table=function(o, true_strs, check_objs) if check_objs and next(o) ~= nil then return true end return false end
13420 }
13421 --- Convert to a boolean value.
13422 -- True values are:
13423 --
13424 -- * boolean: true.
13425 -- * string: 'yes', 'y', 'true', 't', '1' or additional strings specified by `true_strs`.
13426 -- * number: Any non-zero value.
13427 -- * table: Is not empty and `check_objs` is true.
13428 -- * everything else: Is not `nil` and `check_objs` is true.
13429 --
13430 -- @param o The object to evaluate.
13431 -- @param[opt] true_strs optional Additional strings that when matched should evaluate to true. Comparison is case insensitive.
13432 -- This should be a List of strings. E.g. "ja" to support German.
13433 -- @param[opt] check_objs True if objects should be evaluated.
13434 -- @return true if the input evaluates to true, otherwise false.
13435 function types.to_bool(o, true_strs, check_objs)
13436 local true_func
13437 if true_strs then
13438 assert_arg(2, true_strs, "table")
13439 end
13440 true_func = true_types[type(o)]
13441 if true_func then
13442 return true_func(o, true_strs, check_objs)
13443 elseif check_objs and o ~= nil then
13444 return true
13445 end
13446 return false
13447 end
13448
13449
13450 return types
13451
13452 end,
13453
13454 ["pl.url"] = function()
13455 --------------------
13456 -- Module: 'pl.url'
13457 --------------------
13458 --- Python-style URL quoting library.
13459 --
13460 -- @module pl.url
13461
13462 local url = {}
13463
13464 local function quote_char(c)
13465 return string.format("%%%02X", string.byte(c))
13466 end
13467
13468 --- Quote the url, replacing special characters using the '%xx' escape.
13469 -- @string s the string
13470 -- @bool quote_plus Also escape slashes and replace spaces by plus signs.
13471 -- @return The quoted string, or if `s` wasn't a string, just plain unaltered `s`.
13472 function url.quote(s, quote_plus)
13473 if type(s) ~= "string" then
13474 return s
13475 end
13476
13477 s = s:gsub("\n", "\r\n")
13478 s = s:gsub("([^A-Za-z0-9 %-_%./])", quote_char)
13479 if quote_plus then
13480 s = s:gsub(" ", "+")
13481 s = s:gsub("/", quote_char)
13482 else
13483 s = s:gsub(" ", "%%20")
13484 end
13485
13486 return s
13487 end
13488
13489 local function unquote_char(h)
13490 return string.char(tonumber(h, 16))
13491 end
13492
13493 --- Unquote the url, replacing '%xx' escapes and plus signs.
13494 -- @string s the string
13495 -- @return The unquoted string, or if `s` wasn't a string, just plain unaltered `s`.
13496 function url.unquote(s)
13497 if type(s) ~= "string" then
13498 return s
13499 end
13500
13501 s = s:gsub("+", " ")
13502 s = s:gsub("%%(%x%x)", unquote_char)
13503 s = s:gsub("\r\n", "\n")
13504
13505 return s
13506 end
13507
13508 return url
13509
13510 end,
13511
13512 ["pl.utils"] = function()
13513 --------------------
13514 -- Module: 'pl.utils'
13515 --------------------
13516 --- Generally useful routines.
13517 -- See @{01-introduction.md.Generally_useful_functions|the Guide}.
13518 --
13519 -- Dependencies: `pl.compat`, all exported fields and functions from
13520 -- `pl.compat` are also available in this module.
13521 --
13522 -- @module pl.utils
13523 local format = string.format
13524 local compat = require 'pl.compat'
13525 local stdout = io.stdout
13526 local append = table.insert
13527 local concat = table.concat
13528 local _unpack = table.unpack -- always injected by 'compat'
13529 local find = string.find
13530 local sub = string.sub
13531 local next = next
13532 local floor = math.floor
13533
13534 local is_windows = compat.is_windows
13535 local err_mode = 'default'
13536 local raise
13537 local operators
13538 local _function_factories = {}
13539
13540
13541 local utils = { _VERSION = "1.14.0" }
13542
13543 for k, v in pairs(compat) do utils[k] = v end
13544
13545 --- Some standard patterns
13546 -- @table patterns
13547 utils.patterns = {
13548 FLOAT = '[%+%-%d]%d*%.?%d*[eE]?[%+%-]?%d*', -- floating point number
13549 INTEGER = '[+%-%d]%d*', -- integer number
13550 IDEN = '[%a_][%w_]*', -- identifier
13551 FILE = '[%a%.\\][:%][%w%._%-\\]*', -- file
13552 }
13553
13554
13555 --- Standard meta-tables as used by other Penlight modules
13556 -- @table stdmt
13557 -- @field List the List metatable
13558 -- @field Map the Map metatable
13559 -- @field Set the Set metatable
13560 -- @field MultiMap the MultiMap metatable
13561 utils.stdmt = {
13562 List = {_name='List'},
13563 Map = {_name='Map'},
13564 Set = {_name='Set'},
13565 MultiMap = {_name='MultiMap'},
13566 }
13567
13568
13569 --- pack an argument list into a table.
13570 -- @param ... any arguments
13571 -- @return a table with field `n` set to the length
13572 -- @function utils.pack
13573 -- @see compat.pack
13574 -- @see utils.npairs
13575 -- @see utils.unpack
13576 utils.pack = table.pack -- added here to be symmetrical with unpack
13577
13578 --- unpack a table and return its contents.
13579 --
13580 -- NOTE: this implementation differs from the Lua implementation in the way
13581 -- that this one DOES honor the `n` field in the table `t`, such that it is 'nil-safe'.
13582 -- @param t table to unpack
13583 -- @param[opt] i index from which to start unpacking, defaults to 1
13584 -- @param[opt] j index of the last element to unpack, defaults to `t.n` or else `#t`
13585 -- @return multiple return values from the table
13586 -- @function utils.unpack
13587 -- @see compat.unpack
13588 -- @see utils.pack
13589 -- @see utils.npairs
13590 -- @usage
13591 -- local t = table.pack(nil, nil, nil, 4)
13592 -- local a, b, c, d = table.unpack(t) -- this `unpack` is NOT nil-safe, so d == nil
13593 --
13594 -- local a, b, c, d = utils.unpack(t) -- this is nil-safe, so d == 4
13595 function utils.unpack(t, i, j)
13596 return _unpack(t, i or 1, j or t.n or #t)
13597 end
13598
13599 --- print an arbitrary number of arguments using a format.
13600 -- Output will be sent to `stdout`.
13601 -- @param fmt The format (see `string.format`)
13602 -- @param ... Extra arguments for format
13603 function utils.printf(fmt, ...)
13604 utils.assert_string(1, fmt)
13605 utils.fprintf(stdout, fmt, ...)
13606 end
13607
13608 --- write an arbitrary number of arguments to a file using a format.
13609 -- @param f File handle to write to.
13610 -- @param fmt The format (see `string.format`).
13611 -- @param ... Extra arguments for format
13612 function utils.fprintf(f,fmt,...)
13613 utils.assert_string(2,fmt)
13614 f:write(format(fmt,...))
13615 end
13616
13617 do
13618 local function import_symbol(T,k,v,libname)
13619 local key = rawget(T,k)
13620 -- warn about collisions!
13621 if key and k ~= '_M' and k ~= '_NAME' and k ~= '_PACKAGE' and k ~= '_VERSION' then
13622 utils.fprintf(io.stderr,"warning: '%s.%s' will not override existing symbol\n",libname,k)
13623 return
13624 end
13625 rawset(T,k,v)
13626 end
13627
13628 local function lookup_lib(T,t)
13629 for k,v in pairs(T) do
13630 if v == t then return k end
13631 end
13632 return '?'
13633 end
13634
13635 local already_imported = {}
13636
13637 --- take a table and 'inject' it into the local namespace.
13638 -- @param t The table (table), or module name (string), defaults to this `utils` module table
13639 -- @param T An optional destination table (defaults to callers environment)
13640 function utils.import(t,T)
13641 T = T or _G
13642 t = t or utils
13643 if type(t) == 'string' then
13644 t = require (t)
13645 end
13646 local libname = lookup_lib(T,t)
13647 if already_imported[t] then return end
13648 already_imported[t] = libname
13649 for k,v in pairs(t) do
13650 import_symbol(T,k,v,libname)
13651 end
13652 end
13653 end
13654
13655 --- return either of two values, depending on a condition.
13656 -- @param cond A condition
13657 -- @param value1 Value returned if cond is truthy
13658 -- @param value2 Value returned if cond is falsy
13659 function utils.choose(cond, value1, value2)
13660 if cond then
13661 return value1
13662 else
13663 return value2
13664 end
13665 end
13666
13667 --- convert an array of values to strings.
13668 -- @param t a list-like table
13669 -- @param[opt] temp (table) buffer to use, otherwise allocate
13670 -- @param[opt] tostr custom tostring function, called with (value,index). Defaults to `tostring`.
13671 -- @return the converted buffer
13672 function utils.array_tostring (t,temp,tostr)
13673 temp, tostr = temp or {}, tostr or tostring
13674 for i = 1,#t do
13675 temp[i] = tostr(t[i],i)
13676 end
13677 return temp
13678 end
13679
13680
13681
13682 --- is the object of the specified type?
13683 -- If the type is a string, then use type, otherwise compare with metatable
13684 -- @param obj An object to check
13685 -- @param tp String of what type it should be
13686 -- @return boolean
13687 -- @usage utils.is_type("hello world", "string") --> true
13688 -- -- or check metatable
13689 -- local my_mt = {}
13690 -- local my_obj = setmetatable(my_obj, my_mt)
13691 -- utils.is_type(my_obj, my_mt) --> true
13692 function utils.is_type (obj,tp)
13693 if type(tp) == 'string' then return type(obj) == tp end
13694 local mt = getmetatable(obj)
13695 return tp == mt
13696 end
13697
13698
13699
13700 --- an iterator with indices, similar to `ipairs`, but with a range.
13701 -- This is a nil-safe index based iterator that will return `nil` when there
13702 -- is a hole in a list. To be safe ensure that table `t.n` contains the length.
13703 -- @tparam table t the table to iterate over
13704 -- @tparam[opt=1] integer i_start start index
13705 -- @tparam[opt=t.n or #t] integer i_end end index
13706 -- @tparam[opt=1] integer step step size
13707 -- @treturn integer index
13708 -- @treturn any value at index (which can be `nil`!)
13709 -- @see utils.pack
13710 -- @see utils.unpack
13711 -- @usage
13712 -- local t = utils.pack(nil, 123, nil) -- adds an `n` field when packing
13713 --
13714 -- for i, v in utils.npairs(t, 2) do -- start at index 2
13715 -- t[i] = tostring(t[i])
13716 -- end
13717 --
13718 -- -- t = { n = 3, [2] = "123", [3] = "nil" }
13719 function utils.npairs(t, i_start, i_end, step)
13720 step = step or 1
13721 if step == 0 then
13722 error("iterator step-size cannot be 0", 2)
13723 end
13724 local i = (i_start or 1) - step
13725 i_end = i_end or t.n or #t
13726 if step < 0 then
13727 return function()
13728 i = i + step
13729 if i < i_end then
13730 return nil
13731 end
13732 return i, t[i]
13733 end
13734
13735 else
13736 return function()
13737 i = i + step
13738 if i > i_end then
13739 return nil
13740 end
13741 return i, t[i]
13742 end
13743 end
13744 end
13745
13746
13747
13748 --- an iterator over all non-integer keys (inverse of `ipairs`).
13749 -- It will skip any key that is an integer number, so negative indices or an
13750 -- array with holes will not return those either (so it returns slightly less than
13751 -- 'the inverse of `ipairs`').
13752 --
13753 -- This uses `pairs` under the hood, so any value that is iterable using `pairs`
13754 -- will work with this function.
13755 -- @tparam table t the table to iterate over
13756 -- @treturn key
13757 -- @treturn value
13758 -- @usage
13759 -- local t = {
13760 -- "hello",
13761 -- "world",
13762 -- hello = "hallo",
13763 -- world = "Welt",
13764 -- }
13765 --
13766 -- for k, v in utils.kpairs(t) do
13767 -- print("German: ", v)
13768 -- end
13769 --
13770 -- -- output;
13771 -- -- German: hallo
13772 -- -- German: Welt
13773 function utils.kpairs(t)
13774 local index
13775 return function()
13776 local value
13777 while true do
13778 index, value = next(t, index)
13779 if type(index) ~= "number" or floor(index) ~= index then
13780 break
13781 end
13782 end
13783 return index, value
13784 end
13785 end
13786
13787
13788
13789 --- Error handling
13790 -- @section Error-handling
13791
13792 --- assert that the given argument is in fact of the correct type.
13793 -- @param n argument index
13794 -- @param val the value
13795 -- @param tp the type
13796 -- @param verify an optional verification function
13797 -- @param msg an optional custom message
13798 -- @param lev optional stack position for trace, default 2
13799 -- @return the validated value
13800 -- @raise if `val` is not the correct type
13801 -- @usage
13802 -- local param1 = assert_arg(1,"hello",'table') --> error: argument 1 expected a 'table', got a 'string'
13803 -- local param4 = assert_arg(4,'!@#$%^&*','string',path.isdir,'not a directory')
13804 -- --> error: argument 4: '!@#$%^&*' not a directory
13805 function utils.assert_arg (n,val,tp,verify,msg,lev)
13806 if type(val) ~= tp then
13807 error(("argument %d expected a '%s', got a '%s'"):format(n,tp,type(val)),lev or 2)
13808 end
13809 if verify and not verify(val) then
13810 error(("argument %d: '%s' %s"):format(n,val,msg),lev or 2)
13811 end
13812 return val
13813 end
13814
13815 --- creates an Enum or constants lookup table for improved error handling.
13816 -- This helps prevent magic strings in code by throwing errors for accessing
13817 -- non-existing values, and/or converting strings/identifiers to other values.
13818 --
13819 -- Calling on the object does the same, but returns a soft error; `nil + err`, if
13820 -- the call is successful (the key exists), it will return the value.
13821 --
13822 -- When calling with varargs or an array the values will be equal to the keys.
13823 -- The enum object is read-only.
13824 -- @tparam table|vararg ... the input for the Enum. If varargs or an array then the
13825 -- values in the Enum will be equal to the names (must be strings), if a hash-table
13826 -- then values remain (any type), and the keys must be strings.
13827 -- @return Enum object (read-only table/object)
13828 -- @usage -- Enum access at runtime
13829 -- local obj = {}
13830 -- obj.MOVEMENT = utils.enum("FORWARD", "REVERSE", "LEFT", "RIGHT")
13831 --
13832 -- if current_movement == obj.MOVEMENT.FORWARD then
13833 -- -- do something
13834 --
13835 -- elseif current_movement == obj.MOVEMENT.REVERES then
13836 -- -- throws error due to typo 'REVERES', so a silent mistake becomes a hard error
13837 -- -- "'REVERES' is not a valid value (expected one of: 'FORWARD', 'REVERSE', 'LEFT', 'RIGHT')"
13838 --
13839 -- end
13840 -- @usage -- standardized error codes
13841 -- local obj = {
13842 -- ERR = utils.enum {
13843 -- NOT_FOUND = "the item was not found",
13844 -- OUT_OF_BOUNDS = "the index is outside the allowed range"
13845 -- },
13846 --
13847 -- some_method = function(self)
13848 -- return nil, self.ERR.OUT_OF_BOUNDS
13849 -- end,
13850 -- }
13851 --
13852 -- local result, err = obj:some_method()
13853 -- if not result then
13854 -- if err == obj.ERR.NOT_FOUND then
13855 -- -- check on error code, not magic strings
13856 --
13857 -- else
13858 -- -- return the error description, contained in the constant
13859 -- return nil, "error: "..err -- "error: the index is outside the allowed range"
13860 -- end
13861 -- end
13862 -- @usage -- validating/converting user-input
13863 -- local color = "purple"
13864 -- local ansi_colors = utils.enum {
13865 -- black = 30,
13866 -- red = 31,
13867 -- green = 32,
13868 -- }
13869 -- local color_code, err = ansi_colors(color) -- calling on the object, returns the value from the enum
13870 -- if not color_code then
13871 -- print("bad 'color', " .. err)
13872 -- -- "bad 'color', 'purple' is not a valid value (expected one of: 'black', 'red', 'green')"
13873 -- os.exit(1)
13874 -- end
13875 function utils.enum(...)
13876 local first = select(1, ...)
13877 local enum = {}
13878 local lst
13879
13880 if type(first) ~= "table" then
13881 -- vararg with strings
13882 lst = utils.pack(...)
13883 for i, value in utils.npairs(lst) do
13884 utils.assert_arg(i, value, "string")
13885 enum[value] = value
13886 end
13887
13888 else
13889 -- table/array with values
13890 utils.assert_arg(1, first, "table")
13891 lst = {}
13892 -- first add array part
13893 for i, value in ipairs(first) do
13894 if type(value) ~= "string" then
13895 error(("expected 'string' but got '%s' at index %d"):format(type(value), i), 2)
13896 end
13897 lst[i] = value
13898 enum[value] = value
13899 end
13900 -- add key-ed part
13901 for key, value in utils.kpairs(first) do
13902 if type(key) ~= "string" then
13903 error(("expected key to be 'string' but got '%s'"):format(type(key)), 2)
13904 end
13905 if enum[key] then
13906 error(("duplicate entry in array and hash part: '%s'"):format(key), 2)
13907 end
13908 enum[key] = value
13909 lst[#lst+1] = key
13910 end
13911 end
13912
13913 if not lst[1] then
13914 error("expected at least 1 entry", 2)
13915 end
13916
13917 local valid = "(expected one of: '" .. concat(lst, "', '") .. "')"
13918 setmetatable(enum, {
13919 __index = function(self, key)
13920 error(("'%s' is not a valid value %s"):format(tostring(key), valid), 2)
13921 end,
13922 __newindex = function(self, key, value)
13923 error("the Enum object is read-only", 2)
13924 end,
13925 __call = function(self, key)
13926 if type(key) == "string" then
13927 local v = rawget(self, key)
13928 if v ~= nil then
13929 return v
13930 end
13931 end
13932 return nil, ("'%s' is not a valid value %s"):format(tostring(key), valid)
13933 end
13934 })
13935
13936 return enum
13937 end
13938
13939
13940 --- process a function argument.
13941 -- This is used throughout Penlight and defines what is meant by a function:
13942 -- Something that is callable, or an operator string as defined by <code>pl.operator</code>,
13943 -- such as '>' or '#'. If a function factory has been registered for the type, it will
13944 -- be called to get the function.
13945 -- @param idx argument index
13946 -- @param f a function, operator string, or callable object
13947 -- @param msg optional error message
13948 -- @return a callable
13949 -- @raise if idx is not a number or if f is not callable
13950 function utils.function_arg (idx,f,msg)
13951 utils.assert_arg(1,idx,'number')
13952 local tp = type(f)
13953 if tp == 'function' then return f end -- no worries!
13954 -- ok, a string can correspond to an operator (like '==')
13955 if tp == 'string' then
13956 if not operators then operators = require 'pl.operator'.optable end
13957 local fn = operators[f]
13958 if fn then return fn end
13959 local fn, err = utils.string_lambda(f)
13960 if not fn then error(err..': '..f) end
13961 return fn
13962 elseif tp == 'table' or tp == 'userdata' then
13963 local mt = getmetatable(f)
13964 if not mt then error('not a callable object',2) end
13965 local ff = _function_factories[mt]
13966 if not ff then
13967 if not mt.__call then error('not a callable object',2) end
13968 return f
13969 else
13970 return ff(f) -- we have a function factory for this type!
13971 end
13972 end
13973 if not msg then msg = " must be callable" end
13974 if idx > 0 then
13975 error("argument "..idx..": "..msg,2)
13976 else
13977 error(msg,2)
13978 end
13979 end
13980
13981
13982 --- assert the common case that the argument is a string.
13983 -- @param n argument index
13984 -- @param val a value that must be a string
13985 -- @return the validated value
13986 -- @raise val must be a string
13987 -- @usage
13988 -- local val = 42
13989 -- local param2 = utils.assert_string(2, val) --> error: argument 2 expected a 'string', got a 'number'
13990 function utils.assert_string (n, val)
13991 return utils.assert_arg(n,val,'string',nil,nil,3)
13992 end
13993
13994 --- control the error strategy used by Penlight.
13995 -- This is a global setting that controls how `utils.raise` behaves:
13996 --
13997 -- - 'default': return `nil + error` (this is the default)
13998 -- - 'error': throw a Lua error
13999 -- - 'quit': exit the program
14000 --
14001 -- @param mode either 'default', 'quit' or 'error'
14002 -- @see utils.raise
14003 function utils.on_error (mode)
14004 mode = tostring(mode)
14005 if ({['default'] = 1, ['quit'] = 2, ['error'] = 3})[mode] then
14006 err_mode = mode
14007 else
14008 -- fail loudly
14009 local err = "Bad argument expected string; 'default', 'quit', or 'error'. Got '"..tostring(mode).."'"
14010 if err_mode == 'default' then
14011 error(err, 2) -- even in 'default' mode fail loud in this case
14012 end
14013 raise(err)
14014 end
14015 end
14016
14017 --- used by Penlight functions to return errors. Its global behaviour is controlled
14018 -- by `utils.on_error`.
14019 -- To use this function you MUST use it in conjunction with `return`, since it might
14020 -- return `nil + error`.
14021 -- @param err the error string.
14022 -- @see utils.on_error
14023 -- @usage
14024 -- if some_condition then
14025 -- return utils.raise("some condition was not met") -- MUST use 'return'!
14026 -- end
14027 function utils.raise (err)
14028 if err_mode == 'default' then
14029 return nil, err
14030 elseif err_mode == 'quit' then
14031 return utils.quit(err)
14032 else
14033 error(err, 2)
14034 end
14035 end
14036 raise = utils.raise
14037
14038
14039
14040 --- File handling
14041 -- @section files
14042
14043 --- return the contents of a file as a string
14044 -- @param filename The file path
14045 -- @param is_bin open in binary mode
14046 -- @return file contents
14047 function utils.readfile(filename,is_bin)
14048 local mode = is_bin and 'b' or ''
14049 utils.assert_string(1,filename)
14050 local f,open_err = io.open(filename,'r'..mode)
14051 if not f then return raise (open_err) end
14052 local res,read_err = f:read('*a')
14053 f:close()
14054 if not res then
14055 -- Errors in io.open have "filename: " prefix,
14056 -- error in file:read don't, add it.
14057 return raise (filename..": "..read_err)
14058 end
14059 return res
14060 end
14061
14062 --- write a string to a file
14063 -- @param filename The file path
14064 -- @param str The string
14065 -- @param is_bin open in binary mode
14066 -- @return true or nil
14067 -- @return error message
14068 -- @raise error if filename or str aren't strings
14069 function utils.writefile(filename,str,is_bin)
14070 local mode = is_bin and 'b' or ''
14071 utils.assert_string(1,filename)
14072 utils.assert_string(2,str)
14073 local f,err = io.open(filename,'w'..mode)
14074 if not f then return raise(err) end
14075 local ok, write_err = f:write(str)
14076 f:close()
14077 if not ok then
14078 -- Errors in io.open have "filename: " prefix,
14079 -- error in file:write don't, add it.
14080 return raise (filename..": "..write_err)
14081 end
14082 return true
14083 end
14084
14085 --- return the contents of a file as a list of lines
14086 -- @param filename The file path
14087 -- @return file contents as a table
14088 -- @raise error if filename is not a string
14089 function utils.readlines(filename)
14090 utils.assert_string(1,filename)
14091 local f,err = io.open(filename,'r')
14092 if not f then return raise(err) end
14093 local res = {}
14094 for line in f:lines() do
14095 append(res,line)
14096 end
14097 f:close()
14098 return res
14099 end
14100
14101 --- OS functions
14102 -- @section OS-functions
14103
14104 --- Execute a shell command.
14105 -- This function is a copy of `compat.execute`.
14106 -- @class function
14107 -- @name utils.execute
14108
14109 --- execute a shell command and return the output.
14110 -- This function redirects the output to tempfiles and returns the content of those files.
14111 -- @param cmd a shell command
14112 -- @param bin boolean, if true, read output as binary file
14113 -- @return true if successful
14114 -- @return actual return code
14115 -- @return stdout output (string)
14116 -- @return errout output (string)
14117 function utils.executeex(cmd, bin)
14118 local outfile = os.tmpname()
14119 local errfile = os.tmpname()
14120
14121 if is_windows and not outfile:find(':') then
14122 outfile = os.getenv('TEMP')..outfile
14123 errfile = os.getenv('TEMP')..errfile
14124 end
14125 cmd = cmd .. " > " .. utils.quote_arg(outfile) .. " 2> " .. utils.quote_arg(errfile)
14126
14127 local success, retcode = utils.execute(cmd)
14128 local outcontent = utils.readfile(outfile, bin)
14129 local errcontent = utils.readfile(errfile, bin)
14130 os.remove(outfile)
14131 os.remove(errfile)
14132 return success, retcode, (outcontent or ""), (errcontent or "")
14133 end
14134
14135 --- Quote and escape an argument of a command.
14136 -- Quotes a single (or list of) argument(s) of a command to be passed
14137 -- to `os.execute`, `pl.utils.execute` or `pl.utils.executeex`.
14138 -- @param argument (string or table/list) the argument to quote. If a list then
14139 -- all arguments in the list will be returned as a single string quoted.
14140 -- @return quoted and escaped argument.
14141 -- @usage
14142 -- local options = utils.quote_arg {
14143 -- "-lluacov",
14144 -- "-e",
14145 -- "utils = print(require('pl.utils')._VERSION",
14146 -- }
14147 -- -- returns: -lluacov -e 'utils = print(require('\''pl.utils'\'')._VERSION'
14148 function utils.quote_arg(argument)
14149 if type(argument) == "table" then
14150 -- encode an entire table
14151 local r = {}
14152 for i, arg in ipairs(argument) do
14153 r[i] = utils.quote_arg(arg)
14154 end
14155
14156 return concat(r, " ")
14157 end
14158 -- only a single argument
14159 if is_windows then
14160 if argument == "" or argument:find('[ \f\t\v]') then
14161 -- Need to quote the argument.
14162 -- Quotes need to be escaped with backslashes;
14163 -- additionally, backslashes before a quote, escaped or not,
14164 -- need to be doubled.
14165 -- See documentation for CommandLineToArgvW Windows function.
14166 argument = '"' .. argument:gsub([[(\*)"]], [[%1%1\"]]):gsub([[\+$]], "%0%0") .. '"'
14167 end
14168
14169 -- os.execute() uses system() C function, which on Windows passes command
14170 -- to cmd.exe. Escape its special characters.
14171 return (argument:gsub('["^<>!|&%%]', "^%0"))
14172 else
14173 if argument == "" or argument:find('[^a-zA-Z0-9_@%+=:,./-]') then
14174 -- To quote arguments on posix-like systems use single quotes.
14175 -- To represent an embedded single quote close quoted string ('),
14176 -- add escaped quote (\'), open quoted string again (').
14177 argument = "'" .. argument:gsub("'", [['\'']]) .. "'"
14178 end
14179
14180 return argument
14181 end
14182 end
14183
14184 --- error out of this program gracefully.
14185 -- @param[opt] code The exit code, defaults to -`1` if omitted
14186 -- @param msg The exit message will be sent to `stderr` (will be formatted with the extra parameters)
14187 -- @param ... extra arguments for message's format'
14188 -- @see utils.fprintf
14189 -- @usage utils.quit(-1, "Error '%s' happened", "42")
14190 -- -- is equivalent to
14191 -- utils.quit("Error '%s' happened", "42") --> Error '42' happened
14192 function utils.quit(code, msg, ...)
14193 if type(code) == 'string' then
14194 utils.fprintf(io.stderr, code, msg, ...)
14195 io.stderr:write('\n')
14196 code = -1 -- TODO: this is odd, see the test. Which returns 255 as exit code
14197 elseif msg then
14198 utils.fprintf(io.stderr, msg, ...)
14199 io.stderr:write('\n')
14200 end
14201 os.exit(code, true)
14202 end
14203
14204
14205 --- String functions
14206 -- @section string-functions
14207
14208 --- escape any Lua 'magic' characters in a string
14209 -- @param s The input string
14210 function utils.escape(s)
14211 utils.assert_string(1,s)
14212 return (s:gsub('[%-%.%+%[%]%(%)%$%^%%%?%*]','%%%1'))
14213 end
14214
14215 --- split a string into a list of strings separated by a delimiter.
14216 -- @param s The input string
14217 -- @param re optional A Lua string pattern; defaults to '%s+'
14218 -- @param plain optional If truthy don't use Lua patterns
14219 -- @param n optional maximum number of elements (if there are more, the last will remain un-split)
14220 -- @return a list-like table
14221 -- @raise error if s is not a string
14222 -- @see splitv
14223 function utils.split(s,re,plain,n)
14224 utils.assert_string(1,s)
14225 local i1,ls = 1,{}
14226 if not re then re = '%s+' end
14227 if re == '' then return {s} end
14228 while true do
14229 local i2,i3 = find(s,re,i1,plain)
14230 if not i2 then
14231 local last = sub(s,i1)
14232 if last ~= '' then append(ls,last) end
14233 if #ls == 1 and ls[1] == '' then
14234 return {}
14235 else
14236 return ls
14237 end
14238 end
14239 append(ls,sub(s,i1,i2-1))
14240 if n and #ls == n then
14241 ls[#ls] = sub(s,i1)
14242 return ls
14243 end
14244 i1 = i3+1
14245 end
14246 end
14247
14248 --- split a string into a number of return values.
14249 -- Identical to `split` but returns multiple sub-strings instead of
14250 -- a single list of sub-strings.
14251 -- @param s the string
14252 -- @param re A Lua string pattern; defaults to '%s+'
14253 -- @param plain don't use Lua patterns
14254 -- @param n optional maximum number of splits
14255 -- @return n values
14256 -- @usage first,next = splitv('user=jane=doe','=', false, 2)
14257 -- assert(first == "user")
14258 -- assert(next == "jane=doe")
14259 -- @see split
14260 function utils.splitv (s,re, plain, n)
14261 return _unpack(utils.split(s,re, plain, n))
14262 end
14263
14264
14265 --- Functional
14266 -- @section functional
14267
14268
14269 --- 'memoize' a function (cache returned value for next call).
14270 -- This is useful if you have a function which is relatively expensive,
14271 -- but you don't know in advance what values will be required, so
14272 -- building a table upfront is wasteful/impossible.
14273 -- @param func a function that takes exactly one argument (which later serves as the cache key) and returns a single value
14274 -- @return a function taking one argument and returning a single value either from the cache or by running the original input function
14275 function utils.memoize(func)
14276 local cache = {}
14277 return function(k)
14278 local res = cache[k]
14279 if res == nil then
14280 res = func(k)
14281 cache[k] = res
14282 end
14283 return res
14284 end
14285 end
14286
14287
14288 --- associate a function factory with a type.
14289 -- A function factory takes an object of the given type and
14290 -- returns a function for evaluating it
14291 -- @tab mt metatable
14292 -- @func fun a callable that returns a function
14293 function utils.add_function_factory (mt,fun)
14294 _function_factories[mt] = fun
14295 end
14296
14297 local function _string_lambda(f)
14298 if f:find '^|' or f:find '_' then
14299 local args,body = f:match '|([^|]*)|(.+)'
14300 if f:find '_' then
14301 args = '_'
14302 body = f
14303 else
14304 if not args then return raise 'bad string lambda' end
14305 end
14306 local fstr = 'return function('..args..') return '..body..' end'
14307 local fn,err = utils.load(fstr)
14308 if not fn then return raise(err) end
14309 fn = fn()
14310 return fn
14311 else
14312 return raise 'not a string lambda'
14313 end
14314 end
14315
14316
14317 --- an anonymous function as a string. This string is either of the form
14318 -- '|args| expression' or is a function of one argument, '_'
14319 -- @param lf function as a string
14320 -- @return a function
14321 -- @function utils.string_lambda
14322 -- @usage
14323 -- string_lambda '|x|x+1' (2) == 3
14324 -- string_lambda '_+1' (2) == 3
14325 utils.string_lambda = utils.memoize(_string_lambda)
14326
14327
14328 --- bind the first argument of the function to a value.
14329 -- @param fn a function of at least two values (may be an operator string)
14330 -- @param p a value
14331 -- @return a function such that f(x) is fn(p,x)
14332 -- @raise same as @{function_arg}
14333 -- @see func.bind1
14334 -- @usage local function f(msg, name)
14335 -- print(msg .. " " .. name)
14336 -- end
14337 --
14338 -- local hello = utils.bind1(f, "Hello")
14339 --
14340 -- print(hello("world")) --> "Hello world"
14341 -- print(hello("sunshine")) --> "Hello sunshine"
14342 function utils.bind1 (fn,p)
14343 fn = utils.function_arg(1,fn)
14344 return function(...) return fn(p,...) end
14345 end
14346
14347
14348 --- bind the second argument of the function to a value.
14349 -- @param fn a function of at least two values (may be an operator string)
14350 -- @param p a value
14351 -- @return a function such that f(x) is fn(x,p)
14352 -- @raise same as @{function_arg}
14353 -- @usage local function f(a, b, c)
14354 -- print(a .. " " .. b .. " " .. c)
14355 -- end
14356 --
14357 -- local hello = utils.bind1(f, "world")
14358 --
14359 -- print(hello("Hello", "!")) --> "Hello world !"
14360 -- print(hello("Bye", "?")) --> "Bye world ?"
14361 function utils.bind2 (fn,p)
14362 fn = utils.function_arg(1,fn)
14363 return function(x,...) return fn(x,p,...) end
14364 end
14365
14366
14367
14368
14369 --- Deprecation
14370 -- @section deprecation
14371
14372 do
14373 -- the default implementation
14374 local deprecation_func = function(msg, trace)
14375 if trace then
14376 warn(msg, "\n", trace) -- luacheck: ignore
14377 else
14378 warn(msg) -- luacheck: ignore
14379 end
14380 end
14381
14382 --- Sets a deprecation warning function.
14383 -- An application can override this function to support proper output of
14384 -- deprecation warnings. The warnings can be generated from libraries or
14385 -- functions by calling `utils.raise_deprecation`. The default function
14386 -- will write to the 'warn' system (introduced in Lua 5.4, or the compatibility
14387 -- function from the `compat` module for earlier versions).
14388 --
14389 -- Note: only applications should set/change this function, libraries should not.
14390 -- @param func a callback with signature: `function(msg, trace)` both arguments are strings, the latter being optional.
14391 -- @see utils.raise_deprecation
14392 -- @usage
14393 -- -- write to the Nginx logs with OpenResty
14394 -- utils.set_deprecation_func(function(msg, trace)
14395 -- ngx.log(ngx.WARN, msg, (trace and (" " .. trace) or nil))
14396 -- end)
14397 --
14398 -- -- disable deprecation warnings
14399 -- utils.set_deprecation_func()
14400 function utils.set_deprecation_func(func)
14401 if func == nil then
14402 deprecation_func = function() end
14403 else
14404 utils.assert_arg(1, func, "function")
14405 deprecation_func = func
14406 end
14407 end
14408
14409 --- raises a deprecation warning.
14410 -- For options see the usage example below.
14411 --
14412 -- Note: the `opts.deprecated_after` field is the last version in which
14413 -- a feature or option was NOT YET deprecated! Because when writing the code it
14414 -- is quite often not known in what version the code will land. But the last
14415 -- released version is usually known.
14416 -- @param opts options table
14417 -- @see utils.set_deprecation_func
14418 -- @usage
14419 -- warn("@on") -- enable Lua warnings, they are usually off by default
14420 --
14421 -- function stringx.islower(str)
14422 -- raise_deprecation {
14423 -- source = "Penlight " .. utils._VERSION, -- optional
14424 -- message = "function 'islower' was renamed to 'is_lower'", -- required
14425 -- version_removed = "2.0.0", -- optional
14426 -- deprecated_after = "1.2.3", -- optional
14427 -- no_trace = true, -- optional
14428 -- }
14429 -- return stringx.is_lower(str)
14430 -- end
14431 -- -- output: "[Penlight 1.9.2] function 'islower' was renamed to 'is_lower' (deprecated after 1.2.3, scheduled for removal in 2.0.0)"
14432 function utils.raise_deprecation(opts)
14433 utils.assert_arg(1, opts, "table")
14434 if type(opts.message) ~= "string" then
14435 error("field 'message' of the options table must be a string", 2)
14436 end
14437 local trace
14438 if not opts.no_trace then
14439 trace = debug.traceback("", 2):match("[\n%s]*(.-)$")
14440 end
14441 local msg
14442 if opts.deprecated_after and opts.version_removed then
14443 msg = (" (deprecated after %s, scheduled for removal in %s)"):format(
14444 tostring(opts.deprecated_after), tostring(opts.version_removed))
14445 elseif opts.deprecated_after then
14446 msg = (" (deprecated after %s)"):format(tostring(opts.deprecated_after))
14447 elseif opts.version_removed then
14448 msg = (" (scheduled for removal in %s)"):format(tostring(opts.version_removed))
14449 else
14450 msg = ""
14451 end
14452
14453 msg = opts.message .. msg
14454
14455 if opts.source then
14456 msg = "[" .. opts.source .."] " .. msg
14457 else
14458 if msg:sub(1,1) == "@" then
14459 -- in Lua 5.4 "@" prefixed messages are control messages to the warn system
14460 error("message cannot start with '@'", 2)
14461 end
14462 end
14463
14464 deprecation_func(msg, trace)
14465 end
14466
14467 end
14468
14469
14470 return utils
14471
14472
14473
14474 end,
14475
14476 ----------------------
14477 -- Modules part end --
14478 ----------------------
14479 }
14480 if files[path] then
14481 return files[path]
14482 else
14483 return origin_seacher(path)
14484 end
14485 end
14486 end
14487 ---------------------------------------------------------
14488 ----------------Auto generated code block----------------
14489 ---------------------------------------------------------
14490 return require('pl.import_into')()