-
Notifications
You must be signed in to change notification settings - Fork 20
/
builtin.go
2366 lines (2091 loc) · 70.1 KB
/
builtin.go
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
package functions
import (
"bytes"
"fmt"
"html"
"math"
"net/url"
"regexp"
"sort"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/nyaruka/gocommon/dates"
"github.com/nyaruka/gocommon/random"
"github.com/nyaruka/gocommon/urns"
"github.com/nyaruka/goflow/envs"
"github.com/nyaruka/goflow/excellent/types"
"github.com/nyaruka/goflow/utils"
"github.com/shopspring/decimal"
)
var nanosPerSecond = decimal.RequireFromString("1000000000")
var nonPrintableRegex = regexp.MustCompile(`[\p{Cc}\p{C}]`)
func init() {
builtin := map[string]types.XFunc{
// type conversion
"text": OneArgFunction(Text),
"boolean": OneArgFunction(Boolean),
"number": OneArgFunction(Number),
"date": OneArgFunction(Date),
"datetime": OneArgFunction(DateTime),
"time": OneArgFunction(Time),
"array": Array,
"object": Object,
// text functions
"char": OneNumberFunction(Char),
"code": OneTextFunction(Code),
"split": TextAndOptionalTextFunction(Split, types.XTextEmpty),
"trim": TextAndOptionalTextFunction(Trim, types.XTextEmpty),
"trim_left": TextAndOptionalTextFunction(TrimLeft, types.XTextEmpty),
"trim_right": TextAndOptionalTextFunction(TrimRight, types.XTextEmpty),
"title": OneTextFunction(Title),
"word": InitialTextFunction(1, 2, Word),
"remove_first_word": OneTextFunction(RemoveFirstWord),
"word_count": TextAndOptionalTextFunction(WordCount, types.XTextEmpty),
"word_slice": InitialTextFunction(1, 3, WordSlice),
"field": InitialTextFunction(2, 2, Field),
"clean": OneTextFunction(Clean),
"text_slice": InitialTextFunction(1, 3, TextSlice),
"lower": OneTextFunction(Lower),
"regex_match": InitialTextFunction(1, 2, RegexMatch),
"text_length": OneTextFunction(TextLength),
"text_compare": TwoTextFunction(TextCompare),
"repeat": TextAndIntegerFunction(Repeat),
"replace": MinAndMaxArgsCheck(3, 4, Replace),
"upper": OneTextFunction(Upper),
"percent": OneNumberFunction(Percent),
"url_encode": OneTextFunction(URLEncode),
"html_decode": OneTextFunction(HTMLDecode),
// bool functions
"and": MinArgsCheck(1, And),
"if": ThreeArgFunction(If),
"or": MinArgsCheck(1, Or),
// number functions
"round": OneNumberAndOptionalIntegerFunction(Round, 0),
"round_up": OneNumberAndOptionalIntegerFunction(RoundUp, 0),
"round_down": OneNumberAndOptionalIntegerFunction(RoundDown, 0),
"max": MinArgsCheck(1, Max),
"min": MinArgsCheck(1, Min),
"mean": MinArgsCheck(1, Mean),
"mod": TwoNumberFunction(Mod),
"rand": NoArgFunction(Rand),
"rand_between": TwoNumberFunction(RandBetween),
"abs": OneNumberFunction(Abs),
// datetime functions
"parse_datetime": MinAndMaxArgsCheck(2, 3, ParseDateTime),
"datetime_from_epoch": OneNumberFunction(DateTimeFromEpoch),
"datetime_diff": ThreeArgFunction(DateTimeDiff),
"datetime_add": DateTimeAdd,
"replace_time": TwoArgFunction(ReplaceTime),
"tz": OneDateTimeFunction(TZ),
"tz_offset": OneDateTimeFunction(TZOffset),
"now": NoArgFunction(Now),
"epoch": OneDateTimeFunction(Epoch),
// date functions
"date_from_parts": ThreeIntegerFunction(DateFromParts),
"weekday": OneDateFunction(Weekday),
"week_number": OneDateFunction(WeekNumber),
"today": NoArgFunction(Today),
// time functions
"parse_time": TwoArgFunction(ParseTime),
"time_from_parts": ThreeIntegerFunction(TimeFromParts),
// array functions
"contains": TwoArgFunction(Contains),
"join": TwoArgFunction(Join),
"reverse": OneArrayFunction(Reverse),
"sort": OneArrayFunction(Sort),
"sum": OneArrayFunction(Sum),
"unique": OneArrayFunction(Unique),
"concat": TwoArrayFunction(Concat),
"filter": TwoArgFunction(Filter),
// encoded text functions
"urn_parts": OneTextFunction(URNParts),
"attachment_parts": OneTextFunction(AttachmentParts),
// json functions
"json": OneArgFunction(JSON),
"parse_json": OneTextFunction(ParseJSON),
// formatting functions
"format": OneArgFunction(Format),
"format_date": MinAndMaxArgsCheck(1, 2, FormatDate),
"format_datetime": MinAndMaxArgsCheck(1, 3, FormatDateTime),
"format_time": MinAndMaxArgsCheck(1, 2, FormatTime),
"format_location": OneTextFunction(FormatLocation),
"format_number": MinAndMaxArgsCheck(1, 3, FormatNumber),
"format_urn": OneTextFunction(FormatURN),
// utility functions
"is_error": OneArgFunction(IsError),
"count": OneArgFunction(Count),
"default": TwoArgFunction(Default),
"legacy_add": TwoArgFunction(LegacyAdd),
"read_chars": OneTextFunction(ReadChars),
"extract": TwoArgFunction(Extract),
"extract_object": MinArgsCheck(2, ExtractObject),
"foreach": MinArgsCheck(2, ForEach),
"foreach_value": MinArgsCheck(2, ForEachValue),
"keys": OneObjectFunction(Keys),
}
for name, fn := range builtin {
RegisterXFunction(name, fn)
}
}
//------------------------------------------------------------------------------------------
// Type Conversion Functions
//------------------------------------------------------------------------------------------
// Text tries to convert `value` to text.
//
// An error is returned if the value can't be converted.
//
// @(text(3 = 3)) -> true
// @(json(text(123.45))) -> "123.45"
// @(text(1 / 0)) -> ERROR
//
// @function text(value)
func Text(env envs.Environment, value types.XValue) types.XValue {
str, xerr := types.ToXText(env, value)
if xerr != nil {
return xerr
}
return str
}
// Boolean tries to convert `value` to a boolean.
//
// An error is returned if the value can't be converted.
//
// @(boolean(array(1, 2))) -> true
// @(boolean("FALSE")) -> false
// @(boolean(1 / 0)) -> ERROR
//
// @function boolean(value)
func Boolean(env envs.Environment, value types.XValue) types.XValue {
str, xerr := types.ToXBoolean(value)
if xerr != nil {
return xerr
}
return str
}
// Number tries to convert `value` to a number.
//
// An error is returned if the value can't be converted.
//
// @(number(10)) -> 10
// @(number("123.45000")) -> 123.45
// @(number("what?")) -> ERROR
//
// @function number(value)
func Number(env envs.Environment, value types.XValue) types.XValue {
num, xerr := types.ToXNumber(env, value)
if xerr != nil {
return xerr
}
return num
}
// Date tries to convert `value` to a date.
//
// If it is text then it will be parsed into a date using the default date format.
// An error is returned if the value can't be converted.
//
// @(date("1979-07-18")) -> 1979-07-18
// @(date("1979-07-18T10:30:45.123456Z")) -> 1979-07-18
// @(date("10/05/2010")) -> 2010-05-10
// @(date("NOT DATE")) -> ERROR
//
// @function date(value)
func Date(env envs.Environment, value types.XValue) types.XValue {
d, err := types.ToXDate(env, value)
if err != nil {
return types.NewXError(err)
}
return d
}
// DateTime tries to convert `value` to a datetime.
//
// If it is text then it will be parsed into a datetime using the default date
// and time formats. An error is returned if the value can't be converted.
//
// @(datetime("1979-07-18")) -> 1979-07-18T00:00:00.000000-05:00
// @(datetime("1979-07-18T10:30:45.123456Z")) -> 1979-07-18T10:30:45.123456Z
// @(datetime("10/05/2010")) -> 2010-05-10T00:00:00.000000-05:00
// @(datetime("NOT DATE")) -> ERROR
//
// @function datetime(value)
func DateTime(env envs.Environment, value types.XValue) types.XValue {
dt, err := types.ToXDateTime(env, value)
if err != nil {
return types.NewXError(err)
}
return dt
}
// Time tries to convert `value` to a time.
//
// If it is text then it will be parsed into a time using the default time format.
// An error is returned if the value can't be converted.
//
// @(time("10:30")) -> 10:30:00.000000
// @(time("10:30:45 PM")) -> 22:30:45.000000
// @(time(datetime("1979-07-18T10:30:45.123456Z"))) -> 10:30:45.123456
// @(time("what?")) -> ERROR
//
// @function time(value)
func Time(env envs.Environment, value types.XValue) types.XValue {
t, xerr := types.ToXTime(env, value)
if xerr != nil {
return xerr
}
return t
}
// Array takes multiple `values` and returns them as an array.
//
// @(array("a", "b", 356)[1]) -> b
// @(join(array("a", "b", "c"), "|")) -> a|b|c
// @(count(array())) -> 0
// @(count(array("a", "b"))) -> 2
//
// @function array(values...)
func Array(env envs.Environment, values ...types.XValue) types.XValue {
// check none of our args are errors
for _, arg := range values {
if types.IsXError(arg) {
return arg
}
}
return types.NewXArray(values...)
}
// Object takes property name value pairs and returns them as a new object.
//
// @(object()) -> {}
// @(object("a", 123, "b", "hello")) -> {a: 123, b: hello}
// @(object("a")) -> ERROR
//
// @function object(pairs...)
func Object(env envs.Environment, pairs ...types.XValue) types.XValue {
// check none of our args are errors
for _, arg := range pairs {
if types.IsXError(arg) {
return arg
}
}
if len(pairs)%2 != 0 {
return types.NewXErrorf("requires an even number of arguments")
}
properties := make(map[string]types.XValue, len(pairs)/2)
for i := 0; i < len(pairs); i += 2 {
key := pairs[i]
value := pairs[i+1]
keyAsText, xerr := types.ToXText(env, key)
if xerr != nil {
return xerr
}
properties[keyAsText.Native()] = value
}
return types.NewXObject(properties)
}
//------------------------------------------------------------------------------------------
// Bool Functions
//------------------------------------------------------------------------------------------
// And returns whether all the given `values` are truthy.
//
// @(and(true)) -> true
// @(and(true, false, true)) -> false
//
// @function and(values...)
func And(env envs.Environment, values ...types.XValue) types.XValue {
for _, arg := range values {
asBool, xerr := types.ToXBoolean(arg)
if xerr != nil {
return xerr
}
if !asBool.Native() {
return types.XBooleanFalse
}
}
return types.XBooleanTrue
}
// Or returns whether if any of the given `values` are truthy.
//
// @(or(true)) -> true
// @(or(true, false, true)) -> true
//
// @function or(values...)
func Or(env envs.Environment, values ...types.XValue) types.XValue {
for _, arg := range values {
asBool, xerr := types.ToXBoolean(arg)
if xerr != nil {
return xerr
}
if asBool.Native() {
return types.XBooleanTrue
}
}
return types.XBooleanFalse
}
// If returns `value1` if `test` is truthy or `value2` if not.
//
// If the first argument is an error that error is returned.
//
// @(if(1 = 1, "foo", "bar")) -> foo
// @(if("foo" > "bar", "foo", "bar")) -> ERROR
//
// @function if(test, value1, value2)
func If(env envs.Environment, test types.XValue, value1 types.XValue, value2 types.XValue) types.XValue {
asBool, err := types.ToXBoolean(test)
if err != nil {
return err
}
if asBool.Native() {
return value1
}
return value2
}
//------------------------------------------------------------------------------------------
// Text Functions
//------------------------------------------------------------------------------------------
// Code returns the UNICODE code for the first character of `text`.
//
// It is the inverse of [function:char].
//
// @(code("a")) -> 97
// @(code("abc")) -> 97
// @(code("😀")) -> 128512
// @(code("15")) -> 49
// @(code(15)) -> 49
// @(code("")) -> ERROR
//
// @function code(text)
func Code(env envs.Environment, text types.XText) types.XValue {
if text.Length() == 0 {
return types.NewXErrorf("requires a string of at least one character")
}
r, _ := utf8.DecodeRuneInString(text.Native())
return types.NewXNumberFromInt(int(r))
}
// Split splits `text` into an array of separated words.
//
// Empty values are removed from the returned list. There is an optional final parameter `delimiters` which
// is string of characters used to split the text into words.
//
// @(split("a b c")) -> [a, b, c]
// @(split("a", " ")) -> [a]
// @(split("abc..d", ".")) -> [abc, d]
// @(split("a.b.c.", ".")) -> [a, b, c]
// @(split("a|b,c d", " .|,")) -> [a, b, c, d]
//
// @function split(text, [,delimiters])
func Split(env envs.Environment, text types.XText, delimiters types.XText) types.XValue {
splits := extractWords(text.Native(), delimiters.Native())
nonEmpty := make([]types.XValue, 0)
for _, split := range splits {
nonEmpty = append(nonEmpty, types.NewXText(split))
}
return types.NewXArray(nonEmpty...)
}
// Trim removes whitespace from either end of `text`.
//
// There is an optional final parameter `chars` which is string of characters to be removed instead of whitespace.
//
// @(trim(" hello world ")) -> hello world
// @(trim("+123157568", "+")) -> 123157568
//
// @function trim(text, [,chars])
func Trim(env envs.Environment, text types.XText, chars types.XText) types.XValue {
if chars != types.XTextEmpty {
return types.NewXText(strings.Trim(text.Native(), chars.Native()))
}
return types.NewXText(strings.TrimSpace(text.Native()))
}
// TrimLeft removes whitespace from the start of `text`.
//
// There is an optional final parameter `chars` which is string of characters to be removed instead of whitespace.
//
// @("*" & trim_left(" hello world ") & "*") -> *hello world *
// @(trim_left("+12345+", "+")) -> 12345+
//
// @function trim_left(text, [,chars])
func TrimLeft(env envs.Environment, text types.XText, chars types.XText) types.XValue {
if chars != types.XTextEmpty {
return types.NewXText(strings.TrimLeft(text.Native(), chars.Native()))
}
return types.NewXText(strings.TrimLeftFunc(text.Native(), unicode.IsSpace))
}
// TrimRight removes whitespace from the end of `text`.
//
// There is an optional final parameter `chars` which is string of characters to be removed instead of whitespace.
//
// @("*" & trim_right(" hello world ") & "*") -> * hello world*
// @(trim_right("+12345+", "+")) -> +12345
//
// @function trim_right(text, [,chars])
func TrimRight(env envs.Environment, text types.XText, chars types.XText) types.XValue {
if chars != types.XTextEmpty {
return types.NewXText(strings.TrimRight(text.Native(), chars.Native()))
}
return types.NewXText(strings.TrimRightFunc(text.Native(), unicode.IsSpace))
}
// Char returns the character for the given UNICODE `code`.
//
// It is the inverse of [function:code].
//
// @(char(33)) -> !
// @(char(128512)) -> 😀
// @(char("foo")) -> ERROR
//
// @function char(code)
func Char(env envs.Environment, num types.XNumber) types.XValue {
code, xerr := types.ToInteger(env, num)
if xerr != nil {
return xerr
}
return types.NewXText(string(rune(code)))
}
// Title capitalizes each word in `text`.
//
// @(title("foo")) -> Foo
// @(title("ryan lewis")) -> Ryan Lewis
// @(title("RYAN LEWIS")) -> Ryan Lewis
// @(title(123)) -> 123
//
// @function title(text)
func Title(env envs.Environment, text types.XText) types.XValue {
return types.NewXText(strings.Title(strings.ToLower(text.Native())))
}
// Word returns the word at `index` in `text`.
//
// Indexes start at zero. There is an optional final parameter `delimiters` which
// is string of characters used to split the text into words.
//
// @(word("bee cat dog", 0)) -> bee
// @(word("bee.cat,dog", 0)) -> bee
// @(word("bee.cat,dog", 1)) -> cat
// @(word("bee.cat,dog", 2)) -> dog
// @(word("bee.cat,dog", -1)) -> dog
// @(word("bee.cat,dog", -2)) -> cat
// @(word("bee.*cat,dog", 1, ".*=|")) -> cat,dog
// @(word("O'Grady O'Flaggerty", 1, " ")) -> O'Flaggerty
//
// @function word(text, index [,delimiters])
func Word(env envs.Environment, text types.XText, args ...types.XValue) types.XValue {
index, xerr := types.ToInteger(env, args[0])
if xerr != nil {
return xerr
}
delimiters := types.XTextEmpty
if len(args) == 2 && args[1] != nil {
delimiters, xerr = types.ToXText(env, args[1])
if xerr != nil {
return xerr
}
}
words := extractWords(text.Native(), delimiters.Native())
offset := index
if offset < 0 {
offset += len(words)
}
if !(offset >= 0 && offset < len(words)) {
return types.NewXErrorf("index %d is out of range for the number of words %d", index, len(words))
}
return types.NewXText(words[offset])
}
// RemoveFirstWord removes the first word of `text`.
//
// @(remove_first_word("foo bar")) -> bar
// @(remove_first_word("Hi there. I'm a flow!")) -> there. I'm a flow!
//
// @function remove_first_word(text)
func RemoveFirstWord(env envs.Environment, text types.XText) types.XValue {
s := text.Native()
words := extractWords(s, "")
if len(words) < 2 {
return types.XTextEmpty
}
// find first word and remove
w1Start := strings.Index(s, words[0])
s = s[w1Start+len(words[0]):]
// find where second word starts and discard everything up to that
w2Start := strings.Index(s, words[1])
s = s[w2Start:]
return types.NewXText(s)
}
// WordSlice extracts a sub-sequence of words from `text`.
//
// The returned words are those from `start` up to but not-including `end`. Indexes start at zero and a negative
// end value means that all words after the start should be returned. There is an optional final parameter `delimiters`
// which is string of characters used to split the text into words.
//
// @(word_slice("bee cat dog", 0, 1)) -> bee
// @(word_slice("bee cat dog", 0, 2)) -> bee cat
// @(word_slice("bee cat dog", 1, -1)) -> cat dog
// @(word_slice("bee cat dog", 1)) -> cat dog
// @(word_slice("bee cat dog", 2, 3)) -> dog
// @(word_slice("bee cat dog", 3, 10)) ->
// @(word_slice("bee.*cat,dog", 1, -1, ".*=|,")) -> cat dog
// @(word_slice("O'Grady O'Flaggerty", 1, 2, " ")) -> O'Flaggerty
//
// @function word_slice(text, start, end [,delimiters])
func WordSlice(env envs.Environment, text types.XText, args ...types.XValue) types.XValue {
start, xerr := types.ToInteger(env, args[0])
if xerr != nil {
return xerr
}
if start < 0 {
return types.NewXErrorf("must start with a positive index")
}
end := -1
if len(args) >= 2 {
if end, xerr = types.ToInteger(env, args[1]); xerr != nil {
return xerr
}
}
if end > 0 && end <= start {
return types.NewXErrorf("must have a end which is greater than the start")
}
delimiters := types.XTextEmpty
if len(args) >= 3 && args[2] != nil {
delimiters, xerr = types.ToXText(env, args[2])
if xerr != nil {
return xerr
}
}
words := extractWords(text.Native(), delimiters.Native())
if start >= len(words) {
return types.XTextEmpty
}
if end >= len(words) {
end = len(words)
}
if end > 0 {
return types.NewXText(strings.Join(words[start:end], " "))
}
return types.NewXText(strings.Join(words[start:], " "))
}
// WordCount returns the number of words in `text`.
//
// There is an optional final parameter `delimiters` which is string of characters used
// to split the text into words.
//
// @(word_count("foo bar")) -> 2
// @(word_count(10)) -> 1
// @(word_count("")) -> 0
// @(word_count("😀😃😄😁")) -> 4
// @(word_count("bee.*cat,dog", ".*=|")) -> 2
// @(word_count("O'Grady O'Flaggerty", " ")) -> 2
//
// @function word_count(text [,delimiters])
func WordCount(env envs.Environment, text types.XText, delimiters types.XText) types.XValue {
words := extractWords(text.Native(), delimiters.Native())
return types.NewXNumberFromInt(len(words))
}
// Field splits `text` using the given `delimiter` and returns the field at `index`.
//
// The index starts at zero. When splitting with a space, the delimiter is considered to be all whitespace.
//
// @(field("a,b,c", 1, ",")) -> b
// @(field("a,,b,c", 1, ",")) ->
// @(field("a b c", 1, " ")) -> b
// @(field("a b c d", 1, " ")) ->
// @(field("a\t\tb\tc\td", 1, " ")) ->
// @(field("a,b,c", "foo", ",")) -> ERROR
//
// @function field(text, index, delimiter)
func Field(env envs.Environment, text types.XText, args ...types.XValue) types.XValue {
field, xerr := types.ToInteger(env, args[0])
if xerr != nil {
return xerr
}
if field < 0 {
return types.NewXErrorf("cannot use a negative index")
}
sep, xerr := types.ToXText(env, args[1])
if xerr != nil {
return xerr
}
fields := strings.Split(text.Native(), sep.Native())
// when using a space as a delimiter, we consider it splitting on whitespace, so remove empty values
if sep.Native() == " " {
var newFields []string
for _, f := range fields {
if f != "" {
newFields = append(newFields, f)
}
}
fields = newFields
}
if field >= len(fields) {
return types.XTextEmpty
}
return types.NewXText(strings.TrimSpace(fields[field]))
}
// Clean removes any non-printable characters from `text`.
//
// @(clean("😃 Hello \nwo\tr\rld")) -> 😃 Hello world
// @(clean(123)) -> 123
//
// @function clean(text)
func Clean(env envs.Environment, text types.XText) types.XValue {
return types.NewXText(nonPrintableRegex.ReplaceAllString(text.Native(), ""))
}
// TextSlice returns the portion of `text` between `start` (inclusive) and `end` (exclusive).
//
// If `end` is not specified then the entire rest of `text` will be included. Negative values
// for `start` or `end` start at the end of `text`.
//
// @(text_slice("hello", 2)) -> llo
// @(text_slice("hello", 1, 3)) -> el
// @(text_slice("hello😁", -3, -1)) -> lo
// @(text_slice("hello", 7)) ->
//
// @function text_slice(text, start [, end])
func TextSlice(env envs.Environment, text types.XText, args ...types.XValue) types.XValue {
length := utf8.RuneCountInString(text.Native())
start, xerr := types.ToInteger(env, args[0])
if xerr != nil {
return xerr
}
if start < 0 {
start = length + start
}
end := length
if len(args) == 2 {
if end, xerr = types.ToInteger(env, args[1]); xerr != nil {
return xerr
}
}
if end < 0 {
end = length + end
}
var output bytes.Buffer
i := 0
for _, r := range text.Native() {
if i >= start && i < end {
output.WriteRune(r)
}
i++
}
return types.NewXText(output.String())
}
// Lower converts `text` to lowercase.
//
// @(lower("HellO")) -> hello
// @(lower("hello")) -> hello
// @(lower("123")) -> 123
// @(lower("😀")) -> 😀
//
// @function lower(text)
func Lower(env envs.Environment, text types.XText) types.XValue {
return types.NewXText(strings.ToLower(text.Native()))
}
// RegexMatch returns the first match of the regular expression `pattern` in `text`.
//
// An optional third parameter `group` determines which matching group will be returned.
//
// @(regex_match("sda34dfddg67", "\d+")) -> 34
// @(regex_match("Bob Smith", "(\w+) (\w+)", 1)) -> Bob
// @(regex_match("Bob Smith", "(\w+) (\w+)", 2)) -> Smith
// @(regex_match("Bob Smith", "(\w+) (\w+)", 5)) -> ERROR
// @(regex_match("abc", "[\.")) -> ERROR
//
// @function regex_match(text, pattern [,group])
func RegexMatch(env envs.Environment, text types.XText, args ...types.XValue) types.XValue {
pattern, xerr := types.ToXText(env, args[0])
if xerr != nil {
return xerr
}
groupNum := 0
if len(args) == 2 {
groupNum, xerr = types.ToInteger(env, args[1])
if xerr != nil {
return xerr
}
}
exp, err := regexp.Compile(`(?mi)` + pattern.Native())
if err != nil {
return types.NewXErrorf("invalid regular expression")
}
groups := exp.FindStringSubmatch(text.Native())
if groupNum < 0 || groupNum >= len(groups) {
return types.NewXErrorf("invalid regular expression group")
}
return types.NewXText(groups[groupNum])
}
// TextLength returns the length (number of characters) of `value` when converted to text.
//
// @(text_length("abc")) -> 3
// @(text_length(array(2, 3))) -> 6
//
// @function text_length(value)
func TextLength(env envs.Environment, value types.XText) types.XValue {
return types.NewXNumberFromInt(value.Length())
}
// TextCompare returns the dictionary order of `text1` and `text2`.
//
// The return value will be -1 if `text1` comes before `text2`, 0 if they are equal
// and 1 if `text1` comes after `text2`.
//
// @(text_compare("abc", "abc")) -> 0
// @(text_compare("abc", "def")) -> -1
// @(text_compare("zzz", "aaa")) -> 1
//
// @function text_compare(text1, text2)
func TextCompare(env envs.Environment, text1 types.XText, text2 types.XText) types.XValue {
return types.NewXNumberFromInt(text1.Compare(text2))
}
// Repeat returns `text` repeated `count` number of times.
//
// @(repeat("*", 8)) -> ********
// @(repeat("*", "foo")) -> ERROR
//
// @function repeat(text, count)
func Repeat(env envs.Environment, text types.XText, count int) types.XValue {
if count < 0 {
return types.NewXErrorf("must be called with a positive integer, got %d", count)
}
var output bytes.Buffer
for j := 0; j < count; j++ {
output.WriteString(text.Native())
}
return types.NewXText(output.String())
}
// Replace replaces up to `count` occurrences of `needle` with `replacement` in `text`.
//
// If `count` is omitted or is less than 0 then all occurrences are replaced.
//
// @(replace("foo bar foo", "foo", "zap")) -> zap bar zap
// @(replace("foo bar foo", "foo", "zap", 1)) -> zap bar foo
// @(replace("foo bar", "baz", "zap")) -> foo bar
//
// @function replace(text, needle, replacement [, count])
func Replace(env envs.Environment, args ...types.XValue) types.XValue {
text, xerr := types.ToXText(env, args[0])
if xerr != nil {
return xerr
}
needle, xerr := types.ToXText(env, args[1])
if xerr != nil {
return xerr
}
replacement, xerr := types.ToXText(env, args[2])
if xerr != nil {
return xerr
}
count := -1
if len(args) == 4 {
count, xerr = types.ToInteger(env, args[3])
if xerr != nil {
return xerr
}
}
return types.NewXText(strings.Replace(text.Native(), needle.Native(), replacement.Native(), count))
}
// Upper converts `text` to uppercase.
//
// @(upper("Asdf")) -> ASDF
// @(upper(123)) -> 123
//
// @function upper(text)
func Upper(env envs.Environment, text types.XText) types.XValue {
return types.NewXText(strings.ToUpper(text.Native()))
}
// Percent formats `number` as a percentage.
//
// @(percent(0.54234)) -> 54%
// @(percent(1.2)) -> 120%
// @(percent("foo")) -> ERROR
//
// @function percent(number)
func Percent(env envs.Environment, num types.XNumber) types.XValue {
// multiply by 100 and floor
percent := num.Native().Mul(decimal.NewFromFloat(100)).Round(0)
// add on a %
return types.NewXText(fmt.Sprintf("%d%%", percent.IntPart()))
}
// URLEncode encodes `text` for use as a URL parameter.
//
// @(url_encode("two & words")) -> two%20%26%20words
// @(url_encode(10)) -> 10
//
// @function url_encode(text)
func URLEncode(env envs.Environment, text types.XText) types.XValue {
// escapes spaces as %20 matching urllib.quote(s, safe="") in Python
encoded := strings.Replace(url.QueryEscape(text.Native()), "+", "%20", -1)
return types.NewXText(encoded)
}
// HTMLDecode HTML decodes `text`
//
// @(html_decode("Red & Blue")) -> Red & Blue
// @(html_decode("5 + 10")) -> 5 + 10
//
// @function html_decode(text)
func HTMLDecode(env envs.Environment, text types.XText) types.XValue {
decoded := html.UnescapeString(text.Native())
// the common nbsp; turns into a unicode non breaking space, convert to a normal space
decoded = strings.ReplaceAll(decoded, "\U000000A0", " ")
return types.NewXText(decoded)
}
//------------------------------------------------------------------------------------------
// Number Functions
//------------------------------------------------------------------------------------------
// Abs returns the absolute value of `number`.
//
// @(abs(-10)) -> 10
// @(abs(10.5)) -> 10.5
// @(abs("foo")) -> ERROR
//
// @function abs(number)
func Abs(env envs.Environment, num types.XNumber) types.XValue {
return types.NewXNumber(num.Native().Abs())
}
// Round rounds `number` to the nearest value.
//
// You can optionally pass in the number of decimal places to round to as `places`. If `places` < 0,
// it will round the integer part to the nearest 10^(-places).
//
// @(round(12)) -> 12
// @(round(12.141)) -> 12
// @(round(12.6)) -> 13
// @(round(12.141, 2)) -> 12.14
// @(round(12.146, 2)) -> 12.15
// @(round(12.146, -1)) -> 10
// @(round("notnum", 2)) -> ERROR
//
// @function round(number [,places])
func Round(env envs.Environment, num types.XNumber, places int) types.XValue {
return types.NewXNumber(num.Native().Round(int32(places)))
}
// RoundUp rounds `number` up to the nearest integer value.
//
// You can optionally pass in the number of decimal places to round to as `places`.
//
// @(round_up(12)) -> 12
// @(round_up(12.141)) -> 13
// @(round_up(12.6)) -> 13
// @(round_up(12.141, 2)) -> 12.15
// @(round_up(12.146, 2)) -> 12.15
// @(round_up("foo")) -> ERROR
//
// @function round_up(number [,places])
func RoundUp(env envs.Environment, num types.XNumber, places int) types.XValue {
dec := num.Native()
if dec.Round(int32(places)).Equal(dec) {
return num
}
halfPrecision := decimal.New(5, -int32(places)-1)
roundedDec := dec.Add(halfPrecision).Round(int32(places))
return types.NewXNumber(roundedDec)
}
// RoundDown rounds `number` down to the nearest integer value.
//
// You can optionally pass in the number of decimal places to round to as `places`.
//
// @(round_down(12)) -> 12
// @(round_down(12.141)) -> 12
// @(round_down(12.6)) -> 12
// @(round_down(12.141, 2)) -> 12.14
// @(round_down(12.146, 2)) -> 12.14
// @(round_down("foo")) -> ERROR
//
// @function round_down(number [,places])
func RoundDown(env envs.Environment, num types.XNumber, places int) types.XValue {
dec := num.Native()
if dec.Round(int32(places)).Equal(dec) {
return num