-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrt.js
More file actions
4324 lines (3582 loc) · 126 KB
/
rt.js
File metadata and controls
4324 lines (3582 loc) · 126 KB
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
const path=require("node:path");
const fs=require("node:fs");
const cp=require("node:child_process");
const http = require('node:http');
const httpAgent = new http.Agent({ keepAlive: true });
const url = require('node:url');
let https = null;
let httpsAgent = null;
try {
https = require('node:https');
httpsAgent = new https.Agent({ keepAlive: true });
} catch(e) {
}
const yaml=require("yaml");
const prs=require(path.join(__dirname,"prs.js"));
const bs=require(path.join(__dirname,"rtbase.js"));
const showJavascriptStack = false;
// callback for running evaluator
let evalCallback = null;
function setEvalCallback(cb) {
evalCallback = cb;
}
// the file that is being parsed right now. Can't pass that around.
// Should be thread local, or something like this.
let currentSourceInfo = null;
function setCurrentSourceInfo(info) {
let prevValue = currentSourceInfo;
currentSourceInfo = info;
return prevValue;
}
// if set - throw exception if executing a process fails / returns error status
let errorOnExecFail = false;
function setErrorOnExecFail(on) {
errorOnExecFail = on;
}
function _getEnv(frame) {
let [val, _ ] = frame.lookup("ENV");
if (val == null || val.type != bs.TYPE_MAP) {
return {};
}
let envDct = {}
for (let [key, value] of Object.entries(val.val)) {
envDct[key] = bs.value2Str(value);
}
return envDct;
}
function runCmdImpl(cmd, callback, frame) {
let envDct = _getEnv(frame);
let env={shell: true, env: envDct}
let childProc = cp.spawn(cmd, [], env);
let doCallback = function(stdout, stderr, err) {
try {
event = {};
if (stdout != null) {
event['stdout'] = stdout;
}
if (stderr != null) {
event['stderr'] = stderr;
}
if (err != null) {
event['status'] = err;
}
let vargs = [bs.jsValueToRtVal(event)];
bs.evalClosure("", callback, vargs, frame);
} catch(er) {
if (er instanceof bs.RuntimeException) {
er.showStackTrace(true);
} else {
console.trace(er);
}
}
}
childProc.stdout.on('data', (data) => {
doCallback(data.toString(),null,null);
});
childProc.stderr.on('data', (data) => {
doCallback(null,data.toString(),null);
});
childProc.on('close', (code) => {
doCallback(null,null,code);
});
return bs.VALUE_NONE;
}
function _system(cmd, frame) {
let status = 0;
let out = "";
let env = _getEnv(frame);
try {
out = cp.execSync(cmd,{env: env}).toString();
} catch(e) {
console.log("failed to run: " + cmd + " error: " + e.message);
status = 1;//e.status;
out = e.message;
throw e;
}
if (status !=0 && errorOnExecFail) {
throw new bs.RuntimeException("failed to run `" + cmd + "` : " + out);
}
let val = [ new bs.Value(bs.TYPE_STR, out), new bs.Value(bs.TYPE_NUM, status) ];
return new bs.Value(bs.TYPE_LIST, val);
}
function isBascType(ty) {
return ty==bs.TYPE_BOOL || ty == bs.TYPE_NUM || ty == bs.TYPE_STR || ty == bs.TYPE_REGEX || ty == bs.TYPE_NONE;
}
function printImpl(arg) {
let ret = "";
for(let i=0; i<arg.length; ++i) {
if (i != 0) {
ret += " ";
}
let val=arg[i];
if (isBascType(val.type))
ret += bs.value2Str2(val);
else
ret += bs.rtValueToJson(val);
}
return ret;
}
function dimArray(currentDim, dims) {
let n = dims[currentDim];
let val = [];
if (currentDim != dims.length-1) {
for (let i = 0; i < n; ++i) {
val[i] = dimArray( currentDim + 1, dims);
}
} else {
for (let i = 0; i < n; ++i) {
val[i] = new bs.Value(bs.TYPE_NUM, 0);
}
}
return new bs.Value(bs.TYPE_LIST, val);
}
function dimArrayInit(initValue, currentDim, dims) {
let n = dims[currentDim];
let val = [];
if (currentDim != dims.length-1) {
for (let i = 0; i < n; ++i) {
val[i] = dimArrayInit( initValue, currentDim + 1, dims);
}
} else {
for (let i = 0; i < n; ++i) {
val[i] = bs.cloneAll(initValue);
}
}
return new bs.Value(bs.TYPE_LIST, val);
}
function * genValues(val) {
if (val.type == bs.TYPE_LIST) {
for(let i=0; i <val.val.length; ++i) {
yield val.val[i];
}
}
if (val.type == bs.TYPE_MAP) {
for (let keyVal of Object.entries(val.val)) {
let yval = [ new bs.Value(bs.TYPE_STR, keyVal[0]), keyVal[1] ];
yield new bs.Value(bs.TYPE_LIST, yval);
}
}
}
// pythons default float type does not allow Not-a-number - keep it with that...a
// (that makes for less to explain)
function checkResNan(res) {
if (isNaN(res)) {
throw new bs.RuntimeException("results in 'not a number' - that's not allowed here");
}
return res;
}
function makeHttpCallbackInvocationParams(httpReq, httpRes, requestData) {
let req_ = new bs.Value(bs.TYPE_MAP, {
'url_' : new bs.Value(bs.TYPE_STR, httpReq.url),
'url' : new bs.BuiltinFunctionValue(``, 0, function() {
return new bs.Value(bs.TYPE_STR, httpReq.url );
}),
'method' : new bs.BuiltinFunctionValue(``, 0, function() {
return new bs.Value(bs.TYPE_STR, httpReq.method );
}),
'query' : new bs.BuiltinFunctionValue(``, 0, function() {
return bs.jsValueToRtVal(httpReq.query);
}),
'headers' : new bs.BuiltinFunctionValue(``, 0, function() {
return new bs.jsValueToRtVal(httpReq.headers);
}),
'header' : new bs.BuiltinFunctionValue(``, 1, function(arg) {
let name = bs.value2Str(arg, 0);
let val = httpReq.headers[name.toLowerCase()];
return new bs.jsValueToRtVal(val);
}),
'requestData' : new bs.BuiltinFunctionValue(``, 0, function(arg) {
return new bs.Value(bs.TYPE_STR, requestData );
}),
});
let res_ = new bs.Value(bs.TYPE_MAP, {
'setHeader': new bs.BuiltinFunctionValue(``, 2, function(arg) {
httpRes.setHeader(bs.value2Str(arg, 0), bs.rtValueToJsVal(arg[1].val));
return bs.VALUE_NONE;
}),
'send': new bs.BuiltinFunctionValue(``,3, function(arg) {
bs.checkType(arg, 0, bs.TYPE_NUM);
let textResponse = bs.value2Str(arg, 1);
let contentType = "text/plain"
if (arg[2] != null) {
contentType = bs.value2Str(arg, 2);
}
let respHeader = {};
if (httpRes.getHeader("Content-Length") == null) {
respHeader['Content-length'] = textResponse.length.toString();
}
if (httpRes.getHeader("Content-Type") == null) {
respHeader['Content-Type'] = contentType;
}
//console.log("status: " + code.val + " resp-hdr: " + JSON.stringify(respHeader));
httpRes.writeHead(parseInt(arg[0].val), respHeader);
httpRes.write(textResponse);
httpRes.end();
//httpRes.end(textResponse);
//console.log("eof send: " + textResponse);
return bs.VALUE_NONE;
}, [,, null]),
'sendBinary': new bs.BuiltinFunctionValue(``,3, function(arg) {
bs.checkType(arg, 0, bs.TYPE_BINARY);
let binaryResponse = arg[0].val;
let contentType = "application/octet-stream"
if (arg[2] != null) {
contentType = bs.value2Str(arg, 2);
}
let respHeader = {};
if (httpRes.getHeader("Content-Length") == null) {
respHeader['Content-length'] = binaryResponse.length.toString();
}
if (httpRes.getHeader("Content-Type") == null) {
respHeader['Content-Type'] = contentType;
}
//console.log("status: " + code.val + " resp-hdr: " + JSON.stringify(respHeader));
httpRes.writeHead(parseInt(arg[0].val), respHeader);
httpRes.write(binaryResponse);
httpRes.end();
return bs.VALUE_NONE;
}, [,, null])
});
return [ req_, res_ ];
}
function prepareHttpsServerOpts(opts) {
if ('privkeyfile' in opts && 'certfile' in opts) {
let privKeyFile = opts.privkeyfile;
let privKeyFileData = fs.readFileSync(privKeyFile);
let certFile = opts.certfile;
let certFileData = fs.readFileSync(certFile)
delete opts.certfile;
delete opts.privkeyfile
opts.key = privKeyFileData;
opts.cert = certFileData;
return true;
}
return false;
}
function makeHttpServerListener(callback, frame, opts, isHttpClear) {
return function (req, res) {
const chunks = [];
req.on('data', chunk => chunks.push(chunk));
req.on('end', () => {
const data = Buffer.concat(chunks);
// got the request data as well!
// this one is evaluated from another task. runtime exceptions need to be handled here
try {
let vargs = makeHttpCallbackInvocationParams(req,res, data);
bs.evalClosure("", callback, vargs, frame);
} catch(er) {
if (er instanceof bs.RuntimeException) {
er.showStackTrace(true);
} else {
throw er;
}
}
})
};
}
function httpSendImp(arg, frame, responseAsText) {
let options = null
let httpMethod = 'GET';
let httpHeaders = null;
let httpRequestData = null;
let callback = null;
let surl = bs.value2Str(arg, 0);
if (arg[1] != null && arg[1].type != bs.TYPE_NONE) {
bs.checkType(arg, 1, bs.TYPE_MAP);
options = bs.rtValueToJsVal(arg[1]);
if ('method' in options) {
httpMethod = options['method'];
}
if ('headers' in options) {
httpHeaders = options['headers'];
}
if ('data' in options) {
httpRequestData = options['data'];
}
}
if (arg[2] != null) {
bs.checkType(arg, 2, bs.TYPE_CLOSURE);
}
callback = arg[2];
let urlObj = new url.URL(surl);
let requestOptions = {
protocol: urlObj.protocol,
hostname: urlObj.hostname,
port: parseInt(urlObj.port),
path: urlObj.pathname,
method: httpMethod,
};
if (httpHeaders != null) {
requestOptions['headers'] = httpHeaders;
}
//requestOptions['headers'] = { 'Connection': 'keep-alive' };
let callUserFunction = null;
if (responseAsText) {
callUserFunction = function(data, response, error) {
// this one is evaluated from another task. runtime exceptions need to be handled here
let varg = [ new bs.Value(bs.TYPE_NUM, response.statusCode), bs.jsValueToRtVal(response.Headers), new bs.Value(bs.TYPE_STR,data), error ];
try {
bs.evalClosure("", callback, varg, frame);
} catch(er) {
if (er instanceof bs.RuntimeException) {
er.showStackTrace(true);
} else {
throw er;
}
}
}
} else {
callUserFunction = function(data, response, error) {
// this one is evaluated from another task. runtime exceptions need to be handled here
let varg = [ new bs.Value(bs.TYPE_NUM, response.statusCode), bs.jsValueToRtVal(response.Headers), new bs.Value(bs.TYPE_BINARY,data), error ];
try {
bs.evalClosure("", callback, varg, frame);
} catch(er) {
if (er instanceof bs.RuntimeException) {
er.showStackTrace(true);
} else {
throw er;
}
}
}
}
//console.log("request: " + JSON.stringify(requestOptions));
let httpHandler = null;
if (responseAsText) {
httpHandler = function (resp) {
resp.setEncoding('utf8');
let data = "";
resp.on('data', (chunk) => {
data += chunk.toString();
});
resp.on('end', () => {
callUserFunction(data, resp, new bs.Value(bs.TYPE_STR,""));
});
};
} else {
httpHandler = function (resp) {
let data = [];
resp.on('data', (chunk) => {
data.push(chunk);
});
resp.on('end', () => {
let buffer = Buffer.concat(data);
callUserFunction(buffer, resp, new bs.Value(bs.TYPE_STR,""));
});
};
}
let reqObj = null;
if (urlObj.protocol == 'https:') {
if (https==null) {
throw new bs.RuntimeException("https not supported by this nodejs instance");
}
requestOptions['agent'] = httpsAgent;
reqObj = https.request(requestOptions,httpHandler);
} else {
requestOptions['agent'] = httpAgent;
reqObj = http.request(requestOptions,httpHandler);
}
reqObj.on('error', (e) => {
callUserFunction(bs.VALUE_NONE, bs.VALUE_NONE, new bs.Value(bs.TYPE_STR, e.message));
});
if (httpRequestData != null) {
reqObj.write(httpRequestData);
}
reqObj.end();
return bs.VALUE_NONE;
}
function objToDict(obj) {
return Object.keys(obj).reduce((result, key) => {
result[key] = obj[key];
return result;
}, {});
}
function *readDirImp(dirName, recursive) {
let entries = fs.readdirSync(dirName,{withFileTypes:true});
for(let i=0; i<entries.length;++i) {
let entry = entries[i];
let resolvedName = path.resolve(dirName, entry.name);
let stype = '';
if (entry.isFile()) {
stype = "file";
} else if (entry.isDirectory()) {
stype = "directory";
} else if (entry.isSymbolicLink()) {
stype = "symlink";
} else if (entry.isFIFO()) {
stype = "pipe";
} else if (entry.isFIFO()) {
stype = "pipe";
} else if (entry.isBlockDevice()) {
stype = "blockdevice";
} else if (entry.isCharacterDevice()) {
stype = "chardevice";
} else if (entry.isSocket()) { //???
stype = "pipe";
}
let ret = [ new bs.Value(bs.TYPE_STR, resolvedName), new bs.Value(bs.TYPE_STR,stype) ];
yield new bs.Value(bs.TYPE_LIST, ret);
if (recursive && entry.isDirectory() ) {
yield *readDirImp(resolvedName, recursive);
}
}
}
// maps between process id and node childprocess object.
let spawnedProcesses = {};
// the runtime library is defined here
bs.RTLIB={
// functions on binary data
"buffer": new bs.BuiltinFunctionValue(`
# allocate a buffer for binary data, size of buffeer is given in the argument
> a=buffer(10)
{"type":"Buffer","data":[0,0,0,0,0,0,0,0,0,0]}
> a[0]=10
10
> a
{"type":"Buffer","data":[10,0,0,0,0,0,0,0,0,0]}
> a[0]
10
`, 1, function(arg) {
let bufSize = bs.value2Num(arg, 0);
return new bs.Value(bs.TYPE_BINARY, Buffer.alloc(bufSize));
}),
// function on scalars or strings
"find": new bs.BuiltinFunctionValue(`
# search for a string (second argument) in a big string (first argument)
# return indexs of match (zero based index, first match is position zero, if no match -1)
> find("big cat", "big")
0
> find("big cat", "cat")
4
> find("big cat", "bear")
-1
#using regular expressions
> a='123412342 piglet $%#@#$#@%'
"123412342 piglet $%#@#$#@%"
> find(a,/[a-z]+/)
10
# the third parameter is an optional offset to start search from. (zero based index)
> find("a1 !! a1", "a1", 2)
6
> find("a1 !! a1", /[a-z0-9]+/, 2)
6
`, 3, function(arg) {
let hay = bs.value2Str(arg, 0);
let index = 0;
if (arg[2] != null) {
index = parseInt(bs.value2Num(arg, 2));
}
if (arg[1].type == bs.TYPE_REGEX) {
if (index != 0) {
hay = hay.substring(index);
}
let matches = hay.search(arg[1].regex);
if (matches != -1) {
matches += index;
}
return new bs.Value(bs.TYPE_NUM, matches);
}
let needle = bs.value2Str(arg, 1);
let res = hay.indexOf(needle, index)
return new bs.Value(bs.TYPE_NUM, res);
}, [,, null]),
"match": new bs.BuiltinFunctionValue(`
# search for a match of regular expression argument (second) argument) in big text (first argument)
# returns a list - first element is zero based index of match, second is the matching string
>text="a 1232 blablalba 34234 ;aksdf;laksdf 3423"
"a 1232 blablalba 34234 ;aksdf;laksdf 3423"
> match(text,/[0-9]+/)
[2,"1232"]
`, 3, function(arg) {
let hay = bs.value2Str(arg, 0);
bs.checkType(arg, 1, bs.TYPE_REGEX)
let offset = 0;
if (arg[2] != null) {
offset = parseInt(bs.value2Num(arg,2));
hay = hay.substring(offset);
}
let ret = hay.match(arg[1].regex);
let rval;
if (ret == null) {
rval = [ new bs.Value(bs.TYPE_NUM,-1), new bs.Value(bs.TYPE_STR,"") ];
} else {
rval = [ new bs.Value(bs.TYPE_NUM, ret['index'] + offset), new bs.Value(bs.TYPE_STR, ret[0])];
}
return new bs.Value(bs.TYPE_LIST, rval);
}, [,, null]),
"matchAll": new bs.BuiltinFunctionValue(`
> text="a 1232 blablalba 34234 ;aksdf;laksdf 3423"
"a 1232 blablalba 34234 ;aksdf;laksdf 3423"
> matchAll(text,/[0-9]+/)
[[2,"1232"],[17,"34234"],[37,"3423"]]
`, 3, function(arg) {
let hay = bs.value2Str(arg, 0);
let ret = []
bs.checkType(arg, 1, bs.TYPE_REGEX)
let lenConsumed = 0;
let offset = 0;
if (arg[2] != null) {
offset = parseInt(bs.value2Num(arg,2));
hay = hay.substring(offset);
}
while(true) {
let mval = hay.match(arg[1].regex);
if (mval == null) {
break;
}
let index = mval['index'];
let r = [ new bs.Value(bs.TYPE_NUM, lenConsumed + index + offset), new bs.Value(bs.TYPE_STR, mval[0]) ];
ret.push( new bs.Value(bs.TYPE_LIST, r ) );
let toAdd = mval[0].length;
if (toAdd == 0) {
toAdd = 1;
}
hay = hay.substring( index + toAdd );
lenConsumed += index + mval[0].length;
}
return new bs.Value(bs.TYPE_LIST, ret );
}, [,, null]),
"mid": new bs.BuiltinFunctionValue(`
# returns a substring in the text, first argument is the text,
# second argument is the start offset, third argument is ending offset (optional)
> mid("I am me", 2, 4)
"am"
> mid("I am me", 2)
"am me"
> mid("I am me", 2, -1)
"am me"
# it also returns a slice of an input array
> lst=[1,3,2,5,3,2]
[1,3,2,5,3,2]
> mid(lst,2,4)
[2,5]
> mid(lst,3)
[5,3,2]
# it also works with binary buffers
> a=buffer(10)
{"type":"Buffer","data":[0,0,0,0,0,0,0,0,0,0]}
> a[0]=1
1
> a[1]=2
2
> a[2]=3
3
> mid(a,0,3)
{"type":"Buffer","data":[1,2,3]}
`, 3, function(arg) {
let from = parseInt(bs.value2Num(arg[1]), 10);
let to = -1;
if (arg[2] != null) {
to = parseInt(bs.value2Num(arg[2]), 10);
}
if (arg[0].type == bs.TYPE_BINARY) {
let sval = null;
if (to == -1) {
sval = arg[0].val.slice(from);
} else {
sval = arg[0].val.slice(from, to);
}
return new bs.Value(bs.TYPE_BINARY, sval);
} else if (arg[0].type == bs.TYPE_LIST) {
// create a slioce of the array
let sval = null;
if (to == -1) {
to = arg[0].val.length;
sval = arg[0].val.slice(from);
} else {
sval = arg[0].val.slice(from, to);
}
return new bs.Value(bs.TYPE_LIST, sval);
} else {
let sval = bs.value2Str(arg, 0);
if (to == -1) {
sval = sval.substring(from)
} else {
sval = sval.substring(from, to);
}
return new bs.Value(bs.TYPE_STR, sval);
}
}, [,,null ]),
"lc": new bs.BuiltinFunctionValue(`# convert to lower case string
> lc("BIG little")
"big little"`, 1, function(arg) {
let val = bs.value2Str(arg, 0);
return new bs.Value(bs.TYPE_STR, val.toLowerCase());
}),
"uc": new bs.BuiltinFunctionValue(`# convert to upper case string
> uc("BIG little")
"BIG LITTLE"`, 1, function(arg) {
let val = bs.value2Str(arg, 0);
return new bs.Value(bs.TYPE_STR, val.toUpperCase());
}),
"trim": new bs.BuiltinFunctionValue(`# remove leading and trailing whitespace characters
> a= ' honey '
" honey "
> trim(a)
"honey"
> a= '\\t\\n a lot of honey honey \\n '
"\\t\\n a lot of honey honey \\n "
> trim(a)
"a lot of honey honey"`, 1, function(arg) {
let val = bs.value2Str(arg, 0);
return new bs.Value(bs.TYPE_STR, val.trim());
}),
"reverse": new bs.BuiltinFunctionValue(`# return the reverse of the argument (either string or list argument)
> reverse([1,2,3,4])
[4,3,2,1]
> reverse("abcd")
"dcba"`, 1, function(arg) {
if (arg[0].type == bs.TYPE_LIST) {
return new bs.Value(bs.TYPE_LIST, arg[0].val.reverse());
}
let val = bs.value2Str(arg, 0);
return new bs.Value(bs.TYPE_STR, val.split("").reverse().join(""));
}),
"split": new bs.BuiltinFunctionValue(`
# split the first argument string into tokens, the second argument specifies how to split it.
> split("first line\\nsecond line")
["first line","second line"]
> split("a,b,c", ",")
["a","b","c"]
> split("a:b:c", ":")
["a","b","c"]
> split("a:b:c", "")
["a",":","b",":","c"]
# Regular expressions
> a="Roo : Kanga :: Piglet ::: Pooh"
"Roo : Kanga :: Piglet ::: Pooh"
> split(a, /:+/)
["Roo "," Kanga "," Piglet "," Pooh"]
`, 2,function *(arg, frame) {
let hay = bs.value2Str(arg, 0);
let delim = "\n";
if (arg[1] != null) {
if (arg[1].type == bs.TYPE_REGEX) {
delim = arg[1].regex;
} else {
delim = bs.value2Str(arg, 1);
}
}
for(let n of hay.split(delim)) {
yield new bs.Value(bs.TYPE_STR, n);
}
}, [, null], true),
"str": new bs.BuiltinFunctionValue(`> str(123)
"123"
> str("abc")
"abc"`, 1, function(arg) {
let val = bs.value2Str(arg, 0);
return new bs.Value(bs.TYPE_STR, val);
}),
"repeat" : new bs.BuiltinFunctionValue(`> repeat("a",3)
"aaa"
> repeat("ab",3)
"ababab"`, 2, function(arg) {
let val = bs.value2Str(arg, 0);
let rep = bs.value2Num(arg, 1);
return new bs.Value(bs.TYPE_STR, val.repeat(rep));
}),
"replace": new bs.BuiltinFunctionValue(`
# replace replace occurances of second argument string with third argument string in text.
# first arugment - the text
# second argument - string to search for
# third argument - string to replace the match
# fourth argument (optional) - number of matches to substitute (1 is default)
text="a b a c a d"
> "a b a c a d"
> replace(text,'a ', 'x ', -1)
"x b x c x d"
> replace(text,'a ', 'x ', 1)
"x b a c a d"
> replace(text,'a ', 'x ')
"x b a c a d"
> replace(text,'a ', 'x ', 2)
"x b x c a d"
`, 4, function(arg) {
let hay = bs.value2Str(arg, 0);
let needle = bs.value2Str(arg, 1);
let newNeedle = bs.value2Str(arg, 2);
let numTimes = 1;
if (arg[3] != null) {
numTimes = parseInt(bs.value2Num(arg, 3));
}
let retVal = "";
for(let start=0; start < hay.length; numTimes -= 1) {
let findPos = hay.indexOf(needle, start);
if (findPos == -1 || numTimes == 0) {
retVal += hay.substring(start);
break;
}
retVal += hay.substring(start, findPos) + newNeedle;
start = findPos + needle.length;
}
return new bs.Value(bs.TYPE_STR, retVal);
}, [,,, null]),
"replacere": new bs.BuiltinFunctionValue(`
# replace the regular expression (second argument) with replacement expression (third argument)
# in source text (first argument)
> text="Pooh,Bear ## Roo,Kanga ## Christopher,Robin "
"Pooh,Bear ## Roo,Kanga ## Christopher,Robin "
> replacere(text, /([a-zA-Z]+),([a-zA-Z]+)/, "$2,$1")
"Bear,Pooh ## Roo,Kanga ## Christopher,Robin "
> replacere(text, /([a-zA-Z]+),([a-zA-Z]+)/, "$2,$1", 1)
"Bear,Pooh ## Roo,Kanga ## Christopher,Robin "
> replacere(text, /([a-zA-Z]+),([a-zA-Z]+)/, "$2,$1", -1)
"Bear,Pooh ## Kanga,Roo ## Robin,Christopher "
> replacere(text, /([a-zA-Z]+),([a-zA-Z]+)/, "$2,$1", 2)
"Bear,Pooh ## Kanga,Roo ## Christopher,Robin "
`, 4, function(arg) {
let hay = bs.value2Str(arg, 0);
bs.checkType(arg, 1, bs.TYPE_REGEX)
let needle = arg[1].regex;
let newNeedle = bs.value2Str(arg, 2);
let numTimes = 1;
if (arg[3] != null) {
numTimes = parseInt(bs.value2Num(arg, 3));
}
let retVal = "";
for(;;numTimes -= 1) {
let ret = hay.match(needle)
if (ret == null || numTimes == 0) {
retVal += hay;
break;
}
retVal += hay.substring(0, ret['index']);
retVal += ret[0].replace(needle, newNeedle )
// prepare next iteration
let posAfterMatch = ret['index'] + ret[0].length;
hay = hay.substring(posAfterMatch);
}
return new bs.Value(bs.TYPE_STR, retVal);
}, [,,, null]),
// Numeric functions
"int": new bs.BuiltinFunctionValue(`# convert argument string or number to integer value
> int("123")
123
> int("123.5")
123
> int(123.5)
123
> int(123)
123
# beware! numbers are rounded down
> int('3.7')
3
> int(3.7)
3
# hexadecimal number conversion
> int("0xff")
255
> int("ff", 16)
255
# octal number
> int("444", 8)
292
`, 2, function(arg) {
bs.checkTypeList(arg, 0, [bs.TYPE_STR, bs.TYPE_REGEX, bs.TYPE_NUM]);
let sval = bs.value2Str(arg, 0);
let radix = 10;
if (arg[1] != null) {
radix = parseInt(bs.value2Str(arg, 1));
}
if (sval.startsWith("0x")) {
radix = 16;
}
let res = parseInt(sval, radix);
if (res == null) {
throw new bs.RuntimeException("Can't convert " + arg[0].val + " to integer with base " + parseInt(arg[1].val));
}
return new bs.Value(bs.TYPE_NUM, checkResNan(res));
}, [,null]),
"num": new bs.BuiltinFunctionValue(`
# convert argument string to floating point number, if number - returns the same number value
> num('3.7')
3.7
> num('.37e2')
37
`, 1, function(arg) {