-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathL_LuaXP_Reactor.lua
1699 lines (1612 loc) · 59.5 KB
/
L_LuaXP_Reactor.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
------------------------------------------------------------------------
-- LuaXP is a simple expression evaluator for Lua, based on lexp.js, a
-- lightweight (math) expression evaluator for JavaScript by the same
-- author.
--
-- Author: Copyright (c) 2016,2018 Patrick Rigney <[email protected]>
-- License: MIT License
-- Github: https://github.com/toggledbits/luaxp
------------------------------------------------------------------------
module("L_LuaXP_Reactor", package.seeall)
_VERSION = "1.0.2enh"
_VNUMBER = 10002
_DEBUG = false -- Caller may set boolean true or function(msg)
-- Binary operators and precedence (lower prec is higher precedence)
binops = {
{ op='.', prec=-1 }
, { op='*', prec= 3 }
, { op='/', prec= 3 }
, { op='%', prec= 3 }
, { op='+', prec= 4 }
, { op='-', prec= 4 }
, { op='..', prec= 5 }
, { op='<<', prec= 5 }
, { op='>>', prec= 5 }
, { op='<', prec= 6 }
, { op='<=', prec= 6 }
, { op='>', prec= 6 }
, { op='>=', prec= 6 }
, { op='==', prec= 7 }
, { op='<>', prec= 7 }
, { op='!=', prec= 7 }
, { op='~=', prec= 7 }
, { op='&', prec= 8 }
, { op='^', prec= 9 }
, { op='|', prec=10 }
, { op='&&', prec=11 }
, { op='and', prec=11 }
, { op='||', prec=12 }
, { op='or', prec=12 }
, { op='=', prec=14 }
}
local ARRAYMAX = 1000 -- max length of unbounded array
local ARRAYNULL = false -- default false = cannot insert NULL as array element (push, unshift)
local MAXPREC = 99 -- value doesn't matter as long as it's >= any used in binops
local base = _G
local string = require("string")
local math = require("math")
local CONST = 'const'
local VREF = 'vref'
local FREF = 'fref'
local UNOP = 'unop'
local BINOP = 'binop'
local TNUL = 'null'
local NULLATOM = { __type=TNUL }
setmetatable( NULLATOM, { __tostring=function() return "null" end } )
local charmap = { t = "\t", r = "\r", n = "\n" }
local reservedWords = {
['false']=false, ['true']=true
, pi=math.pi, PI=math.pi
, ['null']=NULLATOM, ['NULL']=NULLATOM, ['nil']=NULLATOM
}
local function dump(t, seen)
if seen == nil then seen = {} end
local typ = base.type(t)
if typ == "table" and seen[t]==nil then
seen[t] = 1
local st = "{ "
local first = true
for n,v in base.pairs(t) do
if not first then st = st .. ", " end
st = st .. n .. "=" .. dump(v, seen)
first = false
end
st = st .. " }"
return st
elseif typ == "string" then
return string.format("%q", t)
elseif typ == "boolean" or typ == "number" then
return base.tostring(t)
end
return string.format("(%s)%s", typ, base.tostring(t))
end
-- Debug output function. If _DEBUG is false or nil, no output.
-- If function, uses that, otherwise print()
local function D(s, ...) -- luacheck: ignore 212
if not _DEBUG then return end
local str = string.gsub(s, "%%(%d+)", function( n )
n = base.tonumber(n, 10)
if n < 1 or n > #arg then return "nil" end
local val = arg[n]
if base.type(val) == "table" then
return dump(val)
elseif base.type(val) == "string" then
return string.format("%q", val)
end
return base.tostring(val)
end
)
if base.type(_DEBUG) == "function" then _DEBUG(str) else print(str) end
end
-- Forward declarations
local _comp, _run, runfetch, scan_token
-- Utility functions
local function deepcopy( t )
if base.type(t) ~= "table" then return t end
local r = {}
for k,v in base.pairs( t ) do
if base.type(v) == "table" then
r[k] = deepcopy(v)
else
r[k] = v
end
end
return r
end
-- Value is atom if it matches our atom pattern, and specific atom type if passed
local function isAtom( v, typ )
return base.type(v) == "table" and v.__type ~= nil and ( typ == nil or v.__type == typ )
end
-- Special case null atom
function isNull( v )
return isAtom( v, TNUL )
end
local function is_non( v ) return v == nil or isNull( v ) end
local function _newerr(r)
r.__source = r.__source or "luaxp"
local m = getmetatable( r ) or {}
m.__tostring = function(t) return string.format("[%s]%s%s", t.__source,
t.message or "unspecified error",
t.location and ( " at " .. tostring(t.location) ) or "" ) end
setmetatable( r, m )
return r
end
local function comperror(msg, loc)
D("throwing comperror at %1: %2", loc, msg)
return base.error( _newerr{ ['type']='compile', location=loc, message=msg } )
end
function evalerror(msg, loc)
D("throwing evalerror at %1: %2", loc, msg)
return base.error( _newerr{ ['type']='evaluation', location=loc, message=msg } )
end
local function xp_pow( argv )
local b,x = base.unpack( argv or {} )
return b^x
end
local function xp_select( argv )
local obj,keyname,keyval = base.unpack( argv or {} )
if is_non(obj) then return NULLATOM end
if base.type(obj) ~= "table" then evalerror("select() requires table/object arg 1") end
keyname = base.tostring(keyname)
keyval = base.tostring(keyval)
for _,v in base.pairs(obj) do
if base.tostring(v[keyname]) == keyval then
return v
end
end
return NULLATOM
end
local monthNameMap = {}
local function mapLocaleMonth( m )
if m == nil then error("nil month name") end
local ml = string.lower(base.tostring(m))
if ml:match("^%d+$") then
-- All numeric. Simply return numeric form if valid range.
local k = base.tonumber(ml) or 0
if k >=1 and k <= 12 then return k end
end
if monthNameMap[ml] ~= nil then -- cached result?
D("mapLocaleMonth(%1) cached result=%2", ml, monthNameMap[ml])
return monthNameMap[ml]
end
-- Since we can't get locale information directly in a platform-independent way,
-- deduce it from live results...
local d = os.date("*t") -- current time and date
d.day = 1 -- pinned
for k = 1,12 do
d.month = k
local tt = os.time(d)
local s = os.date("#%b#%B#", tt):lower()
if s:find("#"..ml.."#") then
monthNameMap[ml] = k
return k
end
end
return evalerror("Cannot parse month name '" .. m .. "'")
end
local YMD=0
local DMY=1
local MDY=2
local function guessMDDM()
local d = os.date( "%x", os.time( { year=2001, month=8, day=22, hour=0 } ) )
local p = { d:match("(%d+)([/-])(%d+)[/-](%d+)") }
if p[1] == "2001" then return YMD,p[2]
elseif base.tonumber(p[1]) == 22 then return DMY,p[2]
else return MDY,p[2] end
end
-- Somewhat simple time parsing. Handles the most common forms of ISO 8601, plus many less regular forms.
-- If mm/dd vs dd/mm is ambiguous, it tries to discern using current locale's rule.
local function xp_parse_time( t )
if base.type(t) == "number" then return t end -- if already numeric, assume it's already timestamp
if is_non( t ) or base.tostring(t):lower() == "now" then return os.time() end
t = base.tostring(t) -- force string
local now = os.time()
local nd = os.date("*t", now) -- consistent
local tt = { year=nd.year, month=nd.month, day=nd.day, hour=0, ['min']=0, sec=0 }
local offset = 0
-- Try to match a date. Start with two components.
local order = nil
local p = { t:match("^%s*(%d+)([/-])(%d+)(.*)") } -- entirely numeric w/sep
if p[3] == nil then D("match 2") p = { t:match("^%s*(%d+)([/-])(%a+)(.*)") } order=DMY end -- number-word (4-Jul)
if p[3] == nil then D("match 3") p = { t:match("^%s*(%a+)([/-])(%d+)(.*)") } order=MDY end -- word-number (Jul-4)
if p[3] ~= nil then
-- Look ahead for third component behind same separator
D("Found p1=%1, p2=%2, sep=%3, rem=%4", p[1], p[2], p[3], p[4])
local sep = p[2]
t = p[4] or ""
D("Scanning for 3rd part from: '%1'", t)
p[4],p[5] = t:match("^%" .. sep .. "(%d+)(.*)")
if p[4] == nil then
p[4] = tt.year
else
t = p[5] or "" -- advance token
end
-- We now have three components. Figure out their order.
p[5]=t p[6]=p[6]or"" D("p=%1,%2,%3,%4,%5", base.unpack(p))
local first = base.tonumber(p[1]) or 0
if order == nil and first > 31 then
-- First is year (can't be month or day), assume y/m/d
tt.year = first
tt.month = mapLocaleMonth(p[3])
tt.day = p[4]
elseif order == nil and first > 12 then
-- First is day, assume d/m/y
tt.day = first
tt.month = mapLocaleMonth(p[3])
tt.year = p[4]
else
-- Guess using locale formatting
if order == nil then
D("Guessing MDY order")
order = guessMDDM()
end
D("MDY order is %1", order)
if order == 0 then
tt.year = p[1] tt.month = mapLocaleMonth(p[3]) tt.day = p[4]
elseif order == 1 then
tt.day = p[1] tt.month = mapLocaleMonth(p[3]) tt.year = p[4]
else
tt.month = mapLocaleMonth(p[1]) tt.day = p[3] tt.year = p[4]
end
end
tt.year = base.tonumber(tt.year)
if tt.year < 100 then tt.year = tt.year + 2000 end
D("Parsed date year=%1, month=%2, day=%3", tt.year, tt.month, tt.day)
else
-- YYYYMMDD?
D("No match to delimited")
p = { t:match("^%s*(%d%d%d%d)(%d%d)(%d%d)(.*)") }
if p[3] ~= nil then
tt.year = p[1]
tt.month = p[2]
tt.day = p[3]
t = p[4] or ""
else
D("check %%c format")
-- Fri Aug 4 16:18:22 2017
p = { t:match("^%s*%a+%s+(%a+)%s+(%d+)(.*)") } -- with dow
if p[2] == nil then p = { t:match("^%s*(%a+)%s+(%d+)(.*)") } end -- without dow
if p[2] ~= nil then
D("Matches %%c format, 1=%1,2=%2,3=%3", p[1], p[2], p[3])
tt.day = p[2]
tt.month = mapLocaleMonth(p[1])
t = p[3] or ""
-- Following time and year?
p = { t:match("^%s*([%d:]+)%s+(%d%d%d%d)(.*)") }
if p[1] ~= nil then
tt.year = p[2]
t = (p[1] or "") .. " " .. (p[3] or "")
else
-- Maybe just year?
p = { t:match("^%s*(%d%d%d%d)(.*)") }
if p[1] ~= nil then
tt.year = p[1]
t = p[2] or ""
end
end
else
D("No luck with any known date format.")
end
end
D("Parsed date year=%1, month=%2, day=%3", tt.year, tt.month, tt.day)
end
-- Time? Note: does not support decimal fractions except on seconds component, which is ignored (ISO 8601 allows on any, but must be last component)
D("Scanning for time from: '%1'", t)
local hasTZ = false
p = { t:match("^%s*T?(%d%d)(%d%d)(.*)") } -- ISO 8601 (Thhmm) without delimiters
if p[1] == nil then p = { t:match("^%s*T?(%d+):(%d+)(.*)") } end -- with delimiters
if p[1] ~= nil then
-- Hour and minute
tt.hour = p[1]
tt['min'] = p[2]
t = p[3] or ""
-- Seconds?
p = { t:match("^:?(%d+)(.*)") }
if p[1] ~= nil then
tt.sec = p[1]
t = p[2] or ""
end
-- Swallow decimal on last component?
p = { t:match("^(%.%d+)(.*)") }
if p[1] ~= nil then
t = p[2] or ""
end
-- AM or PM?
p = { t:match("^%s*([AaPp])[Mm]?(.*)") }
if p[1] ~= nil then
D("AM/PM is %1", p[1])
if p[1]:lower() == "p" then tt.hour = tt.hour + 12 end
t = p[2] or ""
end
D("Parsed time is %1:%2:%3", tt.hour, tt['min'], tt.sec)
-- Timezone Zulu?
p = { t:match("^([zZ])(.*)") } -- no whitespace, see comment below.
if p[1] ~= nil then
-- Zulu
offset = 0
hasTZ = true
t = p[2] or ""
end
-- Handling for zones? UTC, GMT, minimally... what about others... EDT, JST, ...?
-- Offset +/-HH[mm] (e.g. +02, -0500). Not that the pattern requires the TZ spec
-- to follow the time without spaces between, to distinguish TZ from offsets (below).
p = { t:match("^([+-]%d%d)(.*)") }
if p[1] ~= nil then
hasTZ = true
offset = 60 * base.tonumber(p[1])
t = p[2];
p = { t:match("^:?(%d%d)(.*)") }
if p[1] ~= nil then
if offset < 0 then offset = offset - base.tonumber(p[1])
else offset = offset + base.tonumber(p[1])
end
t = p[2] or ""
end
end
end
-- Is there an offset? Form is (+/-)DDD:HH:MM:SS. If parts are omitted, the offset
-- is parsed from smallest to largest, so +05:00 is +5 minutes, -35 is minus 35 seconds.
local delta = 0
D("Checking for offset from '%1'", t)
p = { t:match("%s*([+-])(%d+)(.*)") }
if p[2] ~= nil then
D("Parsing offset from %1, first part is %2", t, p[2])
local sign = p[1]
delta = base.tonumber(p[2])
if delta == nil then evalerror("Invalid delta spec: " .. t) end
t = p[3] or ""
for k = 1,3 do
D("Parsing offset from %1", t)
p = { t:match("%:(%d+)(.*)") }
if p[1] == nil then break end
if k == 3 then delta = delta * 24 else delta = delta * 60 end
delta = delta + base.tonumber(p[1])
t = p[2] or ""
end
if sign == "-" then delta = -delta end
D("Final delta is %1", delta)
end
-- There should not be anything left at this point
if t:match("([^%s])") then
return evalerror("Unparseable data: " .. t)
end
local tm = os.time( tt )
if hasTZ then
-- If there's a timezone spec, apply it. Otherwise we assume time was in current (system) TZ
-- and leave it unmodified.
local loctime = os.date( "*t", tm ) -- get new local time's DST flag
local epoch = { year=1970, month=1, day=1, hour=0 }
epoch.isdst = loctime.isdst -- 19084 fix, maybe need Reactor approach?
local locale_offset = os.time( epoch )
tm = tm - locale_offset -- back to UTC, because conversion assumes current TZ, so undo that.
tm = tm - ( offset * 60 ) -- apply specified offset
end
tm = tm + delta
return tm -- returns time in UTC
end
-- Date add. First arg is timestamp, then secs, mins, hours, days, months, years
local function xp_date_add( a )
local tm = xp_parse_time( a[1] )
if a[2] ~= nil then tm = tm + (base.tonumber(a[2]) or evalerror("Invalid seconds (argument 2) to dateadd()")) end
if a[3] ~= nil then tm = tm + 60 * (base.tonumber(a[3]) or evalerror("Invalid minutes (argument 3) to dateadd()")) end
if a[4] ~= nil then tm = tm + 3600 * (base.tonumber(a[4]) or evalerror("Invalid hours (argument 4) to dateadd()")) end
if a[5] ~= nil then tm = tm + 86400 * (base.tonumber(a[5]) or evalerror("Invalid days (argument 5) to dateadd()")) end
if a[6] ~= nil or a[7] ~= nil then
D("Applying delta months and years to %1", tm)
local d = os.date("*t", tm)
d.month = d.month + ( base.tonumber( a[6] ) or 0 )
d.year = d.year + ( base.tonumber( a[7] ) or 0 )
D("Normalizing month,year=%1,%2", d.month, d.year)
while d.month < 1 do
d.month = d.month + 12
d.year = d.year - 1
end
while d.month > 12 do
d.month = d.month - 12
d.year = d.year + 1
end
tm = os.time(d)
end
return tm
end
-- Delta between two times. Returns value in seconds.
local function xp_date_diff( d1, d2 )
return xp_parse_time( d1 ) - xp_parse_time( d2 or os.time() )
end
-- Create a timestamp for date/time in the current timezone or UTC by parts
local function xp_mktime( yy, mm, dd, hours, mins, secs )
local pt = os.date("*t")
pt.year = is_non(yy) and pt.year or base.tonumber(yy) or pt.year
pt.month = is_non(mm) and pt.month or base.tonumber(mm) or pt.month
pt.day = is_non(dd) and pt.day or base.tonumber(dd) or pt.day
pt.hour = is_non(hours) and pt.hour or base.tonumber(hours) or pt.hour
pt.min = is_non(mins) and pt.min or base.tonumber(mins) or pt.min
pt.sec = is_non(secs) and pt.sec or base.tonumber(secs) or pt.sec
pt.isdst = nil
pt.yday = nil
pt.wday = nil
return os.time(pt)
end
local function xp_rtrim(s)
if base.type(s) ~= "string" then evalerror("String required") end
return s:gsub("%s+$", "")
end
local function xp_ltrim(s)
if base.type(s) ~= "string" then evalerror("String required") end
return s:gsub("^%s+", "")
end
local function xp_trim( s )
if base.type(s) ~= "string" then evalerror("String required") end
return xp_ltrim( xp_rtrim( s ) )
end
local function xp_keys( argv )
local arr = base.unpack( argv or {} )
if base.type( arr ) ~= "table" then evalerror("Array/table required") end
local r = {}
for k in base.pairs( arr ) do
if k ~= "__context" then
table.insert( r, k )
end
end
return r
end
local function xp_tlen( t )
local n = 0
for _ in base.pairs(t) do n = n + 1 end
return n
end
local function xp_split( argv )
local str = base.tostring( argv[1] or "" )
local sep = argv[2] or ","
local arr = {}
if #str == 0 then return arr, 0 end
local rest = string.gsub( str or "", "([^" .. sep .. "]*)" .. sep, function( m ) table.insert( arr, m ) return "" end )
table.insert( arr, rest )
return arr, #arr
end
local function xp_join( argv )
local a = argv[1] or {}
if base.type(a) ~= "table" then evalerror("Argument 1 to join() is not an array") end
local d = argv[2] or ","
return table.concat( a, d )
end
local function xp_indexof( args )
local arr, item, start = base.unpack( args )
start = start or 1
if is_non( arr ) then return 0 end
if base.type(arr) ~= "table" then evalerror("Array/table required") end
for k,v in base.ipairs( arr ) do
if k >= start then
if isNull( v ) and is_non( item ) then return k end
if v == item then return k end
end
end
return 0
end
local function xp_replace( args )
local str, fpat, rpat = base.unpack( args )
return string.gsub( tostring(str), tostring(fpat), tostring(rpat or "") )
end
local function xp_min( argv )
local res = NULLATOM
for _,v in base.ipairs( argv ) do
local bv = v
if base.type(v) == "table" then
bv = xp_min( v )
elseif base.type(v) == "string" then
bv = tonumber( v )
end
if base.type(bv)=="number" and ( isNull(res) or bv < res ) then
res = bv
end
end
return res
end
local function xp_max( argv )
local res = NULLATOM
for _,v in base.ipairs( argv ) do
local bv = v
if base.type(v) == "table" then
bv = xp_max( v )
elseif base.type(v) == "string" then
bv = tonumber( v )
end
if base.type(bv)=="number" and ( isNull(res) or bv > res ) then
res = bv
end
end
return res
end
-- sum( arg[, ...] ) returns the sum of its arguments. If any argument is
-- an array, the array contents are summed. Nulls do not count to the sum,
-- thus if no valid values are found, the result may be null. Strings are
-- coerced to numbers if possible.
local function xp_sum( args )
local function tsum( v )
local t = NULLATOM
if is_non( v ) then
-- nada
elseif type(v) == "table" then
for _,n in base.ipairs( v ) do
local d = tsum( n )
if not is_non( d ) then t = ( is_non(t) and 0 or t ) + d end
end
elseif type(v) == "string" or type(v) == "number" then
t = tonumber( v ) or NULLATOM
end
return t
end
return tsum( args )
end
-- count( arg[, ...] ) returns the number of non-null elements in the arguments.
-- Handling of arguments is identical to sum(), so average/mean is easily computed
-- via sum( args ) / count( args ).
local function xp_count( args )
local function tcount( v )
if is_non( v ) then
return 0
elseif type( v ) == "table" then
local t = 0
for _,n in base.ipairs( v ) do
t = t + tcount( n )
end
return t
else
return 1
end
end
return tcount( args )
end
local msgNNA1 = "Non-numeric argument 1"
-- ??? All these tostrings() need to be coerce()
local nativeFuncs = {
['abs'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return (n<0) and -n or n end }
, ['sgn'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return (n<0) and -1 or ((n==0) and 0 or 1) end }
, ['floor'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return math.floor(n) end }
, ['ceil'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return math.ceil(n) end }
, ['round'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) local p = base.tonumber( argv[2] ) or 0 return math.floor( n * (10^p) + 0.5 ) / (10^p) end }
, ['cos'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return math.cos(n) end }
, ['sin'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return math.sin(n) end }
, ['tan'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return math.tan(n) end }
, ['asin'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return math.asin(n) end }
, ['acos'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return math.acos(n) end }
, ['atan'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return math.atan(n) end }
, ['rad'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return n * math.pi / 180 end }
, ['deg'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return n * 180 / math.pi end }
, ['log'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return math.log(n) end }
, ['exp'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return math.exp(n) end }
, ['pow'] = { nargs = 2, impl = xp_pow }
, ['sqrt'] = { nargs = 1, impl = function( argv ) local n = base.tonumber( argv[1] ) or evalerror(msgNNA1) return math.sqrt(n) end }
, ['min'] = { nargs = 1, impl = xp_min }
, ['max'] = { nargs = 1, impl = xp_max }
, ['push'] = { nargs = 2, impl = true }
, ['pop'] = { nargs = 1, impl = true }
, ['unshift'] = { nargs = 2, impl = true }
, ['shift' ] = { nargs = 1, impl = true }
, ['sum' ] = { nargs = 1, impl = xp_sum }
, ['count'] = { nargs = 1, impl = xp_count }
, ['randomseed'] = { nargs = 0, impl = function( argv ) local s = argv[1] or os.time() math.randomseed(s) return s end }
, ['random'] = { nargs = 0, impl = function( argv ) return math.random( base.unpack(argv) ) end }
, ['len'] = { nargs = 1, impl = function( argv ) if isNull(argv[1]) then return 0 elseif base.type(argv[1]) == "table" then return xp_tlen(argv[1]) else return string.len(base.tostring(argv[1])) end end }
, ['sub'] = { nargs = 2, impl = function( argv ) local st = base.tostring(argv[1]) local p = argv[2] local l = (argv[3] or -1) return string.sub(st, p, l) end }
, ['find'] = { nargs = 2, impl = function( argv ) local st = base.tostring(argv[1]) local p = base.tostring(argv[2]) local i = argv[3] or 1 return (string.find(st, p, i) or 0) end }
, ['replace'] = { nargs = 3, impl = xp_replace }
, ['upper'] = { nargs = 1, impl = function( argv ) return string.upper(base.tostring(argv[1])) end }
, ['lower'] = { nargs = 1, impl = function( argv ) return string.lower(base.tostring(argv[1])) end }
, ['trim'] = { nargs = 1, impl = function( argv ) return xp_trim(base.tostring(argv[1])) end }
, ['ltrim'] = { nargs = 1, impl = function( argv ) return xp_ltrim(base.tostring(argv[1])) end }
, ['rtrim'] = { nargs = 1, impl = function( argv ) return xp_rtrim(base.tostring(argv[1])) end }
, ['tostring'] = { nargs = 1, impl = function( argv ) if isNull(argv[1]) then return "" else return base.tostring(argv[1]) end end }
, ['tonumber'] = { nargs = 1, impl = function( argv ) if base.type(argv[1]) == "boolean" then if argv[1] then return 1 else return 0 end end return base.tonumber(argv[1], argv[2] or 10) or evalerror('Argument could not be converted to number') end }
, ['format'] = { nargs = 1, impl = function( argv ) return string.format( base.unpack(argv) ) end }
, ['split'] = { nargs = 1, impl = xp_split }
, ['join'] = { nargs = 1, impl = xp_join }
, ['indexof'] = { nargs = 2, impl = xp_indexof }
, ['time'] = { nargs = 0, impl = function( argv ) return xp_parse_time( argv[1] ) end }
, ['timepart'] = { nargs = 0, impl = function( argv ) return os.date( argv[2] and "!*t" or "*t", (not isNull( argv[1] ) ) and argv[1] or nil ) end }
, ['date'] = { nargs = 0, impl = function( argv ) return xp_mktime(base.unpack(argv)) end }
, ['strftime'] = { nargs = 1, impl = function( argv ) return os.date(base.unpack(argv)) end }
, ['dateadd'] = { nargs = 2, impl = function( argv ) return xp_date_add( argv ) end }
, ['datediff'] = { nargs = 1, impl = function( argv ) return xp_date_diff( argv[1], isNull( argv[2] ) and os.time or argv[2] ) end }
, ['choose'] = { nargs = 2, impl = function( argv ) local ix = argv[1] if ix < 1 or ix > (#argv-2) then return argv[2] else return argv[ix+2] end end }
, ['select'] = { nargs = 3, impl = xp_select }
, ['keys'] = { nargs = 1, impl = xp_keys }
, ['iterate'] = { nargs = 2, impl = true }
, ['map'] = { nargs = 2, impl = true }
, ['if'] = { nargs = 2, impl = true }
, ['void'] = { nargs = 0, impl = function( _ ) return NULLATOM end }
, ['list'] = { nargs = 0, impl = function( argv ) local b = deepcopy( argv ) b.__context=nil return b end }
, ['first'] = { nargs = 1, impl = function( argv ) local arr = argv[1] if base.type(arr) ~= "table" or #arr == 0 then return NULLATOM else return arr[1] end end }
, ['last'] = { nargs = 1, impl = function( argv ) local arr = argv[1] if base.type(arr) ~= "table" or #arr == 0 then return NULLATOM else return arr[#arr] end end }
}
-- Try to load bit module; fake it if we don't find it or not right.
local _, bit = pcall( require, "bit" )
if not ( base.type(bit) == "table" and bit.band and bit.bor and bit.bnot and bit.bxor ) then
bit = nil
end
if not bit then
-- Adapted from "BitUtils", Lua-users wiki at http://lua-users.org/wiki/BitUtils; thank you kind stranger(s)...
bit = {}
bit['nand'] = function(x,y,z)
z=z or 2^16
if z<2 then
return 1-x*y
else
return bit.nand((x-x%z)/z,(y-y%z)/z,math.sqrt(z))*z+bit.nand(x%z,y%z,math.sqrt(z))
end
end
bit["bnot"]=function(y,z) return bit.nand(bit.nand(0,0,z),y,z) end
bit["band"]=function(x,y,z) return bit.nand(bit["bnot"](0,z),bit.nand(x,y,z),z) end
bit["bor"]=function(x,y,z) return bit.nand(bit["bnot"](x,z),bit["bnot"](y,z),z) end
bit["bxor"]=function(x,y,z) return bit["band"](bit.nand(x,y,z),bit["bor"](x,y,z),z) end
end
-- Let's get to work
-- Skips white space, returns index of non-space character or nil
local function skip_white( expr, index )
D("skip_white from %1 in %2", index, expr)
local _,e = string.find( expr, "^%s+", index )
if e then index = e + 1 end -- whitespace(s) found, return pos after
return index
end
-- Scan a numeric token. Supports fractional and exponent specs in
-- decimal numbers, and binary, octal, and hexadecimal integers.
local function scan_numeric( expr, index )
D("scan_numeric from %1 in %2", index, expr)
local len = string.len(expr)
local ch, i
local val = 0
local radix = 0
-- Try to guess the radix first
ch = string.sub(expr, index, index)
if ch == '0' and index < len then
-- Look to next character
index = index + 1
ch = string.sub(expr, index, index)
if ch == 'b' or ch == 'B' then
radix = 2
index = index + 1
elseif ch == 'x' or ch == 'X' then
radix = 16
index = index + 1
elseif ch == '.' then
radix = 10 -- going to be a decimal number
else
radix = 8
end
end
if radix <= 0 then radix = 10 end
-- Now parse the whole part of the number
while (index <= len) do
ch = string.sub(expr, index, index)
if ch == '.' then break end
i = string.find("0123456789ABCDEF", string.upper(ch), 1, true)
if i == nil or ( radix==10 and i==15 ) then break end
if i > radix then comperror("Invalid digit for radix "..radix, index) end
val = radix * val + (i-1)
index = index + 1
end
-- Parse fractional part, if any
if ch == '.' and radix==10 then
local ndec = 0
index = index + 1 -- get past decimal point
while (index <= len) do
ch = string.sub(expr, index, index)
i = string.byte(ch) - 48
if i<0 or i>9 then break end
ndec = ndec + 1
val = val + ( i * 10 ^ -ndec )
index = index + 1
end
end
-- Parse exponent, if any
if (ch == 'e' or ch == 'E') and radix == 10 then
local npow = 0
local neg = nil
index = index + 1 -- get base exponent marker
local st = index
while (index <= len) do
ch = string.sub(expr, index, index)
if neg == nil and ch == "-" then neg = true
elseif neg == nil and ch == "+" then neg = false
else
i = string.byte(ch) - 48
if i<0 or i>9 then break end
npow = npow * 10 + i
if neg == nil then neg = false end
end
index = index + 1
end
if index == st then comperror("Missing exponent", index) end
if neg then npow = -npow end
val = val * ( 10 ^ npow )
end
-- Return result
D("scan_numeric returning index=%1, val=%2", index, val)
return index, { __type=CONST, value=val }
end
-- Parse a string. Trivial at the moment and needs escaping of some kind
local function scan_string( expr, index )
D("scan_string from %1 in %2", index, expr)
local len = string.len(expr)
local st = ""
local i
local qchar = string.sub(expr, index, index)
index = index + 1
while index <= len do
i = string.sub(expr, index, index)
if i == '\\' and index < len then
index = index + 1
i = string.sub(expr, index, index)
if charmap[i] then i = charmap[i] end
elseif i == qchar then
-- PHR??? Should we do the double char style of quoting? don''t won''t ??
index = index + 1
return index, { __type=CONST, value=st }
end
st = st .. i
index = index + 1
end
return comperror("Unterminated string", index)
end
-- Parse a function reference. It is treated as a degenerate case of
-- variable reference, i.e. an alphanumeric string followed immediately
-- by an opening parenthesis.
local function scan_fref( expr, index, name )
D("scan_fref from %1 in %2", index, expr)
local len = string.len(expr)
local args = {}
local parenLevel = 1
local ch
local subexp = ""
index = skip_white( expr, index ) + 1
while ( true ) do
if index > len then return comperror("Unexpected end of argument list", index) end -- unexpected end of argument list
ch = string.sub(expr, index, index)
if ch == ')' then
D("scan_fref: Found a closing paren while at level %1", parenLevel)
parenLevel = parenLevel - 1
if parenLevel == 0 then
subexp = xp_trim( subexp )
D("scan_fref: handling end of argument list with subexp=%1", subexp)
if string.len(subexp) > 0 then -- PHR??? Need to test out all whitespace strings from the likes of "func( )"
table.insert(args, _comp( subexp ) ) -- compile the subexp and put it on the list
elseif #args > 0 then
comperror("Invalid subexpression", index)
end
index = index + 1
D("scan_fref returning, function is %1 with %2 args", name, #args, dump(args))
return index, { __type=FREF, args=args, name=name, pos=index }
else
-- It's part of our argument, so just add it to the subexpress string
subexp = subexp .. ch
index = index + 1
end
elseif ch == "'" or ch == '"' then
-- Start of string?
local qq = ch
index, ch = scan_string( expr, index )
subexp = subexp .. qq .. ch.value .. qq
elseif ch == ',' and parenLevel == 1 then -- completed subexpression
subexp = xp_trim( subexp )
D("scan_fref: handling argument=%1", subexp)
if string.len(subexp) > 0 then
local r = _comp(subexp)
if r == nil then return comperror("Subexpression failed to compile", index) end
table.insert( args, r )
D("scan_fref: inserted argument %1 as %2", subexp, r)
else
comperror("Invalid subexpression", index)
end
index = skip_white( expr, index+1 )
subexp = ""
D("scan_fref: continuing argument scan in %1 from %2", expr, index)
else
subexp = subexp .. ch
if ch == '(' then parenLevel = parenLevel + 1 end
index = index + 1
end
end
end
-- Parse an array reference
local function scan_aref( expr, index, name )
D("scan_aref from %1 in %2", index, expr)
local len = string.len(expr)
local ch
local subexp = ""
local depth = 0
index = skip_white( expr, index ) + 1
while ( true ) do
if index > len then return comperror("Unexpected end of array subscript expression", index) end
ch = string.sub(expr, index, index)
if ch == ']' then
if depth == 0 then
D("scan_aref: Found a closing bracket, subexp=%1", subexp)
local args = _comp(subexp)
D("scan_aref returning, array is %1", name)
return index+1, { __type=VREF, name=name, index=args, pos=index }
end
depth = depth - 1
elseif ch == "[" then
depth = depth + 1
end
subexp = subexp .. ch
index = index + 1
end
end
-- Scan a variable reference; could turn into a function reference
local function scan_vref( expr, index )
D("scan_vref from %1 in %2", index, expr)
local len = string.len(expr);
local ch, k
local name = ""
while index <= len do
ch = string.sub(expr, index, index)
if string.find( expr, "^%s*%(", index ) then
if name == "" then comperror("Invalid operator", index) end
return scan_fref(expr, index, name)
elseif string.find( expr, "^%s*%[", index ) then
-- Possible that name is blank. We allow/endorse, for ['identifier'] form of vref (see runtime)
return scan_aref(expr, index, name)
end
k = string.find("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_", string.upper(ch), 1, true)
if k == nil then
break
elseif name == "" and k <= 10 then
return comperror("Invalid identifier", index)
end
name = name .. ch
index = index + 1
end
return index, { __type=VREF, name=name, pos=index }
end
-- Scan nested expression (called when ( seen while scanning for token)
local function scan_expr( expr, index )
D("scan_expr from %1 in %2", index, expr)
local len = string.len(expr)
local st = ""
local parenLevel = 0
index = index + 1
while index <= len do
local ch = string.sub(expr,index,index)
if ch == ')' then
if parenLevel == 0 then
D("scan_expr parsing subexpression=%1", st)
local r = _comp( st )
if r == nil then return comperror("Subexpression failed to parse", index) end
return index+1, r -- pass as single-element sub-expression
end
parenLevel = parenLevel - 1
elseif ch == '(' then
parenLevel = parenLevel + 1
end
-- Add character to subexpression string (note drop-throughs from above conditionals)
st = st .. ch
index = index + 1
end
return index, nil -- Unexpected end of expression/unmatched paren group
end
local function scan_unop( expr, index )
D("scan_unop from %1 in %2", index, expr)
local len = string.len(expr)
if index > len then return index, nil end
local ch = string.sub(expr, index, index)
if ch == '-' or ch == '+' or ch == '!' or ch == '#' then
-- We have a UNOP
index = index + 1
local k, r = scan_token( expr, index )
if r == nil then return k, r end
return k, { __type=UNOP, op=ch, pos=index, operand=r }
end
return index, nil -- Not a UNOP
end
local function scan_binop( expr, index )
D("scan_binop from %1 in %2", index, expr)
local len = string.len(expr)
index = skip_white(expr, index)
if index > len then return index, nil end
local op = ""
local k = 0
local prec
while index <= len do
local ch = string.sub(expr,index,index)
local st = op .. ch
local matched = false
k = k + 1
for _,f in base.ipairs(binops) do
if string.sub(f.op,1,k) == st then
-- matches something
matched = true
prec = f.prec
break;
end
end
if not matched then
-- Didn't match anything. If we matched nothing on the first character, that's an error.
-- Otherwise, op now contains the name of the longest-matching binop in the catalog.
if k == 1 then return comperror("Invalid operator", index) end
break
end
-- Keep going to find longest match
op = st
index = index + 1
end
D("scan_binop succeeds with op=%1", op)
return index, { __type=BINOP, op=op, prec=prec, pos=index }
end
-- Scan our next token (forward-declared)