-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathBuiltinFunctions.cs
2111 lines (1955 loc) · 90.1 KB
/
BuiltinFunctions.cs
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
using Jsonata.Net.Native.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Jsonata.Net.Native.Eval
{
internal static class BuiltinFunctions
{
private static readonly Encoding UTF8_NO_BOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
#region String functions
/**
Signature: $string(arg, prettify)
Casts the arg parameter to a string using the following casting rules
If arg is not specified (i.e. this function is invoked with no arguments), then the context value is used as the value of arg.
If prettify is true, then "prettified" JSON is produced. i.e One line per field and lines will be indented based on the field depth.
*/
public static JToken @string([AllowContextAsValue] JToken arg, [OptionalArgument(false)] bool prettify)
{
switch (arg.Type)
{
case JTokenType.Undefined:
// undefined inputs always return undefined
return arg;
case JTokenType.String:
//Strings are unchanged
return arg;
case JTokenType.Float:
{
double value = (double)arg;
if (Double.IsNaN(value) || Double.IsInfinity(value))
{
throw new JsonataException("D3001", "Attempting to invoke string function on Infinity or NaN");
};
return new JValue(arg.ToFlatString());
};
case JTokenType.Function:
//Functions are converted to an empty string
return new JValue("");
default:
return new JValue(prettify? arg.ToIndentedString() : arg.ToFlatString());
}
}
/**
Signature: $length(str)
Returns the number of characters in the string str.
If str is not specified (i.e. this function is invoked with no arguments), then the context value is used as the value of str.
An error is thrown if str is not a string.
*/
public static int length([AllowContextAsValue][PropagateUndefined] string str)
{
return str.Length;
}
/**
Signature: $substring(str, start[, length])
Returns a string containing the characters in the first parameter str starting at position start (zero-offset).
If str is not specified (i.e. this function is invoked with only the numeric argument(s)), then the context value is used as the value of str. An error is thrown if str is not a string.
If length is specified, then the substring will contain maximum length characters.
If start is negative then it indicates the number of characters from the end of str. See substr for full definition.
*/
public static string substring([AllowContextAsValue][PropagateUndefined] string str, int start, [OptionalArgument(100000000)] int len)
{
//see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
if (start < 0)
{
start = str.Length + start;
if (start < 0)
{
start = 0;
}
};
if (start + len > str.Length)
{
len = str.Length - start;
};
if (len < 0)
{
len = 0;
};
return str.Substring(start, len);
}
/**
Signature: $substringBefore(str, chars)
Returns the substring before the first occurrence of the character sequence chars in str.
If str is not specified (i.e. this function is invoked with only one argument), then the context value is used as the value of str.
If str does not contain chars, then it returns str. An error is thrown if str and chars are not strings.
*/
public static string substringBefore([AllowContextAsValue][PropagateUndefined] string str, string chars)
{
int index = str.IndexOf(chars);
if (index < 0)
{
return str;
}
else
{
return str.Substring(0, index);
}
}
/**
Signature: $substringAfter(str, chars)
Returns the substring after the first occurrence of the character sequence chars in str.
If str is not specified (i.e. this function is invoked with only one argument), then the context value is used as the value of str.
If str does not contain chars, then it returns str. An error is thrown if str and chars are not strings.
*/
public static string substringAfter([AllowContextAsValue][PropagateUndefined] string str, string chars)
{
int index = str.IndexOf(chars);
if (index < 0)
{
return str;
}
else
{
return str.Substring(index + chars.Length);
}
}
/**
Signature: $uppercase(str)
Returns a string with all the characters of str converted to uppercase.
If str is not specified (i.e. this function is invoked with no arguments), then the context value is used as the value of str.
An error is thrown if str is not a string.
*/
public static string uppercase([AllowContextAsValue][PropagateUndefined] string str)
{
return str.ToUpper();
}
/**
Signature: $lowercase(str)
Returns a string with all the characters of str converted to lowercase.
If str is not specified (i.e. this function is invoked with no arguments), then the context value is used as the value of str.
An error is thrown if str is not a string.
*/
public static string lowercase([AllowContextAsValue][PropagateUndefined] string str)
{
return str.ToLower();
}
/**
Signature: $trim(str)
Normalizes and trims all whitespace characters in str by applying the following steps:
All tabs, carriage returns, and line feeds are replaced with spaces.
Contiguous sequences of spaces are reduced to a single space.
Trailing and leading spaces are removed.
If str is not specified (i.e. this function is invoked with no arguments), then the context value is used as the value of str.
An error is thrown if str is not a string.
*/
public static string trim([AllowContextAsValue][PropagateUndefined] string str)
{
str = Regex.Replace(str, @"\s+", " ");
return str.Trim();
}
/**
Signature: $pad(str, width [, char])
Returns a copy of the string str with extra padding, if necessary, so that its total number of characters is at least the absolute value of the width parameter.
If width is a positive number, then the string is padded to the right;
if negative, it is padded to the left.
The optional char argument specifies the padding character(s) to use.
If not specified, it defaults to the space character
*/
public static string pad([AllowContextAsValue][PropagateUndefined] string str, int width, [OptionalArgument(" ")] string chars)
{
if (chars == "")
{
chars = " ";
};
if (width >= 0)
{
bool changed = false;
while (str.Length < width)
{
str += chars;
changed = true;
};
if (changed && str.Length > width)
{
str = str.Substring(0, width);
};
}
else
{
width = -width;
bool changed = false;
while (str.Length < width)
{
str = chars + str;
changed = true;
};
if (changed && str.Length > width)
{
str = str.Substring(str.Length - width);
};
};
return str;
}
/**
Signature: $contains(str, pattern)
Returns true if str is matched by pattern, otherwise it returns false.
If str is not specified (i.e. this function is invoked with one argument), then the context value is used as the value of str.
The pattern parameter can either be a string or a regular expression (regex).
If it is a string, the function returns true if the characters within pattern are contained contiguously within str.
If it is a regex, the function will return true if the regex matches the contents of str.
Examples
$contains("abracadabra", "bra") => true
$contains("abracadabra", /a.*a/) => true
$contains("abracadabra", /ar.*a/) => false
$contains("Hello World", /wo/) => false
$contains("Hello World", /wo/i) => true
*/
public static bool contains([AllowContextAsValue][PropagateUndefined] string str, JToken pattern)
{
switch (pattern.Type)
{
case JTokenType.String:
return str.Contains((string)pattern!);
case JTokenType.Function:
if (pattern is not FunctionTokenRegex regex)
{
throw new JsonataException("T0410", $"Argument 2 of function {nameof(contains)} should be either string or regex. Passed function {pattern.GetType().Name})");
}
else
{
return regex.regex.IsMatch(str);
}
default:
throw new JsonataException("T0410", $"Argument 2 of function {nameof(contains)} should be either string or regex. Passed {pattern.Type} ({pattern.ToFlatString()})");
}
}
/**
Signature: $split(str, separator [, limit])
Splits the str parameter into an array of substrings.
If str is not specified, then the context value is used as the value of str.
It is an error if str is not a string.
The separator parameter can either be a string or a regular expression (regex).
If it is a string, it specifies the characters within str about which it should be split.
If it is the empty string, str will be split into an array of single characters.
If it is a regex, it splits the string around any sequence of characters that match the regex.
The optional limit parameter is a number that specifies the maximum number of substrings to include in the resultant array.
Any additional substrings are discarded.
If limit is not specified, then str is fully split with no limit to the size of the resultant array.
It is an error if limit is not a non-negative number.
*/
public static JArray split([PropagateUndefined] string str, JToken separator, [OptionalArgument(Int32.MaxValue)] int limit)
{
//TODO: support RegExes!!
if (limit < 0)
{
throw new JsonataException("D3020", $"Third argument of {nameof(split)} function must evaluate to a positive number. Passed {limit}");
}
JArray result = new JArray();
switch (separator.Type)
{
case JTokenType.String:
{
string separatorString = (string)separator!;
if (separatorString == "")
{
foreach (char c in str)
{
if (result.Count >= limit)
{
break;
}
result.Add(new JValue(c));
}
}
else
{
foreach (string part in Regex.Split(str, Regex.Escape(separatorString)))
{
if (result.Count >= limit)
{
break;
}
result.Add(new JValue(part));
}
}
}
break;
case JTokenType.Function:
{
if (separator is not FunctionTokenRegex regex)
{
throw new JsonataException("T0410", $"Argument 2 of function {nameof(split)} should be either string or regex. Passed function {separator.GetType().Name})");
};
foreach (string part in regex.regex.Split(str))
{
if (result.Count >= limit)
{
break;
}
result.Add(new JValue(part));
};
}
break;
default:
throw new JsonataException("T0410", $"Argument 2 of function {nameof(split)} should be either string or regex. Passed {separator.Type} ({separator.ToFlatString()})");
}
return result;
}
/**
Signature: $join(array[, separator])
Joins an array of component strings into a single concatenated string with each component string separated by the optional separator parameter.
It is an error if the input array contains an item which isn't a string.
If separator is not specified, then it is assumed to be the empty string, i.e. no separator between the component strings.
It is an error if separator is not a string.
*/
public static string join([PropagateUndefined] JToken array, [OptionalArgument(null)] JToken? separator)
{
string separatorString;
if (separator == null)
{
separatorString = "";
}
else
{
switch (separator.Type)
{
case JTokenType.Undefined:
separatorString = "";
break;
case JTokenType.String:
separatorString = (string)separator!;
break;
default:
throw new JsonataException("T0410", $"Argument 2 of function {nameof(join)} is expected to be string. Specified {separator.Type}");
}
};
List<string> elements = new List<string>();
switch (array.Type)
{
case JTokenType.String:
elements.Add((string)array!);
break;
case JTokenType.Array:
foreach (JToken element in ((JArray)array).ChildrenTokens)
{
if (element.Type != JTokenType.String)
{
throw new JsonataException("T0412", $"Argument 1 of function {nameof(join)} must be an array of strings");
}
else
{
elements.Add((string)element!);
}
}
break;
default:
throw new JsonataException("T0410", $"Argument 1 of function {nameof(join)} is expected to be an Array. Specified {array.Type}");
}
return String.Join(separatorString, elements);
}
/**
Signature: $match(str, pattern [, limit])
Applies the str string to the pattern regular expression and returns an array of objects,
with each object containing information about each occurrence of a match withing str.
The object contains the following fields:
match - the substring that was matched by the regex.
index - the offset (starting at zero) within str of this match.
groups - if the regex contains capturing groups (parentheses), this contains an array of strings representing each captured group.
If str is not specified, then the context value is used as the value of str. It is an error if str is not a string.
*/
public static JArray match([AllowContextAsValue][PropagateUndefined] string str, JToken pattern, [OptionalArgument(Int32.MaxValue)] int limit)
{
if (pattern is not FunctionTokenRegex regex)
{
throw new JsonataException("T0410", $"Argument 2 of function {nameof(match)} should be regex. Passed {pattern.Type} ({pattern.ToFlatString()})");
};
if (limit < 0)
{
throw new JsonataException("D3040", $"Third argument of {nameof(match)} function must evaluate to a positive number");
};
JArray result = new JArray();
foreach (Match match in regex.regex.Matches(str))
{
if (result.Count >= limit)
{
break;
};
result.Add(FunctionTokenRegex.ConvertRegexMatch(match));
}
return result;
}
/**
Signature: $replace(str, pattern, replacement [, limit])
Finds occurrences of pattern within str and replaces them with replacement.
If str is not specified, then the context value is used as the value of str. It is an error if str is not a string.
The pattern parameter can either be a string or a regular expression (regex).
If it is a string, it specifies the substring(s) within str which should be replaced.
If it is a regex, its is used to find .
The replacement parameter can either be a string or a function.
If it is a string, it specifies the sequence of characters that replace the substring(s) that are matched by pattern.
If pattern is a regex, then the replacement string can refer to the characters that were matched by the regex as well as any of the captured groups
using a $ followed by a number N:
If N = 0, then it is replaced by substring matched by the regex as a whole.
If N > 0, then it is replaced by the substring captured by the Nth parenthesised group in the regex.
If N is greater than the number of captured groups, then it is replaced by the empty string.
A literal $ character must be written as $$ in the replacement string
If the replacement parameter is a function, then it is invoked for each match occurrence of the pattern regex.
The replacement function must take a single parameter which will be the object structure of a regex match
as described in the $match function; and must return a string.
The optional limit parameter, is a number that specifies the maximum number of replacements to make before stopping.
The remainder of the input beyond this limit will be copied to the output unchanged.
*/
public static string replace([PropagateUndefined] string str, JToken pattern, JToken replacement, [OptionalArgument(Int32.MaxValue)] int limit)
{
if (limit < 0)
{
throw new JsonataException("D3011", $"Fourth argument of {nameof(replace)} function must evaluate to a positive number");
}
else if (limit == 0)
{
return str;
}
switch (pattern.Type)
{
case JTokenType.String:
{
string patternString = (string)pattern!;
if (patternString == "")
{
throw new JsonataException("D3010", $"Second argument of {nameof(replace)} function cannot be an empty string");
}
else
{
if (replacement.Type != JTokenType.String)
{
throw new JsonataException("D3012", "Attempted to replace a matched string with a non-string value");
};
string replacementString = (string)replacement!;
StringBuilder builder = new StringBuilder();
int replacesCount = 0;
int replaceStartAt = 0;
while (true)
{
if (replacesCount >= limit)
{
break;
};
int pos = str.IndexOf(patternString, startIndex: replaceStartAt);
if (pos < 0)
{
break;
}
else
{
if (pos > replaceStartAt)
{
builder.Append(str.Substring(replaceStartAt, pos - replaceStartAt));
}
builder.Append(replacementString);
++replacesCount;
replaceStartAt = pos + patternString.Length;
};
}
if (replaceStartAt < str.Length)
{
builder.Append(str.Substring(replaceStartAt));
};
return builder.ToString();
}
}
//break;
case JTokenType.Function:
{
if (pattern is not FunctionTokenRegex regex)
{
throw new JsonataException("T0410", $"Argument 2 of function {nameof(replace)} should be either string or regex. Passed function {pattern.GetType().Name})");
};
MatchCollection matches = regex.regex.Matches(str);
if (matches.Count == 0)
{
return str;
};
switch (replacement.Type)
{
case JTokenType.String:
{
string replacementString = (string)replacement!;
StringBuilder builder = new StringBuilder();
int replacesCount = 0;
int replaceStartAt = 0;
foreach (Match match in matches)
{
if (replacesCount >= limit)
{
break;
};
if (match.Index < replaceStartAt)
{
continue; //overlapping matches
}
else if (match.Index > replaceStartAt)
{
builder.Append(str.Substring(replaceStartAt, match.Index - replaceStartAt));
}
//TODO: use ProcessAppendReplacementStringForMatch instead of Result, but actually it's too ugly!
//ProcessAppendReplacementStringForMatch(builder, match, replacementString);
builder.Append(match.Result(replacementString));
++replacesCount;
replaceStartAt = match.Index + match.Length;
}
if (replaceStartAt < str.Length)
{
builder.Append(str.Substring(replaceStartAt));
};
return builder.ToString();
}
//break;
case JTokenType.Function:
{
FunctionToken replacementFunction = (FunctionToken)replacement;
StringBuilder builder = new StringBuilder();
EvaluationEnvironment env = EvaluationEnvironment.CreateEvalEnvironment(EvaluationEnvironment.DefaultEnvironment); //TODO: think of providing proper env. Maybe via a func param?
int replacesCount = 0;
int replaceStartAt = 0;
foreach (Match match in matches)
{
if (replacesCount >= limit)
{
break;
};
if (match.Index < replaceStartAt)
{
continue; //overlapping matches
}
else if (match.Index > replaceStartAt)
{
builder.Append(str.Substring(replaceStartAt, match.Index - replaceStartAt));
};
JObject matchObject = FunctionTokenRegex.ConvertRegexMatch(match);
JToken replacementToken = EvalProcessor.InvokeFunction(replacementFunction, new List<JToken>() { matchObject }, null, env);
if (replacementToken.Type != JTokenType.String)
{
throw new JsonataException("D3012", "Attempted to replace a matched string with a non-string value");
}
builder.Append((string)replacementToken!);
++replacesCount;
replaceStartAt = match.Index + match.Length;
}
if (replaceStartAt < str.Length)
{
builder.Append(str.Substring(replaceStartAt));
};
return builder.ToString();
}
//break;
default:
throw new JsonataException("T0410", $"Argument 3 of function {nameof(replace)} should be either string or function. Passed {replacement.Type} ({replacement.ToFlatString()})");
};
}
//break;
default:
throw new JsonataException("T0410", $"Argument 2 of function {nameof(replace)} should be either string or regex. Passed {pattern.Type} ({pattern.ToFlatString()})");
};
/*
//see jsonata-js functions.js around line 440: "replacer = function (regexMatch)"
void ProcessAppendReplacementStringForMatch(StringBuilder builder, Match match, string replacement)
{
int maxDigits;
if (match.Groups.Count == 1)
{
// no sub-matches; any $ followed by a digit will be replaced by an empty string
maxDigits = 1;
}
else
{
// max number of digits to parse following the $
maxDigits = (int)Math.Floor(Math.Log(match.Groups.Count) * Math.Log10(Math.E)) + 1;
}
// scan forward, copying the replacement text into the substitute string
// and replace any occurrence of $n with the values matched by the regex
int position = 0;
int index = replacement.IndexOf('$', position);
while (index >= 0 && position < replacement.Length)
{
builder.Append(replacement.Substring(position, index - position));
position = index + 1;
char dollarVal = replacement[position];
if (dollarVal == '$')
{
// literal $
builder.Append('$');
++position;
}
else if (dollarVal == '0')
{
builder.Append(match.Value);
++position;
}
else
{
index = Int32.TryParse(replacement.substring(position, position + maxDigits), 10);
if (maxDigits > 1 && index > regexMatch.groups.length)
{
index = parseInt(replacement.substring(position, position + maxDigits - 1), 10);
}
if (!isNaN(index))
{
if (regexMatch.groups.length > 0)
{
var submatch = regexMatch.groups[index - 1];
if (typeof submatch !== 'undefined')
{
substitute += submatch;
}
}
position += index.toString().length;
}
else
{
// not a capture group, treat the $ as literal
substitute += '$';
}
}
index = replacement.indexOf('$', position);
}
substitute += replacement.substring(position);
return substitute;
}
*/
}
/**
Signature: $eval(expr [, context])
Parses and evaluates the string expr which contains literal JSON or a JSONata expression using the current context as the context for evaluation.
Optionally override the context by specifying the second parameter
*/
public static JToken eval([PropagateUndefined] string expr, [AllowContextAsValue] JToken context)
{
JsonataQuery query = new JsonataQuery(expr);
return query.Eval(context); //TODO: think of using bindings from current environment (custom bindings). Also propagating time from parentevaluationEnvironment
}
/**
Signature: $base64encode()
Converts an ASCII string to a base 64 representation.
Each each character in the string is treated as a byte of binary data.
This requires that all characters in the string are in the 0x00 to 0xFF range, which includes all characters in URI encoded strings.
Unicode characters outside of that range are not supported.
*/
public static string base64encode([AllowContextAsValue][PropagateUndefined] string str)
{
return Convert.ToBase64String(UTF8_NO_BOM.GetBytes(str));
}
/**
$base64decode()
Signature: $base64decode()
Converts base 64 encoded bytes to a string, using a UTF-8 Unicode codepage.
*/
public static string base64decode([AllowContextAsValue][PropagateUndefined] string str)
{
return UTF8_NO_BOM.GetString(Convert.FromBase64String(str));
}
/**
$encodeUrlComponent()
Signature: $encodeUrlComponent(str)
Encodes a Uniform Resource Locator(URL) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character.
*/
public static string encodeUrlComponent([AllowContextAsValue][PropagateUndefined] string str)
{
//return WebUtility.UrlEncode(str);
return Uri.EscapeDataString(str);
}
/**
$encodeUrl()
Signature: $encodeUrl(str)
Encodes a Uniform Resource Locator (URL) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character.
*/
public static string encodeUrl([AllowContextAsValue][PropagateUndefined] string str)
{
//see https://stackoverflow.com/a/34189188/376066 and
// https://stackoverflow.com/questions/4396598/whats-the-difference-between-escapeuristring-and-escapedatastring/34189188#comment81544744_34189188
#pragma warning disable SYSLIB0013
return Uri.EscapeUriString(str);
#pragma warning restore
}
/**
$decodeUrlComponent()
Signature: $decodeUrlComponent(str)
Decodes a Uniform Resource Locator (URL) component previously created by encodeUrlComponent.
*/
public static string decodeUrlComponent([AllowContextAsValue][PropagateUndefined] string str)
{
//return WebUtility.UrlEncode(str);
return Uri.UnescapeDataString(str);
}
/**
$decodeUrl()
Signature: $decodeUrl(str)
Decodes a Uniform Resource Locator (URL) previously created by encodeUrl.
*/
public static string decodeUrl([AllowContextAsValue][PropagateUndefined] string str)
{
return Uri.UnescapeDataString(str); //there's no Uri.UnescapeUriString, but actually - what's the difference?
// see https://stackoverflow.com/questions/747641/what-is-the-difference-between-decodeuricomponent-and-decodeuri#comment116291569_747700
}
#endregion
#region Numeric functions
/**
Signature: $number(arg)
Casts the arg parameter to a number using the following casting rules
If arg is not specified (i.e. this function is invoked with no arguments), then the context value is used as the value of arg.
*/
public static JToken number([AllowContextAsValue] JToken arg)
{
switch (arg.Type)
{
case JTokenType.Undefined:
// undefined inputs always return undefined
return arg;
case JTokenType.Integer:
//Numbers are unchanged
return arg;
case JTokenType.Float:
//Numbers are unchanged
return arg;
case JTokenType.String:
//Strings that contain a sequence of characters that represent a legal JSON number are converted to that number
{
string str = (string)arg!;
if (Int64.TryParse(str, out long longValue))
{
return new JValue(longValue);
}
else if (Double.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out double doubleValue))
{
if (!Double.IsNaN(doubleValue) && !Double.IsInfinity(doubleValue))
{
long doubleAsLongValue = (long)doubleValue;
if (doubleAsLongValue == doubleValue)
{
//support for 1e5 cases
return new JValue(doubleAsLongValue);
}
else
{
return new JValue(doubleValue);
}
}
else
{
throw new JsonataException("D3030", "Jsonata does not support NaNs or Infinity values");
}
}
else
{
throw new JsonataException("D3030", $"Failed to parse string to number: '{str}'");
}
};
case JTokenType.Boolean:
//
return new JValue((bool)arg ? 1 : 0);
default:
//All other values cause an error to be thrown.
throw new JsonataException("D3030", $"Unable to cast value to a number. Value type is {arg.Type}");
}
}
/**
Signature: $abs(number)
Returns the absolute value of the number parameter, i.e. if the number is negative, it returns the positive value.
If number is not specified (i.e. this function is invoked with no arguments), then the context value is used as the value of number.
*/
public static double abs([AllowContextAsValue][PropagateUndefined] double number)
{
return Math.Abs(number);
}
/**
Signature: $floor(number)
Returns the value of number rounded down to the nearest integer that is smaller or equal to number.
If number is not specified (i.e. this function is invoked with no arguments), then the context value is used as the value of number.
*/
public static long floor([AllowContextAsValue][PropagateUndefined] double number)
{
return (long)Math.Floor(number);
}
/**
Signature: $ceil(number)
Returns the value of number rounded up to the nearest integer that is greater than or equal to number
If number is not specified (i.e. this function is invoked with no arguments), then the context value is used as the value of number.
*/
public static long ceil([AllowContextAsValue][PropagateUndefined] double number)
{
return (long)Math.Ceiling(number);
}
/**
Signature: $round(number [, precision])
Returns the value of the number parameter rounded to the number of decimal places specified by the optional precision parameter.
The precision parameter (which must be an integer) species the number of decimal places to be present in the rounded number.
If precision is not specified then it defaults to the value 0 and the number is rounded to the nearest integer.
If precision is negative, then its value specifies which column to round to on the left side of the decimal place
This function uses the Round half to even strategy to decide which way to round numbers that fall exactly between two candidates at the specified precision.
This strategy is commonly used in financial calculations and is the default rounding mode in IEEE 754.
*/
public static decimal round([AllowContextAsValue][PropagateUndefined] decimal number, [OptionalArgument(0)] int precision)
{
//This function uses decimal because Math.Round for double in C# does not exactly follow the expectations because of binary arithmetics issues
if (precision >= 0)
{
return Math.Round(number, precision, MidpointRounding.ToEven);
}
else
{
precision = -precision;
int power = (int)Math.Pow(10, precision);
number = Math.Round(number / power, 0, MidpointRounding.ToEven);
number *= power;
return number;
}
}
/**
Signature: $power(base, exponent)
Returns the value of base raised to the power of exponent (base ^ exponent).
If base is not specified (i.e. this function is invoked with one argument), then the context value is used as the value of base.
An error is thrown if the values of base and exponent lead to a value that cannot be represented as a JSON number (e.g. Infinity, complex numbers).
*/
public static double power([AllowContextAsValue][PropagateUndefined] double @base, double exponent)
{
return Math.Pow(@base, exponent);
}
/**
Signature: $sqrt(number)
Returns the square root of the value of the number parameter.
If number is not specified (i.e. this function is invoked with one argument), then the context value is used as the value of number.
An error is thrown if the value of number is negative.
*/
public static double sqrt([AllowContextAsValue][PropagateUndefined] double number)
{
return Math.Sqrt(number);
}
/**
Signature: $random()
Returns a pseudo random number greater than or equal to zero and less than one (0 ≤ n < 1)
*/
public static double random([EvalSupplementArgument] EvaluationSupplement evalEnv)
{
return evalEnv.Random.NextDouble();
}
/**
Signature: $formatNumber(number, picture [, options])
Casts the number to a string and formats it to a decimal representation as specified by the picture string.
The behaviour of this function is consistent with the XPath/XQuery function fn:format-number as defined in the XPath F&O 3.1 specification.
The picture string parameter defines how the number is formatted and has the same syntax as fn:format-number.
The optional third argument options is used to override the default locale specific formatting characters such as the decimal separator.
If supplied, this argument must be an object containing name/value pairs specified in the decimal format section of the XPath F&O 3.1 specification.
*/
public static string formatNumber([AllowContextAsValue][PropagateUndefined] double number, string picture, [OptionalArgument(null)] JObject? options)
{
//TODO: try implementing or using proper XPath fn:format-number
picture = Regex.Replace(picture, @"[1-9]", "0");
picture = Regex.Replace(picture, @",", @"\,");
return number.ToString(picture, CultureInfo.InvariantCulture);
}
/**
Signature: $formatBase(number [, radix])
Casts the number to a string and formats it to an integer represented in the number base specified by the radix argument.
If radix is not specified, then it defaults to base 10. radix can be between 2 and 36, otherwise an error is thrown.
*/
public static string formatBase([AllowContextAsValue][PropagateUndefined] long number, [OptionalArgument(10)] int radix)
{
if (radix < 2 || radix > 36)
{
throw new JsonataException("D3100", $"The radix of the {nameof(formatBase)} function must be between 2 and 36. It was given {radix}");
};
//TODO: implement properly
if (number < 0)
{
return "-" + formatBase(-number, radix);
};
switch (radix)
{
case 2:
case 8:
case 10:
case 16:
return Convert.ToString(number, radix);
default:
throw new NotImplementedException($"No support for radix={radix} in {nameof(formatBase)}() yet");
}
}
/**
Signature: $formatInteger(number, picture)
Casts the number to a string and formats it to an integer representation as specified by the picture string.
The behaviour of this function is consistent with the two-argument version of the XPath/XQuery function fn:format-integer as defined in the XPath F&O 3.1 specification.
The picture string parameter defines how the number is formatted and has the same syntax as fn:format-integer.
*/
public static string formatInteger([AllowContextAsValue][PropagateUndefined] long number, string picture)
{
//TODO: try implementing or using proper XPath fn:format-integer
//picture = Regex.Replace(picture, @"[1-9]", "0");
//picture = Regex.Replace(picture, @",", @"\,");
return number.ToString(picture, CultureInfo.InvariantCulture);
}
/**
Signature: $parseInteger(string, picture)
Parses the contents of the string parameter to an integer (as a JSON number) using the format specified by the picture string.
The picture string parameter has the same format as $formatInteger.
Although the XPath specification does not have an equivalent function for parsing integers, this capability has been added to JSONata.
*/
public static long parseInteger([AllowContextAsValue][PropagateUndefined] string str, [OptionalArgument(null)] string? picture)
{
//TODO: try implementing properly
return Int64.Parse(str);
}
#endregion
#region Numeric aggregation functions
/**
Signature: $sum(array)
Returns the arithmetic sum of an array of numbers.
It is an error if the input array contains an item which isn't a number.
*/
public static JToken sum([PropagateUndefined] JToken arg)
{
switch (arg.Type)
{
case JTokenType.Integer:
case JTokenType.Float:
return arg;
case JTokenType.Array: