-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstdlib.lua
881 lines (766 loc) · 18.5 KB
/
stdlib.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
--[[
if not prev_assert then prev_assert = assert end
function assert(...)
dlog_flush()
prev_assert(...)
end
--]]
function max(a, b, ...)
if b == nil then return a end
if a >= b then
return max(a, ...)
else
return max(b, ...)
end
end
function min(a, b, ...)
if b == nil then return a end
if a <= b then
return min(a, ...)
else
return min(b, ...)
end
end
-- puts the keys of t into an "array"
function keys(t)
local r = {}
for k, v in pairs(t) do
r[1+#r] = k
end
table.sort(r)
return r
end
-- values as an array
function values(t)
local r = {}
for k, v in pairs(t) do
r[1+#r] = v
end
return r
end
function sorted(t, compfn)
local r = {}
for k, v in pairs(t) do
r[k] = v
end
table.sort(r, compfn)
return r
end
function startswith(s, pattern)
local i, j
i, j = string.find(s, pattern, 1)
return i == 1
end
--[[
function is_seq(t)
local keys = {}
local i = 0
for k, v in pairs(t) do
i = i + 1
local is_num_key = (type(k) == 'number')
if not is_num_key then return nil end -- all numeric keys
if not (k == i) then return nil end -- no holes
end
return 1
end
--]]
function is_seq(t)
local n = 0
for k, v in pairs(t) do
n = n + 1
end
return #t == n -- no other keys except those in table's "array view".
end
function is_list(t)
return is_seq(t)
end
function obj_to_str(v)
local v_str = v
if type(v) == 'table' then
if is_seq(v) then
v_str = list_to_str(v)
else
v_str = map_to_str(v)
end
end
if type(v) == 'function' then
v_str = '<function>'
end
if type(v) == 'boolean' then
if v == true then v_str = 'true' else v_str = 'false' end
end
return v_str
end
function list_to_str(x)
if #x == 0 then return '[]' end
local s = ''
if #x > 1 and #x <= 4 then
s = s .. '('
else
s = s .. '['
end
for i, v in ipairs(x) do
if i > 1 then s = s .. ', ' end
local v_str = obj_to_str(v)
s = s .. v_str
end
if #x > 1 and #x <= 4 then
s = s .. ')'
else
s = s .. ']'
end
return s
end
function map_to_str(x)
local s = '{'
local n = 1
for k, v in pairs(x) do
if n > 1 then s = s .. ', ' end
local v_str = obj_to_str(v)
s = s .. k .. '=' .. v_str
n = n + 1
end
s = s .. '}'
return s
end
function range(l, starti, endi)
local t = {}
if not starti then starti = 1 end
if not endi then endi = #l end
for i = starti, endi do
t[1+#t] = l[i]
end
return t
end
function find_embedded_string_positions(instr, starti, endi)
local t = {}
if not starti then starti = 1 end
if not endi then endi = string.len(instr) end
local s = instr;
-- dlog('find_embedded_string_positions', 's=', string.sub(s, starti, endi))
local offset = 0
while starti < endi do
local sbegin, send;
assert(starti < endi)
sbegin = string.find(s, '%f[\'"]', starti)
-- dlog('find_embedded_string_positions', 'sbegin=', sbegin)
if not sbegin then break end
if sbegin >= (endi-1) then break end
assert(sbegin < endi)
send = string.find(s, '%f[\'"]', sbegin+1)
if not send then break end
t[1+#t] = {offset+sbegin, offset+send}
--dlog('find_embedded_string_positions', 'found string in range:', t[#t], ' = ', string.sub(instr, table.unpack(t[#t])))
--dlog('find_embedded_string_positions', 'sbegin=', sbegin, ' send=', send, ' sub=', string.sub(s, sbegin, send))
starti = send + 1
if starti > endi then break end
s = string.sub(s, starti)
offset = offset + starti - 1
starti = 1
endi = string.len(s)
-- dlog('find_embedded_string_positions', 's=', s)
end
return t
end
-- ranges is a list of 2-element lists (e.g., as returned by func above)
-- ranges have to be sorted by beginning subrange.
-- ranges cannot overlap.
function string_copy_excluding_ranges(s, ranges)
local r = ''
if #ranges == 0 then
r = s
return r
end
-- at least one range.
local i = 1
local prev_end = 0
for i = 1, #ranges do
local curr_begin, curr_end = table.unpack(ranges[i])
--dlog('scer', 'i=', i, 'curr_begin=', curr_begin, ' curr_end=', curr_end)
local left_of_range = string.sub(s, prev_end+1, curr_begin-1)
--dlog('scer', 'left_of_range=', left_of_range)
r = r .. left_of_range
prev_end = curr_end
end
--dlog('scer', 'prev_end=', prev_end)
local right_of_range = string.sub(s, prev_end+1)
--dlog('scer', 'right_of_range=', right_of_range)
r = r .. right_of_range
return r
end
stdlib = {
scer = string_copy_excluding_ranges,
fesp = find_embedded_string_positions,
disabled_dlog_sections = {} -- string keys
}
-- a,b,c -> [a, b, c]
-- a,b,c, -> [a, b, c, <empty value>]
-- ,a,b,c -> [<empty>, a, b, c]
-- TODO: return the separators also in parts?
function split(s, pattern)
local i, j, j0
local parts = {}
if #s == 0 then return parts end
i = nil
j = nil
j0 = 0
i, j = string.find(s, pattern, j0+1)
while i do
parts[1+#parts] = string.sub(s, j0+1, i-1)
j0 = j
i, j = string.find(s, pattern, j0+1)
end
parts[1+#parts] = string.sub(s, j0+1)
return parts
end
function splitfn(pattern)
local f = function(s) return split(s, pattern) end
return f
end
-- bind_back(f, a, b, c)(e, f, g) = f(e, f, g, a, b, c)
function bind_back(f, ...)
local args = table.pack(...)
local r = function(...) return f(..., table.unpack(args)) end -- closure
return r
end
-- bind_front(f, a, b, c)(e, f, g) = f(a, b, c, e, f, g)
function bind_front(f, ...)
local args = table.pack(...)
local r = function(...) return f(table.unpack(args), ...) end
return r
end
--[[
-- bindafter(f, a, b, c)(e, f, g) = f(e, f, g, a, b, c)
function bindafter(f, ...)
local args = table.pack(...)
local r = function(...) return f(..., table.unpack(args)) end
return r
end
-- bindbefore(f, a, b, c)(e, f, g) = f(a, b, c, e, f, g)
function bindbefore(f, ...)
local args = table.pack(...)
local r = function(...) return f(table.unpack(args), ...) end
return r
end
--]]
function join(l, sep, starti, endi)
local s = ''
if not starti then starti = 1 end
if not endi then endi = #l end
for i = starti, endi do
if i > starti then s = s .. sep end
s = s .. l[i]
end
return s
end
function dlog_snippet(x)
if x == nil then
return 'nil'
end
if type(x) == 'table' then
if is_seq(x) then
return list_to_str(x)
else
return map_to_str(x)
end
elseif type(x) == 'boolean' then
if x == true then return 'true' else return 'false' end
elseif type(x) == 'function' then
return '<function>'
end
return x
end
function center_string(s, n)
local padding = n - #s
local left = math.floor((n - #s) / 2)
local right = padding - left
local r
if padding == 0 then
r = s
elseif padding > 0 then -- s is shorter than n chars
r = rep(' ', left) .. s .. rep(' ', right)
else
assert(padding < 0) -- s is more than n chars.
r = pad_string(s, n) -- use same algo as pad_string
end
return r
end
-- do something if s is shorter/longer than n.
function pad_string(s, n)
local padding = n - #s
local r
if padding == 0 then
r = s
elseif padding > 0 then -- s is shorter than n chars
-- pad on the left
r = rep(' ', padding) .. s
else
-- truncate from the right; delta is negative we need a positive offset
-- fancy lol: use fewer chars for trunc marker if s is just a bit longer
-- fancy2 lol: use the negative offsets of string.sub.
local trunc_marker = string.sub('...', padding)
local offset = (#s + #trunc_marker) - n
r = string.sub(s, 1, -offset-1) .. trunc_marker
end
return r
end
function dlog_flush()
io.output():flush()
end
function dlogue(loc, level, ...)
if stdlib.disabled_dlog_sections[loc] == 1 then return end
if stdlib.disabled_dlog_sections['*'] == 1 and
stdlib.disabled_dlog_sections[loc] ~= 0 then
return -- all disabled, and this is not explicitly enabled.
end
local loc_str
if loc == nil then loc_str = '<any>' else loc_str = loc end
if type(loc) == 'table' then
loc_str = join(loc, '.')
end
loc_str = pad_string(loc_str, 12)
io.write('dlog', level, ' ', loc_str, ': ')
for i = 1, select('#', ...) do
-- if i > 1 then io.write(', ') end
local arg = select(i, ...)
io.write(dlog_snippet(arg))
end
io.write('\n')
end
function dlog(loc, ...)
dlogue(loc, 1, ...)
end
function dlog1(...)
return dlog(...)
end
function dlog8(loc, ...)
dlogue(loc, 8, rep(' ', 4), ...)
end
function dlog6(loc, ...)
dlogue(loc, 6, rep(' ', 3), ...)
end
function dlog4(loc, ...)
dlogue(loc, 4, rep(' ', 2), ...)
end
function dlog2(loc, ...)
dlogue(loc, 2, rep(' ', 1), ...)
end
function dlogue_lines(loc, level, title, lines)
if stdlib.disabled_dlog_sections[loc] == 1 then return end
if stdlib.disabled_dlog_sections['*'] == 1 then return end
local loc_str = loc
if type(loc) == 'table' then
loc_str = join(loc, '.')
end
local s = 'llog' .. level .. ' ' .. loc .. ': '
io.write(s, dlog_snippet(title), '\n')
assert(type(lines) == 'table')
if is_seq(lines) then
for i = 1, #lines do
io.write(rep(' ', #s), ' ', rep(' ', 1+math.floor(level/2)))
io.write(i, '. ', dlog_snippet(lines[i]))
io.write('\n')
end
else
local i = 0
for k, v in pairs(lines) do
i = i + 1
io.write(rep(' ', #s), ' ', rep(' ', 1+math.floor(level/2)))
io.write('+ ', dlog_snippet(k), ' -> ', dlog_snippet(v))
io.write('\n')
end
end
-- io.write('\n')
end
--[[
function dlogue_lines(loc, level, title, ...)
if stdlib.disabled_dlog_sections[loc] then return end
local loc_str = loc
if type(loc) == 'table' then
loc_str = join(loc, '.')
end
local args = {}
for i = 1, select('#', ...) do
local arg = select(i, ...)
table.insert(args, arg)
end
local s = 'llog' .. level .. ' ' .. loc .. ': '
io.write(s, dlog_snippet(title), '\n')
for i = 1, #args do
io.write(rep(' ', #s), ' ', rep(' ', 1+math.floor(level/2)))
io.write(i, '. ', dlog_snippet(args[i]))
io.write('\n')
end
-- io.write('\n')
end
--]]
function dlog_lines(loc, ...)
dlogue_lines(loc, 1, ...)
end
function map_to_kv_pairs(t)
local r = {}
for k, v in pairs(t) do
table.insert(r, {k, v})
end
return r
end
-- r = m1 - m2
function set_difference(m1, m2)
local r = {}
for k, v in pairs(m1) do
if not m2[k] then
table.insert(r, k)
end
end
return r
end
function list_difference(l1, l2)
local m1 = {}
local m2 = {}
for i, v in ipairs(l1) do m1[v] = 1 end
for i, v in ipairs(l2) do m2[v] = 1 end
return set_difference(m1, m2)
end
function dlog_disable(section, ...)
stdlib.disabled_dlog_sections[section] = 1
for i = 1, select('#', ...) do
local s = select(i, ...)
stdlib.disabled_dlog_sections[s] = 1
end
end
function dlog_enable(section, ...)
stdlib.disabled_dlog_sections[section] = 0
for i = 1, select('#', ...) do
local s = select(i, ...)
stdlib.disabled_dlog_sections[s] = 0
end
end
function dlogger(me, debug_level, ...)
local args = {}
assert(me ~= nil)
table.insert(args, me)
if debug_level ~= nil then table.insert(args, debug_level) end
for i = 1, select('#', ...) do
local s = select(i, ...)
table.insert(args, s)
end
return bind_front(dlog, table.unpack(args))
end
function rep(s, n)
local r = ''
for i = 1, n do
r = r .. s
end
return r
end
-- remove leading and trailing space.
-- use gsub
function trim(s)
if type(s) == 'table' then
return map(s, trimleft, trimright)
end
return trimright(trimleft(s))
end
function trimleft(s)
if type(s) == 'table' then
return map(s, trimleft)
end
local t = string.gsub(s, '^%s+', '')
return t
end
function trimright(s)
if type(s) == 'table' then
return map(s, trimleft)
end
local t = string.gsub(s, '%s+$', '')
return t
end
--[[
function map(l, f)
local o = {}
for i, v in ipairs(l) do
o[1+#o] = f(v)
end
return o
end
--]]
function list_sum(l)
local r = 0
for i, v in ipairs(l) do
r = r + v
end
return r
end
function list_uniq(l)
local r = {}
for i, v in ipairs(l) do
r[v] = 1
end
return keys(r)
end
-- functions are applied from left to right with short-circuiting (f first).
function map_table(l, f, ...)
local o = {}
for k, v in pairs(l) do
local v2, k2 = f(v, k)
for j = 1, select('#', ...) do
local g = select(j, ...)
v2, k2 = g(v2, k)
end
o[k] = v2
end
return o
end
-- functions are applied from left to right with short-circuiting (f first).
function filter_table(l, f, ...)
local o = {}
for k, v in pairs(l) do
local ok = f(v, k)
for j = 1, select('#', ...) do
local g = select(j, ...)
ok = (ok == true) and g(v, k) -- short-circuiting
end
if ok == true then
o[k] = v
end
end
return o
end
-- functions are applied from left to right with short-circuiting (f first).
function filter(l, f, ...)
local o = {}
for i, v in ipairs(l) do
local ok = f(v, i)
for j = 1, select('#', ...) do
local g = select(j, ...)
ok = (ok == true) and g(v, i) -- short-circuiting
end
if ok == true then
o[1+#o] = v
end
end
return o
end
-- functions are applied from left to right with short-circuiting (f first).
function filter_anytrue(l, f, ...)
local o = {}
for i, v in ipairs(l) do
local ok = f(v)
for j = 1, select('#', ...) do
local g = select(j, ...)
ok = ok or g(v, i) -- short-circuiting
end
if ok == true then
o[1+#o] = v
end
end
return o
end
-- returns [g(f(l[1])), g(f(l[2])), ...]
-- functions are applied from left to right.
function map(l, f, ...)
local o = {}
for i, v in ipairs(l) do
local t = f(v, i)
for j = 1, select('#', ...) do
local g = select(j, ...)
t = g(t, i)
end
o[1+#o] = t
end
return o
end
-- apply first function on x.
-- then apply the second function on the first result.
-- third on the second etc etc.
-- compose('a, b , c,d', splitfn(','), trim)
-- returns ['a', 'b', 'c', 'd']
function compose(x, f, ...)
local o = f(x)
for i = 1, select('#', ...) do
local g = select(i, ...)
o = g(o)
end
return o
end
-- Same as the previous but the function object to be operated upon is
-- the *LAST* argument. The function declaration is written as below
-- for documentation purposes ('x' is by convention the name of the
-- object to be acted upon).
--
-- In the code itself, we rely on dynamic typing to finally use the
-- last argument as 'x'. But we need a minium of one function and one
-- object i.e., a minimum of two arguments.
function compose2(f, x, ...)
assert(f ~= nil)
assert(x ~= nil)
if (f == nil) or (x == nil) then
return nil
end
local args = {f, x}
for i = 1, select('#', ...) do
local g = select(i, ...)
assert(g ~= nil)
if g == nil then
return nil
end
table.insert(args, g)
end
local obj = table.remove(args)
return compose(obj, table.unpack(args))
end
function list_max(l)
local o;
for i, v in ipairs(l) do
if i == 1 then
o = v
end
if (not (v == nil)) and (not (o == nil)) then
if v > o then
o = v
end
end
end
return o
end
function list_min(l)
local o;
for i, v in ipairs(l) do
if i == 1 then
o = v
end
if (not (v == nil)) and (not (o == nil)) then
if v < o then
o = v
end
end
end
return o
end
-- returns the index, nil if not found.
function list_find(l, needle)
for i, v in ipairs(l) do
if v == needle then
return i
end
end
return nil
end
_printt_stats = {PASS=0, FAIL=0, DONTCARE=0}
function printt(val, checker)
local res = 'PASS'
if checker then
if checker(val) ~= true then res = 'FAIL' end
else
if val == nil then res = 'FAIL' else res = 'DONTCARE' end
end
_printt_stats[res] = _printt_stats[res] + 1
print(dlog_snippet(val), '->', res)
if res == 'PASS' then return true, val else return false end
end
function expect_zero(r) if type(r) == 'number' and r == 0 then return true else return false end end
function expect_one(r) if type(r) == 'number' and r == 1 then return true else return false end end
function expect_false(r) if r == false then return true else return false end end
function expect_true(r) if r == true then return true else return false end end
function expect_string(s)
local checker = function(r)
if r == s then return true else return false end
end
return checker
end
function expect_int(n)
local checker = function(r)
if type(r) == 'number' and r == n then return true else return false end
end
return checker
end
function serialize (o)
local s
if type(o) == "number" then
s = '' .. o
elseif type(o) == "string" then
s = string.format("%q", o)
elseif type(o) == "table" then
s = "{\n"
for k,v in pairs(o) do
local quoted_k = string.format("%q", k)
local safe_k
if quoted_k == k then safe_k = k else safe_k = quoted_k end
s = s .. " " .. safe_k .. " = "
s = s .. serialize(v)
s = s .. ",\n"
end
s = s .. "}\n"
else
error("cannot serialize a " .. type(o))
s = nil
end
return s
end
function set_file_contents(lfn, data)
assert(type(data) == 'string')
local fh = io.open(lfn, "wb")
fh:write(data)
fh:close()
end
function get_file_contents(lfn)
local fh = io.open(lfn, "rb")
local data = fh:read('*all')
fh:close()
return data
end
function cwd()
return os.getenv('PWD')
end
function path_join(a, b)
return a .. '/' .. b
end
-- =============================
local lfn = path_join(cwd(), "out/libcpp.so")
local luaopen_libcpp = package.loadlib(lfn, "luaopen_libcpp")
if luaopen_libcpp == nil then
print('Error opening shared library libcpp.so from: ', lfn)
end
assert(luaopen_libcpp ~= nil)
local libcpp = luaopen_libcpp()
function int_to_hex64(n)
return libcpp.int_to_hex64(n)
end
function is_bare_filename(fn)
return libcpp.fs_has_root_path(fn) == 0
end
function file_size(fn)
return libcpp.fs_file_size(fn)
end
-- dn is a directory path.
function space_in_dir(dn)
local si = libcpp.fs_space(dn)
if si then return si.available else return nil end
function test_00()
x = libcpp.fs_space("/var")
print(x.available)
for k, v in pairs(x) do
print('k: ', k, ' v: ', v)
end
end
end
local M = {}
M.libcpp = libcpp
M.cpp = libcpp
M.dlog_snippet = dlog_snippet
M.rep = rep
M.dlog = dlog
M.dlog1 = dlog1
M.dlog2 = dlog2
M.dlog4 = dlog4
M.dlog6 = dlog6
M.dlog8 = dlog8
M.printt = printt
M.serialize = serialize
M.set_file_contents = set_file_contents
M.get_file_contents = get_file_contents
M.is_bare_filename = is_bare_filename
M.int_to_hex64 = int_to_hex64
M.file_size = file_size
M.space_in_dir = space_in_dir
return M