-
Notifications
You must be signed in to change notification settings - Fork 45
/
olua.lua
1479 lines (1342 loc) · 39.2 KB
/
olua.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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local cjson
xpcall(function ()
cjson = require "cjson.safe"
end, function ()
cjson = {}
end)
local is_windows = package.config:find("\\")
local _ipairs = ipairs
function ipairs(t)
local mt = getmetatable(t)
return (mt and mt.__ipairs or _ipairs)(t)
end
local _pairs = pairs
function pairs(t)
local mt = getmetatable(t)
return (mt and mt.__pairs or _pairs)(t)
end
olua = {}
---Suppress warnings and hook the value used in `olua.format`.
---@param ... unknown
function olua.use(...) end
function olua.print(fmt)
print(olua.format(fmt))
end
function olua.isdir(path)
if not string.find(path, "[/\\]$") then
path = path .. "/"
end
local ok, err, code = os.rename(path, path)
if not ok then
if code == 13 then
return true
end
end
return ok, err
end
function olua.mkdir(dir)
if not olua.isdir(dir) then
if is_windows then
os.execute("mkdir " .. dir:gsub("/", "\\"))
else
os.execute("mkdir -p " .. dir)
end
end
end
function olua.write(path, content)
path = olua.format(path)
local f = io.open(path, "rb")
if f then
local flag = f:read("*a") == content
f:close()
if flag then
olua.print("up-to-date: ${path}")
return
end
end
olua.print("write: ${path}")
local dir = path:match("(.*)/[^/]+$")
if dir then
olua.mkdir(dir)
end
f = io.open(path, "w+b")
assert(f, path)
f:write(content)
f:flush()
f:close()
end
-------------------------------------------------------------------------------
-- Error handle
-------------------------------------------------------------------------------
local willdo = ""
---Will do the job.
---@param message string
function olua.willdo(message)
willdo = olua.format(message)
end
local function throw_error(msg)
if #willdo > 0 then
print(willdo)
end
error(msg)
end
---Throw error.
---@param message string
function olua.error(message)
throw_error(olua.format(message))
end
---Check the value
---@generic T
---@param value T
---@param message? string
---@return T
function olua.assert(value, message)
if not value then
olua.error(message or "<no assert info>")
end
return value
end
-------------------------------------------------------------------------------
-- array & map & string
-------------------------------------------------------------------------------
---Split the string.
---@param str string
---@param sep string
---@return array
function olua.split(str, sep)
local arr = olua.array()
for s in str:gmatch("([^" .. sep .. "]+)") do
arr:push(s)
end
return arr
end
---Join the array.
---@param arr array
---@param sep string
---@param prefix? string
---@param posfix? string
---@return unknown
function olua.join(arr, sep, prefix, posfix)
prefix = prefix or ""
posfix = posfix or ""
return prefix .. table.concat(arr, sep) .. posfix
end
---Clone a table.
---@param t table
---@param new? table
function olua.clone(t, new)
new = new or {}
for k, v in pairs(t) do
if type(v) == "table" then
if v.clone then
new[k] = v:clone()
else
new[k] = olua.clone(v)
end
else
new[k] = v
end
end
return new
end
---Get the keys of a table.
---@param t table
---@return array
function olua.keys(t)
local keys = olua.array()
for k in pairs(t) do
keys:push(k)
end
return keys
end
---Iterate over the table.
---@param t table
---@param fn fun(value:any, key:string|integer, t:table)
function olua.foreach(t, fn)
for k, v in pairs(t) do
fn(v, k, t)
end
end
---Get the values of a table.
---@param t table
---@return array
function olua.values(t)
local values = olua.array()
for _, v in pairs(t) do
values:push(v)
end
return values
end
---Sort the table.
---@param t table
---@param field? string|fun(a:any, b:any):boolean
function olua.sort(t, field)
if type(field) == "function" then
table.sort(t, field)
elseif field then
table.sort(t, function (a, b)
return a[field] < b[field]
end)
else
table.sort(t)
end
return t
end
---@param t any
---@return array
function olua.make_array(t)
local arr = olua.array()
setmetatable(t, getmetatable(arr))
return t
end
---@param t any
---@return ordered_map
function olua.make_ordered_map(t)
local map = olua.ordered_map()
for k, v in pairs(t) do
map:set(k, v)
t[k] = nil
end
setmetatable(map, nil)
for k, v in pairs(map) do
t[k] = v
end
setmetatable(t, t)
return t
end
---Create a new array.
---@param sep? string
---@param prefix? string
---@param posfix? string
---@return array
function olua.array(sep, prefix, posfix)
---@class array
---@field private __tostring fun(self):string
---@field private __olua_type string
local array = {
__olua_type = "olua.array"
}
local joiner = { sep = sep, prefix = prefix, posfix = posfix }
local function __tostring(self)
return self:join(joiner.sep or "", joiner.prefix, joiner.posfix)
end
if sep then
array.__tostring = __tostring
end
---@private
array.__index = array
---Clear the array.
function array:clear()
for i = 1, #self do
self[i] = nil
end
end
---Clone the array.
---@return array
function array:clone()
local arr = olua.array(joiner.sep, joiner.prefix, joiner.posfix)
for _, v in ipairs(self) do
arr:push(olua.clone(v))
end
return arr
end
---Get an element at the given index. If `index` is negative, it is relative to the end of the array.
---@param index integer
---@return any
function array:at(index)
if index < 0 then
index = #self + index + 1
end
return self[index]
end
---Push an element at the end of the array. If `value` is `nil`, nothing is done.
---@param value any
---@return any # Return `value`.
function array:push(value)
if value ~= nil then
table.insert(self, value)
end
return value
end
---Push a formatting string at the end of the array.
---@param value string
---@param indent? integer
---@return self
function array:pushf(value, indent)
self:push(olua.format(value, indent))
return self
end
---Remove and return the last element of the array.
---@return any
function array:pop()
return table.remove(self)
end
---Remove and return the first element of the array.
function array:shift()
return table.remove(self, 1)
end
---Push an element at the beginning of the array. If `value` is `nil`, nothing is done.
---@param value any
function array:unshift(value)
if value ~= nil then
table.insert(self, 1, value)
end
end
---Insert an element at the specified position. If `value` is `nil`, nothing is done.
---@param index integer
---@param value any
function array:insert(index, value)
if value ~= nil then
table.insert(self, index, value)
end
end
---Remove an element from the array.
---@param value any
function array:remove(value)
for i = 1, #self do
if self[i] == value then
table.remove(self, i)
break
end
end
end
---Remove an element at the specified position from the array.
---@param index any
---@return unknown|nil
function array:remove_at(index)
if index >= 1 and index <= #self then
return table.remove(self, index)
end
end
---Concatenate the array with another array.
---@param arr any[]
---@return self
function array:concat(arr)
for _, v in ipairs(arr) do
self:push(v)
end
return self
end
---
---Return the index of the value, or 0 if not found.
---
---@param value any
---@return integer
function array:index_of(value)
for i, v in ipairs(self) do
if v == value then
return i
end
end
return 0
end
---Sort the array.
---@param fn? string | fun(a:any, b:any):boolean
---@return self
function array:sort(fn)
return olua.sort(self, fn)
end
---Get a slice of the array.
---@param from? integer
---@param to? integer
---@return array
function array:slice(from, to)
local arr = olua.array(joiner.sep, joiner.prefix, joiner.posfix)
for i = from or 1, to or #self do
if i > #self then
break
end
arr:push(self[i])
end
return arr
end
---Iterate over the array.
---@param fn fun(value:any, index:integer, array:array)
function array:foreach(fn)
for k, v in ipairs(self) do
fn(v, k, self)
end
end
---Join the array with a separator.
---@param sep string
---@param prefix? string
---@param posfix? string
---@diagnostic disable-next-line: redefined-local
function array:join(sep, prefix, posfix)
prefix = prefix or ""
posfix = posfix or ""
return prefix .. table.concat(self, sep) .. posfix
end
---Return a new array with unique values.
---@return array
function array:toset()
local filter = {}
local arr = olua.array(joiner.sep, joiner.prefix, joiner.posfix)
for _, v in ipairs(self) do
if not filter[v] then
arr:push(v)
filter[v] = true
end
end
return arr
end
---Return a new array with filtered values.
---@param fn fun(value:any, index:integer, array:array):boolean
---@return array
function array:filter(fn)
local arr = olua.array(joiner.sep, joiner.prefix, joiner.posfix)
for i, v in ipairs(self) do
if fn(v, i, self) then
arr:push(v)
end
end
return arr
end
---Find an element in the array.
---@param fn fun(value:any, index:integer, array:array):boolean
---@return any
function array:find(fn)
for i, v in ipairs(self) do
if fn(v, i, self) then
return v
end
end
end
---Calls a defined callback function on each element of an array, and returns an array that contains the results.
---@param fn fun(value:any, index:integer, array:array):any
---@return array
function array:map(fn)
local arr = olua.array(joiner.sep, joiner.prefix, joiner.posfix)
for i, v in ipairs(self) do
arr:push(fn(v, i, self))
end
return arr
end
return setmetatable({}, array)
end
---Create a new ordered map.
---@param overwritable? boolean Can overwrite the value with the same key, default is `true`.
---@return ordered_map
function olua.ordered_map(overwritable)
---@class ordered_map
---@field private _keys array
---@field private _map table
local ordered_map = {
__olua_type = "olua.ordered_map",
_keys = olua.array(),
_map = {}
}
overwritable = overwritable ~= false
---@private
---@param key string|integer
---@return any
function ordered_map:__index(key)
return self:get(key)
end
---@private
---@param key string|integer
---@param value any
function ordered_map:__newindex(key, value)
self:set(key, value)
end
---@private
function ordered_map:__len()
return #self._keys
end
---@private
function ordered_map:__pairs()
return pairs(self._map)
end
---@private
function ordered_map:__ipairs()
return ipairs(self:values())
end
---Clone the ordered map.
---@return ordered_map
function ordered_map:clone()
local new_map = olua.ordered_map(overwritable)
self:foreach(function (value, key)
new_map:set(key, olua.clone(value))
end)
return new_map
end
---Set value with the key.
---@param key any
---@param value any
function ordered_map:set(key, value)
if self._keys:index_of(key) == 0 then
if value ~= nil then
self._map[key] = value
self._keys:push(key)
end
elseif overwritable then
self._map[key] = value
if value == nil then
self._keys:remove(key)
end
else
error(string.format("key '%s' already exists", key))
end
end
---Replace value with the key.
---@param key string|integer
---@param value any
function ordered_map:replace(key, value)
self._map[key] = value
if self._keys:index_of(key) == 0 then
self._keys:push(key)
end
end
---Get value with the key.
---@param key string|integer
---@return unknown
function ordered_map:get(key)
return self._map[key]
end
---Check if the key exists.
---@param key string|integer
---@return boolean
function ordered_map:has(key)
return self._map[key] ~= nil
end
---Remove value with the key.
---@param key string|integer
function ordered_map:remove(key)
self._keys:remove(key)
self._map[key] = nil
end
---Take value with the key.
---@param key string|integer
---@return any
function ordered_map:take(key)
local value = self._map[key]
self._keys:remove(key)
self._map[key] = nil
return value
end
---Iterate over the ordered map.
---@param fn fun(value:any, key:string|integer, map:ordered_map)
function ordered_map:foreach(fn)
local keys = self._keys:slice()
for _, key in ipairs(keys) do
fn(self._map[key], key, self)
end
end
---Clear the ordered map.
function ordered_map:clear()
self._keys:clear()
self._map = {}
end
---Return values of the ordered.
---@return array
function ordered_map:values()
local arr = olua.array()
for _, key in ipairs(self._keys) do
arr:push(self._map[key])
end
return arr
end
---Return keys of the ordered.
---@return array
function ordered_map:keys()
return self._keys
end
---Sort the ordered map.
---@param fn? fun(a:any, b:any):boolean
function ordered_map:sort(fn)
self._keys:sort(fn)
return self
end
---@alias insertmode
---|>'"front"'
---| '"after"'
---| '"before"'
---| '"back"'
---Insert an element into the ordered map.
---@param mode insertmode
---@param at_key string|number|nil
---@param key string|number
---@param value any
function ordered_map:insert(mode, at_key, key, value)
local idx = 0
if mode == "front" then
idx = 1
elseif mode == "after" then
idx = self._keys:index_of(at_key)
if idx == 0 then
idx = #self._keys + 1
else
idx = idx + 1
end
elseif mode == "before" then
idx = self._keys:index_of(at_key)
if idx == 0 then
idx = 1
end
elseif mode == "back" then
idx = #self._keys + 1
else
olua.error("invalid insert mode: ${insertmode}")
end
self._keys:insert(idx, key)
self._map[key] = value
end
return setmetatable(ordered_map, ordered_map)
end
-------------------------------------------------------------------------------
--- string util
-------------------------------------------------------------------------------
local FORMAT_PATTERN = "${[%w_.?#()]+}"
local curr_expr = nil
function olua.is_end_with(str, substr)
local _, e = str:find(substr, #str - #substr + 1, true)
return e == #str
end
---@param level integer
---@param key string
---@return any
local function lookup(level, key)
assert(key and #key > 0, key)
while true do
local value
local searchupvalue = true
local info1 = debug.getinfo(level, "fu")
for i = 1, 256 do
local k, v = debug.getlocal(level, i)
if i <= info1.nparams and v == curr_expr then
searchupvalue = false
end
if k == key then
if type(v) ~= "string" or not v:find(FORMAT_PATTERN) then
value = v
end
elseif not k then
break
end
end
if value ~= nil then
return value
end
if searchupvalue then
for i = 1, info1.nups do
local k, v = debug.getupvalue(info1.func, i)
if k == key then
return v
end
end
break
else
level = level + 1
end
end
end
local function lookup_key_expr(level, key_expr)
local key = string.match(key_expr, "[%w_]+")
local value = lookup(level, key)
local first = true
value = value == nil and _G[key] or value
for field in string.gmatch(key_expr, "[^.]+") do
if first then
first = false
elseif value == nil then
break
else
value = value[field]
end
end
return value
end
---@param line string
---@param indent integer
local function eval(line, indent)
local drop = false
local function replace(str)
local level = 1
while true do
local info = debug.getinfo(level, "Sfn")
if info then
if string.find(info.source, "olua.lua$") and
info.func == olua.format
then
break
else
level = level + 1
end
else
break
end
end
local leading_space = string.match(line, " *")
local value, opt, fix
local fn, key = string.match(str, "([%w_.]+)%(([%w_.]+)%)")
if fn then
--- in lookup func, olua.format is level + 2(lookup_key_expr + lookup)
local func = lookup_key_expr(level + 3, fn)
if not func then
throw_error(string.format("function '%s' not found used by '%s'", fn, str))
end
value = lookup_key_expr(level + 3, key)
if not value then
throw_error(string.format("value '%s' not found used by '%s'", key, str))
end
value = func(value)
if value == nil then
throw_error(string.format("%s(%s) return nil in '%s'", fn, key, str))
end
else
-- search in the functin local value
key = string.match(str, "[%w_]+")
opt = string.match(str, "%?+")
fix = string.match(str, "#")
value = lookup(level + 2, key)
value = value == nil and _G[key] or value
for field in string.gmatch(string.match(str, "[%w_.]+"), "[^.]+") do
if value == nil then
break
elseif field ~= key then
value = value[field]
end
end
end
if value == nil and not opt then
throw_error("value not found for '" .. str .. "'")
end
-- indent the value if value has multiline
local prefix, posfix = "", ""
if type(value) == "table" then
local mt = getmetatable(value)
if mt and mt.__tostring then
value = tostring(value)
else
throw_error("no meta method '__tostring' for " .. str)
end
elseif value == nil then
drop = opt == "??"
value = "nil"
elseif type(value) == "string" then
value = value:gsub("[\n]*$", "")
if opt then
value = olua.trim(value)
if value:find("[\n\r]") then
value = "\n" .. value
prefix = "[["
posfix = "\n" .. leading_space .. "]]"
leading_space = leading_space .. string.rep(" ", indent)
elseif value:find('[\'"]') then
value = "[[" .. value .. "]]"
else
value = "'" .. value .. "'"
end
end
else
value = tostring(value)
end
if fix then
value = value:gsub("[^%w_]+", "_"):gsub("_+$", "")
end
return prefix .. value:gsub("\n", "\n" .. leading_space) .. posfix
end
line = line:gsub(FORMAT_PATTERN, replace)
return not drop and line or nil
end
---@param expr string
---@param indent integer
local function doeval(expr, indent)
local arr = {}
local idx = 1
while idx <= #expr do
local from, to = string.find(expr, "[\n\r]", idx)
if not from then
from = #expr + 1
to = from
end
arr[#arr + 1] = eval(string.sub(expr, idx, from - 1), indent)
idx = to + 1
end
return table.concat(arr, "\n")
end
---Trim the expression.
---@param expr string
---@param indent? integer
---@param keepspace? boolean
---@return string
function olua.trim(expr, indent, keepspace)
if type(expr) == "string" then
local idx
expr, idx = expr:gsub("[\n\r]", "\n")
if idx > 0 or not keepspace then
expr = expr:gsub("^[\n]*", "") -- trim head '\n'
expr = expr:gsub("[ \n]*$", "") -- trim tail '\n' or ' '
local space = string.match(expr, "^[ ]*")
expr = expr:gsub("^[ ]*", "") -- trim head space
expr = expr:gsub("\n" .. space, "\n")
if indent and indent ~= 4 then
expr = expr:gsub("\n( +)", function (spaces)
local n = #spaces // 4
return "\n" .. string.rep(" ", n * indent)
end)
end
end
end
return expr
end
---Format the expression.
---
--- Example:
--- ```lua
--- olua.format("${path}/output")
--- olua.format("${olua.tostring(file.path)}")
--- ```
---@param expr string
---@param indent? integer
---@return string
function olua.format(expr, indent)
curr_expr = expr
expr = doeval(olua.trim(expr, indent, true), indent or 4)
while true do
local s, n = expr:gsub("\n[ ]+\n", "\n\n")
expr = s
if n == 0 then
break
end
end
while true do
local s, n = expr:gsub("\n\n\n", "\n\n")
expr = s
if n == 0 then
break
end
end
expr = expr:gsub("{\n\n", "{\n")
expr = expr:gsub("\n\n}", "\n}")
return expr
end
-- TODO: rm
function olua.command_proxy(cmd, parent)
local proxy = {}
assert(cmd.__proxy == nil, "already add command proxy")
cmd.__proxy = proxy
function proxy.__index(_, key)
local f = cmd[key]
if f then
return function (...)
return f(...) or proxy
end
elseif parent and parent.__proxy then
return parent.__proxy[key]
else
error(string.format("command '%s' not found", key))
end
end
function proxy.__newindex(_, key, value)
error(string.format("create command '%s' is not allowed", key))
end
return setmetatable(proxy, proxy)
end
---@param t any
---@param name string
---@return boolean
function olua.has_metafield(t, name)
return olua.get_metafield(t, name) ~= nil
end
---@param t any
---@param name string
---@return unknown
function olua.get_metafield(t, name)
local mt = getmetatable(t)
return mt and mt[name]
end
-------------------------------------------------------------------------------
--- stringify
-------------------------------------------------------------------------------
local function is_array(t)
local mt = getmetatable(t)
if mt and mt.__olua_object then
return false
end
local n = 0
for k in pairs(t) do
n = n + 1
end
if #t ~= n then
return false
else
for i = 1, n do
if t[i] == nil then
return false
end
end
return true
end
end
function olua.as_object(t)
local mt = getmetatable(t)
if not mt then
mt = {}
setmetatable(t, mt)
end
mt.__olua_object = true
end
---Get the comment of a field. If not found, return empty string.
---@param t any
---@param k string
---@param marshal? string
---@return string
function olua.get_comment(t, k, marshal)
local comments = olua.get_metafield(t, "__olua_comment")
local str = comments and comments[k] or ""
if marshal and str ~= "" then