-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathjsonata.py
More file actions
2021 lines (1778 loc) · 82.7 KB
/
Copy pathjsonata.py
File metadata and controls
2021 lines (1778 loc) · 82.7 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
#
# Copyright Robert Yokota
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Derived from the following code:
#
# Project name: jsonata-java
# Copyright Dashjoin GmbH. https://dashjoin.com
# Licensed under the Apache License, Version 2.0 (the "License")
#
# Project name: JSONata
# © Copyright IBM Corp. 2016, 2017 All Rights Reserved
# This project is licensed under the MIT License, see LICENSE
#
import copy
import inspect
import math
import re
import sys
import threading
from dataclasses import dataclass
from typing import Any, Callable, Mapping, MutableSequence, Optional, Sequence, Type, MutableMapping
from jsonata import functions, jexception, parser, signature as sig, timebox, utils
#
# @module JSONata
# @description JSON query and transformation language
#
class Jsonata:
class Frame:
bindings: MutableMapping[str, Any]
parent: 'Jsonata.Optional[Frame]'
is_parallel_call: bool
def __init__(self, parent):
self.bindings = {}
self.parent = parent
self.is_parallel_call = False
def bind(self, name: str, val: Optional[Any]) -> None:
self.bindings[name] = val
if getattr(val, "signature", None) is not None:
val.signature.set_function_name(name)
def lookup(self, name: str) -> Optional[Any]:
# Important: if we have a null value,
# return it
val = self.bindings.get(name, utils.Utils.NONE)
if val is not utils.Utils.NONE:
return val
if self.parent is not None:
return self.parent.lookup(name)
return None
#
# Sets the runtime bounds for this environment
#
# @param timeout Timeout in millis
# @param maxRecursionDepth Max recursion depth
#
def set_runtime_bounds(self, timeout: int, max_recursion_depth: int) -> None:
timebox.Timebox(self, timeout, max_recursion_depth)
def set_evaluate_entry_callback(self, cb: Callable) -> None:
self.bind("__evaluate_entry", cb)
def set_evaluate_exit_callback(self, cb: Callable) -> None:
self.bind("__evaluate_exit", cb)
static_frame = None # = createFrame(null);
#
# JFunction callable Lambda interface
#
class JFunctionCallable:
def call(self, input: Optional[Any], args: Optional[Sequence]) -> Optional[Any]:
pass
class JFunctionSignatureValidation:
def validate(self, args: Optional[Any], context: Optional[Any]) -> Optional[Any]:
pass
class JLambda(JFunctionCallable, JFunctionSignatureValidation):
function: Callable
def __init__(self, function):
self.function = function
def call(self, input: Optional[Any], args: Optional[Sequence]) -> Optional[Any]:
if isinstance(args, list):
return self.function(*args)
else:
return self.function()
def validate(self, args: Optional[Any], context: Optional[Any]) -> Optional[Any]:
return args
#
# JFunction definition class
#
class JFunction(JFunctionCallable, JFunctionSignatureValidation):
function: 'Jsonata.JFunctionCallable'
signature: Optional[sig.Signature]
function_name: Optional[str]
def __init__(self, function, signature):
self.function = function
if signature is not None:
# use classname as default, gets overwritten once the function is registered
self.signature = sig.Signature(signature, str(type(function)))
else:
self.signature = None
self.function_name = None
def call(self, input: Optional[Any], args: Optional[Sequence]) -> Optional[Any]:
return self.function.call(input, args)
def validate(self, args: Optional[Any], context: Optional[Any]) -> Optional[Any]:
if self.signature is not None:
return self.signature.validate(args, context)
else:
return args
def get_number_of_args(self) -> int:
return 0
class JNativeFunction(JFunction):
function_name: str
signature: Optional[sig.Signature]
clz: Type[functions.Functions]
method: Optional[Any]
nargs: int
def __init__(self, function_name, signature, clz, impl_method_name):
super().__init__(None, None)
self.function_name = function_name
self.signature = sig.Signature(signature, function_name)
if impl_method_name is None:
impl_method_name = self.function_name
self.method = functions.Functions.get_function(clz, impl_method_name)
self.nargs = len(inspect.signature(self.method).parameters) if self.method is not None else 0
if self.method is None:
print("Function not implemented: " + function_name + " impl=" + impl_method_name)
def call(self, input: Optional[Any], args: Optional[Sequence]) -> Optional[Any]:
return functions.Functions._call(self.method, self.nargs, args)
def get_number_of_args(self) -> int:
return self.nargs
class Transformer(JFunctionCallable):
_jsonata: 'Jsonata'
_expr: Optional[parser.Parser.Symbol]
_environment: 'Jsonata.Optional[Frame]'
def __init__(self, jsonata, expr, environment):
self._jsonata = jsonata
self._expr = expr
self._environment = environment
def call(self, input: Optional[Any], args: Optional[Sequence]) -> Optional[Any]:
# /* async */ Object (obj) { // signature <(oa):o>
obj = args[0]
# undefined inputs always return undefined
if obj is None:
return None
# this Object returns a copy of obj with changes specified by the pattern/operation
result = functions.Functions.function_clone(obj)
matches = self._jsonata.eval(self._expr.pattern, result, self._environment)
if matches is not None:
if not (isinstance(matches, list)):
matches = [matches]
for match_ in matches:
# evaluate the update value for each match
update = self._jsonata.eval(self._expr.update, match_, self._environment)
# update must be an object
# var updateType = typeof update
# if(updateType != null)
if update is not None:
if not (isinstance(update, dict)):
# throw type error
raise jexception.JException("T2011", self._expr.update.position, update)
# merge the update
for k in update.keys():
match_[k] = update[k]
# delete, if specified, must be an array of strings (or single string)
if self._expr.delete is not None:
deletions = self._jsonata.eval(self._expr.delete, match_, self._environment)
if deletions is not None:
val = deletions
if not (isinstance(deletions, list)):
deletions = [deletions]
if not utils.Utils.is_array_of_strings(deletions):
# throw type error
raise jexception.JException("T2012", self._expr.delete.position, val)
for item in deletions:
if isinstance(match_, dict):
match_.pop(item, None)
# delete match[deletions[jj]]
return result
#
# Evaluate expression against input data
# @param {Object} expr - JSONata expression
# @param {Object} input - Input data to evaluate against
# @param {Object} environment - Environment
# @returns {*} Evaluated input data
#
def eval(self, expr: Optional[parser.Parser.Symbol], input: Optional[Any], environment: Optional[Frame]) -> Optional[Any]:
# Thread safety:
# Make sure each evaluate is executed on an instance per thread
return self.get_per_thread_instance()._eval(expr, input, environment)
def _eval(self, expr: Optional[parser.Parser.Symbol], input: Optional[Any], environment: Optional[Frame]) -> Optional[Any]:
result = None
# Store the current input
# This is required by Functions.functionEval for current $eval() input context
self.input = input
if self.parser.dbg:
print("eval expr=" + str(expr) + " type=" + expr.type) # +" input="+input);
entry_callback = environment.lookup("__evaluate_entry")
if entry_callback is not None:
entry_callback(expr, input, environment)
if getattr(expr, "type", None) is not None:
if expr.type == "path":
result = self.evaluate_path(expr, input, environment)
elif expr.type == "binary":
result = self.evaluate_binary(expr, input, environment)
elif expr.type == "unary":
result = self.evaluate_unary(expr, input, environment)
elif expr.type == "name":
result = self.evaluate_name(expr, input, environment)
if self.parser.dbg:
print("evalName " + result)
elif expr.type == "string" or expr.type == "number" or expr.type == "value":
result = self.evaluate_literal(expr) # , input, environment);
elif expr.type == "wildcard":
result = self.evaluate_wildcard(expr, input) # , environment);
elif expr.type == "descendant":
result = self.evaluate_descendants(expr, input) # , environment);
elif expr.type == "parent":
result = environment.lookup(expr.slot.label)
elif expr.type == "condition":
result = self.evaluate_condition(expr, input, environment)
elif expr.type == "block":
result = self.evaluate_block(expr, input, environment)
elif expr.type == "bind":
result = self.evaluate_bind_expression(expr, input, environment)
elif expr.type == "regex":
result = self.evaluate_regex(expr) # , input, environment);
elif expr.type == "function":
result = self.evaluate_function(expr, input, environment, utils.Utils.NONE)
elif expr.type == "variable":
result = self.evaluate_variable(expr, input, environment)
elif expr.type == "lambda":
result = self.evaluate_lambda(expr, input, environment)
elif expr.type == "partial":
result = self.evaluate_partial_application(expr, input, environment)
elif expr.type == "apply":
result = self.evaluate_apply_expression(expr, input, environment)
elif expr.type == "transform":
result = self.evaluate_transform_expression(expr, input, environment)
if getattr(expr, "predicate", None) is not None:
for item in expr.predicate:
result = self.evaluate_filter(item.expr, result, environment)
if getattr(expr, "type", None) is not None and expr.type != "path" and getattr(expr, "group", None) is not None:
result = self.evaluate_group_expression(expr.group, result, environment)
exit_callback = environment.lookup("__evaluate_exit")
if exit_callback is not None:
exit_callback(expr, input, environment, result)
# mangle result (list of 1 element -> 1 element, empty list -> null)
if result is not None and utils.Utils.is_sequence(result) and not result.tuple_stream:
if expr.keep_array:
result.keep_singleton = True
if not result:
result = None
elif len(result) == 1:
result = result if result.keep_singleton else result[0]
return result
#
# Evaluate path expression against input data
# @param {Object} expr - JSONata expression
# @param {Object} input - Input data to evaluate against
# @param {Object} environment - Environment
# @returns {*} Evaluated input data
#
# async
def evaluate_path(self, expr: Optional[parser.Parser.Symbol], input: Optional[Any],
environment: Optional[Frame]) -> Optional[Any]:
# expr is an array of steps
# if the first step is a variable reference ($...), including root reference ($$),
# then the path is absolute rather than relative
if isinstance(input, list) and expr.steps[0].type != "variable":
input_sequence = input
else:
# if input is not an array, make it so
input_sequence = utils.Utils.create_sequence(input)
result_sequence = None
is_tuple_stream = False
tuple_bindings = None
# evaluate each step in turn
for ii, step in enumerate(expr.steps):
if step.tuple is not None:
is_tuple_stream = True
# if the first step is an explicit array constructor, then just evaluate that (i.e. don"t iterate over a context array)
if ii == 0 and step.consarray:
result_sequence = self.eval(step, input_sequence, environment)
else:
if is_tuple_stream:
tuple_bindings = self.evaluate_tuple_step(step, input_sequence, tuple_bindings, environment)
else:
result_sequence = self.evaluate_step(step, input_sequence, environment, ii == len(expr.steps) - 1)
if not is_tuple_stream and (result_sequence is None or not result_sequence):
break
if step.focus is None:
input_sequence = result_sequence
if is_tuple_stream:
if expr.tuple is not None:
# tuple stream is carrying ancestry information - keep this
result_sequence = tuple_bindings
else:
result_sequence = utils.Utils.create_sequence_from_iter(b["@"] for b in tuple_bindings)
if expr.keep_singleton_array:
# If we only got an ArrayList, convert it so we can set the keepSingleton flag
if not (isinstance(result_sequence, utils.Utils.JList)):
result_sequence = utils.Utils.JList(result_sequence)
# if the array is explicitly constructed in the expression and marked to promote singleton sequences to array
if (isinstance(result_sequence, utils.Utils.JList)) and result_sequence.cons and not result_sequence.sequence:
result_sequence = utils.Utils.create_sequence(result_sequence)
result_sequence.keep_singleton = True
if expr.group is not None:
result_sequence = self.evaluate_group_expression(expr.group,
tuple_bindings if is_tuple_stream else result_sequence,
environment)
return result_sequence
def create_frame_from_tuple(self, environment: Optional[Frame], tuple: Optional[Mapping[str, Any]]) -> Frame:
frame = self.create_frame(environment)
if tuple is not None:
for prop, val in tuple.items():
frame.bind(prop, val)
return frame
#
# Evaluate a step within a path
# @param {Object} expr - JSONata expression
# @param {Object} input - Input data to evaluate against
# @param {Object} environment - Environment
# @param {boolean} lastStep - flag the last step in a path
# @returns {*} Evaluated input data
#
# async
def evaluate_step(self, expr: parser.Parser.Symbol, input: Optional[Any], environment: Optional[Frame],
last_step: bool) -> Optional[Any]:
if expr.type == "sort":
result = self.evaluate_sort_expression(expr, input, environment)
if expr.stages is not None:
result = self.evaluate_stages(expr.stages, result, environment)
return result
result = utils.Utils.create_sequence()
for inp in input:
res = self.eval(expr, inp, environment)
if expr.stages is not None:
for stage in expr.stages:
res = self.evaluate_filter(stage.expr, res, environment)
if res is not None:
result.append(res)
result_sequence = utils.Utils.create_sequence()
if last_step and len(result) == 1 and (isinstance(result[0], list)) and not utils.Utils.is_sequence(
result[0]):
result_sequence = result[0]
else:
# flatten the sequence
for res in result:
if not (isinstance(res, list)) or (isinstance(res, utils.Utils.JList) and res.cons):
# it's not an array - just push into the result sequence
result_sequence.append(res)
else:
# res is a sequence - flatten it into the parent sequence
result_sequence.extend(res)
return result_sequence
# async
def evaluate_stages(self, stages: Optional[Sequence[parser.Parser.Symbol]], input: Any,
environment: Optional[Frame]) -> Any:
result = input
for stage in stages:
if stage.type == "filter":
result = self.evaluate_filter(stage.expr, result, environment)
elif stage.type == "index":
for ee, tuple in enumerate(result):
tuple[str(stage.value)] = ee
return result
#
# Evaluate a step within a path
# @param {Object} expr - JSONata expression
# @param {Object} input - Input data to evaluate against
# @param {Object} tupleBindings - The tuple stream
# @param {Object} environment - Environment
# @returns {*} Evaluated input data
#
# async
def evaluate_tuple_step(self, expr: parser.Parser.Symbol, input: Optional[Sequence],
tuple_bindings: Optional[Sequence[Mapping[str, Any]]],
environment: Optional[Frame]) -> Optional[Any]:
result = None
if expr.type == "sort":
if tuple_bindings is not None:
result = self.evaluate_sort_expression(expr, tuple_bindings, environment)
else:
sorted = self.evaluate_sort_expression(expr, input, environment)
result = utils.Utils.create_sequence_from_iter({"@": item, expr.index: ss}
for ss, item in enumerate(sorted))
result.tuple_stream = True
if expr.stages is not None:
result = self.evaluate_stages(expr.stages, result, environment)
return result
result = utils.Utils.create_sequence()
result.tuple_stream = True
step_env = environment
if tuple_bindings is None:
tuple_bindings = [{"@": item} for item in input]
for tuple_binding in tuple_bindings:
step_env = self.create_frame_from_tuple(environment, tuple_binding)
res = self.eval(expr, tuple_binding["@"], step_env)
# res is the binding sequence for the output tuple stream
if res is not None:
if not (isinstance(res, list)):
res = [res]
for bb, item in enumerate(res):
tuple = dict(tuple_binding)
# Object.assign(tuple, tupleBindings[ee])
if (isinstance(res, utils.Utils.JList)) and res.tuple_stream:
tuple.update(item)
else:
if expr.focus is not None:
tuple[expr.focus] = item
tuple["@"] = tuple_binding["@"]
else:
tuple["@"] = item
if expr.index is not None:
tuple[expr.index] = bb
if expr.ancestor is not None:
tuple[expr.ancestor.label] = tuple_binding["@"]
result.append(tuple)
if expr.stages is not None:
result = self.evaluate_stages(expr.stages, result, environment)
return result
#
# Apply filter predicate to input data
# @param {Object} predicate - filter expression
# @param {Object} input - Input data to apply predicates against
# @param {Object} environment - Environment
# @returns {*} Result after applying predicates
#
# async
def evaluate_filter(self, predicate: Optional[Any], input: Optional[Any], environment: Optional[Frame]) -> Any:
results = utils.Utils.create_sequence()
if isinstance(input, utils.Utils.JList) and input.tuple_stream:
results.tuple_stream = True
if not (isinstance(input, list)):
input = utils.Utils.create_sequence(input)
if predicate.type == "number":
index = int(predicate.value) # round it down - was Math.floor
if index < 0:
# count in from end of array
index = len(input) + index
item = input[index] if 0 <= index < len(input) else None
if item is not None:
if isinstance(item, list):
results = item
else:
results.append(item)
else:
for index, item in enumerate(input):
context = item
env = environment
if isinstance(input, utils.Utils.JList) and input.tuple_stream:
context = item["@"]
env = self.create_frame_from_tuple(environment, item)
res = self.eval(predicate, context, env)
if utils.Utils.is_numeric(res):
res = utils.Utils.create_sequence(res)
if utils.Utils.is_array_of_numbers(res):
for ires in res:
# round it down
ii = int(ires) # Math.floor(ires);
if ii < 0:
# count in from end of array
ii = len(input) + ii
if ii == index:
results.append(item)
elif Jsonata.boolize(res):
results.append(item)
return results
#
# Evaluate binary expression against input data
# @param {Object} expr - JSONata expression
# @param {Object} input - Input data to evaluate against
# @param {Object} environment - Environment
# @returns {*} Evaluated input data
#
# async
def evaluate_binary(self, expr: Optional[parser.Parser.Symbol], input: Optional[Any],
environment: Optional[Frame]) -> Optional[Any]:
lhs = self.eval(expr.lhs, input, environment)
op = str(expr.value)
if op == "and" or op == "or":
# defer evaluation of RHS to allow short-circuiting
evalrhs = lambda: self.eval(expr.rhs, input, environment)
try:
return self.evaluate_boolean_expression(lhs, evalrhs, op)
except Exception as err:
if not (isinstance(err, jexception.JException)):
raise jexception.JException("Unexpected", expr.position)
# err.position = expr.position
# err.token = op
raise err
rhs = self.eval(expr.rhs, input, environment) # evalrhs();
try:
if op == "+" or op == "-" or op == "*" or op == "/" or op == "%":
result = self.evaluate_numeric_expression(lhs, rhs, op)
elif op == "=" or op == "!=":
result = self.evaluate_equality_expression(lhs, rhs, op)
elif op == "<" or op == "<=" or op == ">" or op == ">=":
result = self.evaluate_comparison_expression(lhs, rhs, op)
elif op == "&":
result = self.evaluate_string_concat(lhs, rhs)
elif op == "..":
result = self.evaluate_range_expression(lhs, rhs)
elif op == "in":
result = self.evaluate_includes_expression(lhs, rhs)
else:
raise jexception.JException("Unexpected operator " + op, expr.position)
except Exception as err:
# err.position = expr.position
# err.token = op
raise err
return result
#
# Evaluate unary expression against input data
# @param {Object} expr - JSONata expression
# @param {Object} input - Input data to evaluate against
# @param {Object} environment - Environment
# @returns {*} Evaluated input data
#
# async
def evaluate_unary(self, expr: Optional[parser.Parser.Symbol], input: Optional[Any],
environment: Optional[Frame]) -> Optional[Any]:
result = None
value = str(expr.value)
if value == "-":
result = self.eval(expr.expression, input, environment)
if result is None:
result = None
elif utils.Utils.is_numeric(result):
result = utils.Utils.convert_number(-float(result))
else:
raise jexception.JException("D1002", expr.position, expr.value, result)
elif value == "[":
# array constructor - evaluate each item
result = utils.Utils.JList() # [];
idx = 0
for item in expr.expressions:
environment.is_parallel_call = idx > 0
value = self.eval(item, input, environment)
if value is not None:
if str(item.value) == "[":
result.append(value)
else:
result = functions.Functions.append(result, value)
idx += 1
if expr.consarray:
if not (isinstance(result, utils.Utils.JList)):
result = utils.Utils.JList(result)
# System.out.println("const "+result)
result.cons = True
elif value == "{":
# object constructor - apply grouping
result = self.evaluate_group_expression(expr, input, environment)
return result
#
# Evaluate name object against input data
# @param {Object} expr - JSONata expression
# @param {Object} input - Input data to evaluate against
# @param {Object} environment - Environment
# @returns {*} Evaluated input data
#
def evaluate_name(self, expr: Optional[parser.Parser.Symbol], input: Optional[Any],
environment: Optional[Frame]) -> Optional[Any]:
# lookup the "name" item in the input
return functions.Functions.lookup(input, str(expr.value))
#
# Evaluate literal against input data
# @param {Object} expr - JSONata expression
# @returns {*} Evaluated input data
#
def evaluate_literal(self, expr: Optional[parser.Parser.Symbol]) -> Optional[Any]:
return expr.value if expr.value is not None else utils.Utils.NULL_VALUE
#
# Evaluate wildcard against input data
# @param {Object} expr - JSONata expression
# @param {Object} input - Input data to evaluate against
# @returns {*} Evaluated input data
#
def evaluate_wildcard(self, expr: Optional[parser.Parser.Symbol], input: Optional[Any]) -> Optional[Any]:
results = utils.Utils.create_sequence()
if (isinstance(input, utils.Utils.JList)) and input.outer_wrapper and input:
input = input[0]
if input is not None and isinstance(input, dict):
for value in input.values():
if isinstance(value, list):
value = self.flatten(value, None)
results = functions.Functions.append(results, value)
else:
results.append(value)
elif isinstance(input, list):
# Java: need to handle List separately
for value in input:
if isinstance(value, list):
value = self.flatten(value, None)
results = functions.Functions.append(results, value)
else:
results.append(value)
# result = normalizeSequence(results)
return results
#
# Returns a flattened array
# @param {Array} arg - the array to be flatten
# @param {Array} flattened - carries the flattened array - if not defined, will initialize to []
# @returns {Array} - the flattened array
#
def flatten(self, arg: Any, flattened: Optional[MutableSequence]) -> Any:
if flattened is None:
flattened = []
if isinstance(arg, list):
for item in arg:
self.flatten(item, flattened)
else:
flattened.append(arg)
return flattened
#
# Evaluate descendants against input data
# @param {Object} expr - JSONata expression
# @param {Object} input - Input data to evaluate against
# @returns {*} Evaluated input data
#
def evaluate_descendants(self, expr: Optional[parser.Parser.Symbol], input: Optional[Any]) -> Optional[Any]:
result = None
result_sequence = utils.Utils.create_sequence()
if input is not None:
# traverse all descendants of this object/array
self.recurse_descendants(input, result_sequence)
if len(result_sequence) == 1:
result = result_sequence[0]
else:
result = result_sequence
return result
#
# Recurse through descendants
# @param {Object} input - Input data
# @param {Object} results - Results
#
def recurse_descendants(self, input: Optional[Any], results: MutableSequence) -> None:
# this is the equivalent of //* in XPath
if not (isinstance(input, list)):
results.append(input)
if isinstance(input, list):
for member in input:
self.recurse_descendants(member, results)
elif input is not None and isinstance(input, dict):
for value in input.values():
self.recurse_descendants(value, results)
#
# Evaluate numeric expression against input data
# @param {Object} lhs - LHS value
# @param {Object} rhs - RHS value
# @param {Object} op - opcode
# @returns {*} Result
#
def evaluate_numeric_expression(self, lhs: Optional[Any], rhs: Optional[Any], op: Optional[str]) -> Optional[Any]:
result = 0
if lhs is not None and not utils.Utils.is_numeric(lhs):
raise jexception.JException("T2001", -1, op, lhs)
if rhs is not None and not utils.Utils.is_numeric(rhs):
raise jexception.JException("T2002", -1, op, rhs)
if lhs is None or rhs is None:
# if either side is undefined, the result is undefined
return None
# System.out.println("op22 "+op+" "+_lhs+" "+_rhs)
lhs = float(lhs)
rhs = float(rhs)
if op == "+":
result = lhs + rhs
elif op == "-":
result = lhs - rhs
elif op == "*":
result = lhs * rhs
elif op == "/":
result = lhs / rhs
elif op == "%":
result = int(math.fmod(lhs, rhs))
return utils.Utils.convert_number(result)
#
# Evaluate equality expression against input data
# @param {Object} lhs - LHS value
# @param {Object} rhs - RHS value
# @param {Object} op - opcode
# @returns {*} Result
#
def evaluate_equality_expression(self, lhs: Optional[Any], rhs: Optional[Any], op: Optional[str]) -> Optional[Any]:
if lhs is None or rhs is None:
# if either side is undefined, the result is false
return False
# JSON might come with integers,
# convert all to double...
# FIXME: semantically OK?
if not isinstance(lhs, bool) and isinstance(lhs, (int, float)):
lhs = float(lhs)
if not isinstance(rhs, bool) and isinstance(rhs, (int, float)):
rhs = float(rhs)
result = None
if op == "=":
result = utils.Utils.is_deep_equal(lhs, rhs)
elif op == "!=":
result = not utils.Utils.is_deep_equal(lhs, rhs)
return result
#
# Evaluate comparison expression against input data
# @param {Object} lhs - LHS value
# @param {Object} rhs - RHS value
# @param {Object} op - opcode
# @returns {*} Result
#
def evaluate_comparison_expression(self, lhs: Optional[Any], rhs: Optional[Any], op: Optional[str]) -> Optional[Any]:
result = None
# type checks
lcomparable = (lhs is None or isinstance(lhs, str) or
(not isinstance(lhs, bool) and isinstance(lhs, (int, float))))
rcomparable = (rhs is None or isinstance(rhs, str) or
(not isinstance(rhs, bool) and isinstance(rhs, (int, float))))
# if either aa or bb are not comparable (string or numeric) values, then throw an error
if not lcomparable or not rcomparable:
raise jexception.JException("T2010", 0, op, lhs if lhs is not None else rhs)
# if either side is undefined, the result is undefined
if lhs is None or rhs is None:
return None
# if aa and bb are not of the same type
if type(lhs) is not type(rhs):
if (not isinstance(lhs, bool) and isinstance(lhs, (int, float)) and
not isinstance(rhs, bool) and isinstance(rhs, (int, float))):
# Java : handle Double / Integer / Long comparisons
# convert all to double -> loss of precision (64-bit long to double) be a problem here?
lhs = float(lhs)
rhs = float(rhs)
else:
raise jexception.JException("T2009", 0, lhs, rhs)
if op == "<":
result = lhs < rhs
elif op == "<=":
result = lhs <= rhs
elif op == ">":
result = lhs > rhs
elif op == ">=":
result = lhs >= rhs
return result
#
# Inclusion operator - in
#
# @param {Object} lhs - LHS value
# @param {Object} rhs - RHS value
# @returns {boolean} - true if lhs is a member of rhs
#
def evaluate_includes_expression(self, lhs: Optional[Any], rhs: Optional[Any]) -> Any:
result = False
if lhs is None or rhs is None:
# if either side is undefined, the result is false
return False
if not (isinstance(rhs, list)):
rhs = [rhs]
for item in rhs:
if item == lhs:
result = True
break
return result
#
# Evaluate boolean expression against input data
# @param {Object} lhs - LHS value
# @param {functions.Function} evalrhs - Object to evaluate RHS value
# @param {Object} op - opcode
# @returns {*} Result
#
# async
def evaluate_boolean_expression(self, lhs: Optional[Any], evalrhs: Callable[[], Optional[Any]],
op: Optional[str]) -> Optional[Any]:
result = None
l_bool = Jsonata.boolize(lhs)
if op == "and":
result = l_bool and Jsonata.boolize(evalrhs())
elif op == "or":
result = l_bool or Jsonata.boolize(evalrhs())
return result
@staticmethod
def boolize(value: Optional[Any]) -> bool:
booled_value = functions.Functions.to_boolean(value)
return False if booled_value is None else booled_value
#
# Evaluate string concatenation against input data
# @param {Object} lhs - LHS value
# @param {Object} rhs - RHS value
# @returns {string|*} Concatenated string
#
def evaluate_string_concat(self, lhs: Optional[Any], rhs: Optional[Any]) -> str:
lstr = ""
rstr = ""
if lhs is not None:
lstr = functions.Functions.string(lhs, None)
if rhs is not None:
rstr = functions.Functions.string(rhs, None)
result = lstr + rstr
return result
@dataclass
class GroupEntry:
data: Optional[Any]
exprIndex: int
#
# Evaluate group expression against input data
# @param {Object} expr - JSONata expression
# @param {Object} input - Input data to evaluate against
# @param {Object} environment - Environment
# @returns {{}} Evaluated input data
#
# async
def evaluate_group_expression(self, expr: Optional[parser.Parser.Symbol], input: Optional[Any],
environment: Optional[Frame]) -> Any:
result = {}
groups = {}
reduce = True if (isinstance(input, utils.Utils.JList)) and input.tuple_stream else False
# group the input sequence by "key" expression
if not (isinstance(input, list)):
input = utils.Utils.create_sequence(input)
# if the array is empty, add an undefined entry to enable literal JSON object to be generated
if not input:
input.append(None)
for itemIndex, item in enumerate(input):
env = self.create_frame_from_tuple(environment, item) if reduce else environment
for pairIndex, pair in enumerate(expr.lhs_object):
key = self.eval(pair[0], item["@"] if reduce else item, env)
# key has to be a string
if key is not None and not (isinstance(key, str)):
raise jexception.JException("T1003", expr.position, key)
if key is not None:
entry = Jsonata.GroupEntry(item, pairIndex)
if groups.get(key) is not None:
# a value already exists in this slot
if groups[key].exprIndex != pairIndex:
# this key has been generated by another expression in this group
# when multiple key expressions evaluate to the same key, then error D1009 must be thrown
raise jexception.JException("D1009", expr.position, key)
# append it as an array
groups[key].data = functions.Functions.append(groups[key].data, item)
else:
groups[key] = entry
# iterate over the groups to evaluate the "value" expression
# let generators = /* await */ Promise.all(Object.keys(groups).map(/* async */ (key, idx) => {
idx = 0
for k, v in groups.items():
entry = v
context = entry.data
env = environment
if reduce:
tuple = self.reduce_tuple_stream(entry.data)
context = tuple["@"]
tuple.pop("@", None)
env = self.create_frame_from_tuple(environment, tuple)
env.is_parallel_call = idx > 0
# return [key, /* await */ eval(expr.lhs[entry.exprIndex][1], context, env)]
res = self.eval(expr.lhs_object[entry.exprIndex][1], context, env)
if res is not None:
result[k] = res
idx += 1
# for (let generator of generators) {
# var [key, value] = /* await */ generator
# if(typeof value !== "undefined") {
# result[key] = value
# }
# }
return result
def reduce_tuple_stream(self, tuple_stream: Optional[Any]) -> Optional[Any]:
if not (isinstance(tuple_stream, list)):
return tuple_stream
result = dict(tuple_stream[0])