jsonata 2.2.2.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -92,8 +92,8 @@ module Jsonata
92
92
  end
93
93
 
94
94
  # parses and evaluates the supplied expression
95
- # @param expr - expression to evaluate
96
- # @returns result of evaluating the expression
95
+ # @param expr [String] expression to evaluate
96
+ # @return [Object] result of evaluating the expression
97
97
  def function_eval(expr, focus)
98
98
  # undefined inputs always return undefined
99
99
  return nil if expr.nil?
@@ -127,8 +127,8 @@ module Jsonata
127
127
  end
128
128
 
129
129
  # Clones an object
130
- # @param arg - object to clone (deep copy)
131
- # @returns the cloned object
130
+ # @param arg [Object] object to clone (deep copy)
131
+ # @return [Object] the cloned object
132
132
  def function_clone(arg)
133
133
  # undefined inputs always return undefined
134
134
  return nil if arg.nil?
@@ -141,10 +141,10 @@ module Jsonata
141
141
  module_function
142
142
 
143
143
  # Evaluate expression against input data
144
- # @param expr - JSONata expression
145
- # @param input - Input data to evaluate against
146
- # @param environment - Environment
147
- # @returns Evaluated input data
144
+ # @param expr [Object] JSONata expression
145
+ # @param input [Object] Input data to evaluate against
146
+ # @param environment [Object] Environment
147
+ # @return [Object] Evaluated input data
148
148
  def evaluate(expr, input, environment)
149
149
  environment.base.depth += 1
150
150
  environment.base.guardrails.call
@@ -170,6 +170,8 @@ module Jsonata
170
170
  environment.lookup(expr[:slot][:label])
171
171
  when 'condition'
172
172
  evaluate_condition(expr, input, environment)
173
+ when 'template'
174
+ evaluate_template(expr, input, environment)
173
175
  when 'block'
174
176
  evaluate_block(expr, input, environment)
175
177
  when 'bind'
@@ -191,8 +193,8 @@ module Jsonata
191
193
  end
192
194
 
193
195
  if expr.key?(:predicate)
194
- expr[:predicate].each do |predicate|
195
- result = evaluate_filter(predicate[:expr], result, environment)
196
+ expr[:predicate].each_with_index do |predicate, ii|
197
+ result = evaluate_filter(predicate[:expr], result, environment, ii < expr[:predicate].length - 1)
196
198
  end
197
199
  end
198
200
 
@@ -291,7 +293,7 @@ module Jsonata
291
293
  end
292
294
 
293
295
  # Evaluate a step within a path
294
- # @param last_step - flag the last step in a path
296
+ # @param last_step [Boolean] flag the last step in a path
295
297
  def evaluate_step(expr, input, environment, last_step)
296
298
  if expr[:type] == 'sort'
297
299
  result = evaluate_sort_expression(expr, input, environment)
@@ -303,8 +305,8 @@ module Jsonata
303
305
 
304
306
  input.each do |item|
305
307
  res = evaluate(expr, item, environment)
306
- expr[:stages]&.each do |stage|
307
- res = evaluate_filter(stage[:expr], res, environment)
308
+ expr[:stages]&.each_with_index do |stage, ss|
309
+ res = evaluate_filter(stage[:expr], res, environment, ss < expr[:stages].length - 1)
308
310
  end
309
311
  result.push(res) unless res.nil?
310
312
  end
@@ -330,10 +332,11 @@ module Jsonata
330
332
 
331
333
  def evaluate_stages(stages, input, environment)
332
334
  result = input
333
- stages.each do |stage|
335
+ stages.each_with_index do |stage, ss|
334
336
  case stage[:type]
335
337
  when 'filter'
336
- result = evaluate_filter(stage[:expr], result, environment)
338
+ result = evaluate_filter(stage[:expr], result, environment,
339
+ ss < stages.length - 1 && stages[ss + 1][:type] == 'filter')
337
340
  when 'index'
338
341
  result.each_with_index do |tuple, ee|
339
342
  tuple[stage[:value]] = ee
@@ -344,7 +347,7 @@ module Jsonata
344
347
  end
345
348
 
346
349
  # Evaluate a step within a path
347
- # @param tuple_bindings - The tuple stream
350
+ # @param tuple_bindings [Object] The tuple stream
348
351
  def evaluate_tuple_step(expr, input, tuple_bindings, environment)
349
352
  if expr[:type] == 'sort'
350
353
  if tuple_bindings
@@ -373,7 +376,7 @@ module Jsonata
373
376
  # res is the binding sequence for the output tuple stream
374
377
  next if res.nil?
375
378
 
376
- res = [res] unless res.kind_of?(Array)
379
+ res = [res] if !res.kind_of?(Array) || (res.kind_of?(JArray) && res.cons && !expr[:stages])
377
380
  res.each_with_index do |item, bb|
378
381
  tuple = {}
379
382
  tuple.merge!(binding)
@@ -399,10 +402,11 @@ module Jsonata
399
402
  end
400
403
 
401
404
  # Apply filter predicate to input data
402
- # @param predicate - filter expression
403
- # @param input - Input data to apply predicates against
404
- # @returns Result after applying predicates
405
- def evaluate_filter(predicate, input, environment)
405
+ # @param predicate [Object] filter expression
406
+ # @param input [Object] Input data to apply predicates against
407
+ # @param chained [Boolean] another predicate will be applied to the result
408
+ # @return [Object] Result after applying predicates
409
+ def evaluate_filter(predicate, input, environment, chained)
406
410
  results = environment.base.create_sequence
407
411
  results.tuple_stream = true if input.kind_of?(JArray) && input.tuple_stream
408
412
  input = environment.base.create_sequence(input) unless input.kind_of?(Array)
@@ -421,6 +425,9 @@ module Jsonata
421
425
  end
422
426
  end
423
427
  else
428
+ # the position selected by the predicate, while it evaluates to the same number for every item
429
+ position = nil
430
+ same_position = true
424
431
  input.each_with_index do |item, index|
425
432
  context = item
426
433
  env = environment
@@ -429,7 +436,11 @@ module Jsonata
429
436
  env = create_frame_from_tuple(environment, item)
430
437
  end
431
438
  res = evaluate(predicate, context, env)
432
- res = [res] if Utils.numeric?(res)
439
+ if Utils.numeric?(res)
440
+ res = [res]
441
+ else
442
+ same_position = false
443
+ end
433
444
  if Utils.array_of_numbers?(res)
434
445
  res.each do |ires|
435
446
  # round it down
@@ -438,12 +449,20 @@ module Jsonata
438
449
  # count in from end of array
439
450
  ii = input.length + ii
440
451
  end
452
+ same_position = false if index.positive? && ii != position
453
+ position = ii
441
454
  results.push(item) if ii == index
442
455
  end
443
456
  elsif FN.boolean(res) # truthy
444
457
  results.push(item)
445
458
  end
446
459
  end
460
+ if chained && same_position && results.length == 1 && results[0].kind_of?(Array)
461
+ # an expression that evaluates to the same number for every item selects an array the same way
462
+ # a literal index does, so the next predicate is applied to that array rather than to a sequence
463
+ # containing it
464
+ results = results[0]
465
+ end
447
466
  end
448
467
  results
449
468
  end
@@ -459,8 +478,8 @@ module Jsonata
459
478
  begin
460
479
  return evaluate_boolean_expression(lhs, evalrhs, op)
461
480
  rescue Jsonata::Error => e
462
- e.position = expr[:position]
463
- e.token = op
481
+ e.position = expr[:position] if e.position.nil?
482
+ e.token = op if e.token.nil?
464
483
  raise
465
484
  end
466
485
  end
@@ -563,8 +582,8 @@ module Jsonata
563
582
  end
564
583
 
565
584
  # Returns a flattened array
566
- # @param arg - the array to be flatten
567
- # @param flattened - carries the flattened array - if not defined, will initialize to []
585
+ # @param arg [Array] the array to be flatten
586
+ # @param flattened [Array] carries the flattened array - if not defined, will initialize to []
568
587
  def flatten(arg, flattened = [])
569
588
  if arg.kind_of?(Array)
570
589
  arg.each do |item|
@@ -595,7 +614,8 @@ module Jsonata
595
614
  # Recurse through descendants
596
615
  def recurse_descendants(input, results)
597
616
  # this is the equivalent of //* in XPath
598
- results.push(input) unless input.kind_of?(Array)
617
+ # a function is never a descendant, the same as for the single wildcard (*)
618
+ results.push(input) if !input.kind_of?(Array) && !Utils.function?(input)
599
619
  if input.kind_of?(Array)
600
620
  input.each do |member|
601
621
  recurse_descendants(member, results)
@@ -669,7 +689,7 @@ module Jsonata
669
689
  end
670
690
 
671
691
  # Inclusion operator - in
672
- # @returns true if lhs is a member of rhs
692
+ # @return [Boolean] true if lhs is a member of rhs
673
693
  def evaluate_includes_expression(lhs, rhs)
674
694
  # if either side is undefined, the result is false
675
695
  return false if lhs.nil? || rhs.nil?
@@ -680,7 +700,7 @@ module Jsonata
680
700
  end
681
701
 
682
702
  # Evaluate boolean expression against input data
683
- # @param evalrhs - function to evaluate RHS value
703
+ # @param evalrhs [Lambda, NativeFunction, Proc] function to evaluate RHS value
684
704
  def evaluate_boolean_expression(lhs, evalrhs, op)
685
705
  l_bool = boolize(lhs)
686
706
 
@@ -699,12 +719,40 @@ module Jsonata
699
719
 
700
720
  # Evaluate string concatenation against input data
701
721
  def evaluate_string_concat(lhs, rhs)
702
- lstr = ''
703
- rstr = ''
704
- lstr = FN.string(lhs) unless lhs.nil?
705
- rstr = FN.string(rhs) unless rhs.nil?
706
-
707
- lstr + rstr
722
+ cast_string(lhs) + cast_string(rhs)
723
+ end
724
+
725
+ # Cast a value to string for concatenation, as done by the & operator and template strings
726
+ # @param value [Object] value to cast
727
+ # @return [String] the empty string if value is undefined, otherwise the result of $string(value)
728
+ def cast_string(value)
729
+ value.nil? ? '' : FN.string(value)
730
+ end
731
+
732
+ # Evaluate template string against input data
733
+ # Literal text is appended as is; each embedded expression is evaluated and cast like the & operator
734
+ # @param expr [Hash] JSONata expression
735
+ # @param input [Object] Input data to evaluate against
736
+ # @param environment [Frame] Environment
737
+ # @return [String] Evaluated template
738
+ def evaluate_template(expr, input, environment)
739
+ result = +''
740
+ expr[:parts].each do |part|
741
+ if part.kind_of?(String)
742
+ result << part
743
+ next
744
+ end
745
+ value = evaluate(part[:expression], input, environment)
746
+ begin
747
+ result << cast_string(value)
748
+ rescue Jsonata::Error => e
749
+ # point at the embedded expression whose value could not be cast
750
+ e.position = part[:position]
751
+ e.token = '{'
752
+ raise e
753
+ end
754
+ end
755
+ result
708
756
  end
709
757
 
710
758
  # Evaluate group expression against input data
@@ -782,7 +830,7 @@ module Jsonata
782
830
  end
783
831
 
784
832
  # Evaluate range expression against input data
785
- # @returns Resultant array
833
+ # @return [Array] Resultant array
786
834
  def evaluate_range_expression(lhs, rhs, environment)
787
835
  raise Jsonata::Error.new('T2003', :value => lhs) if !lhs.nil? && !Utils.integer?(lhs)
788
836
  raise Jsonata::Error.new('T2004', :value => rhs) if !rhs.nil? && !Utils.integer?(rhs)
@@ -846,27 +894,29 @@ module Jsonata
846
894
  end
847
895
 
848
896
  # Prepare a regex
849
- # @param expr - expression containing regex
850
- # @returns Higher order function representing prepared regex
897
+ # @param expr [Object] expression containing regex
898
+ # @return [Lambda, NativeFunction, Proc] Higher order function representing prepared regex
851
899
  def evaluate_regex(expr, _input, environment)
852
900
  engine = environment.base.regex_engine
853
901
  re = engine ? engine.call(expr[:value].source, expr[:value].flags) : expr[:value].regexp
854
- last_index = 0
902
+ # (jsonata-js: re.lastIndex)
903
+ re_last_index = 0
855
904
  closure = nil
856
905
  closure = lambda do |str, from_index = nil|
857
906
  result = nil
858
- last_index = from_index || 0
859
- match = last_index > str.length ? nil : re.match(str, last_index)
907
+ re_last_index = from_index || 0
908
+ match = re_last_index > str.length ? nil : re.match(str, re_last_index)
860
909
  if match.nil?
861
- last_index = 0
910
+ re_last_index = 0
862
911
  else
863
- last_index = match.end(0)
912
+ re_last_index = match.end(0)
864
913
  result = {
865
914
  'match' => match[0],
866
915
  'start' => match.begin(0),
867
916
  'end' => match.end(0),
868
917
  'groups' => match.captures
869
918
  }
919
+ last_index = re_last_index
870
920
  result['next'] = lambda do
871
921
  if last_index >= str.length
872
922
  nil
@@ -899,8 +949,8 @@ module Jsonata
899
949
  end
900
950
 
901
951
  # sort / order-by operator
902
- # @param expr - AST for operator
903
- # @returns Ordered sequence
952
+ # @param expr [Object] AST for operator
953
+ # @return [Object] Ordered sequence
904
954
  def evaluate_sort_expression(expr, input, environment)
905
955
  # evaluate the lhs, then sort the results in order according to rhs expression
906
956
  lhs = input
@@ -969,9 +1019,31 @@ module Jsonata
969
1019
  focus.sort(lhs, comparator)
970
1020
  end
971
1021
 
1022
+ # Collects the objects and arrays that make up a value, by following their own properties
1023
+ # @param value [Object] the value
1024
+ # @return [Hash] the objects and arrays (jsonata-js: WeakSet; Ruby specific: a compare_by_identity Hash)
1025
+ def objects_within(value)
1026
+ objects = {}.compare_by_identity
1027
+ pending = [value]
1028
+ until pending.empty?
1029
+ item = pending.pop
1030
+ next unless !item.equal?(NULL) && Utils.typeof(item) == 'object' && !Utils.function?(item) && !objects.key?(item)
1031
+
1032
+ objects[item] = true
1033
+ # only follow the values of data properties, so that no getters are run
1034
+ # (Ruby specific: only the values of Hashes and the items of Arrays are data properties)
1035
+ if item.kind_of?(Hash)
1036
+ item.each_value { |val| pending.push(val) }
1037
+ elsif item.kind_of?(Array)
1038
+ item.each { |val| pending.push(val) }
1039
+ end
1040
+ end
1041
+ objects
1042
+ end
1043
+
972
1044
  # create a transformer function
973
- # @param expr - AST for operator
974
- # @returns tranformer function
1045
+ # @param expr [Object] AST for operator
1046
+ # @return [Object] tranformer function
975
1047
  def evaluate_transform_expression(expr, _input, environment)
976
1048
  # create a function to implement the transform definition
977
1049
  transformer = lambda do |obj| # signature <(oa):o>
@@ -979,7 +1051,8 @@ module Jsonata
979
1051
  next nil if obj.nil?
980
1052
 
981
1053
  # this function returns a copy of obj with changes specified by the pattern/operation
982
- clone_function = environment.lookup('clone')
1054
+ # Look up $clone from the top-level execution environment.
1055
+ clone_function = environment.base.lookup('clone')
983
1056
  unless Utils.function?(clone_function)
984
1057
  # throw type error
985
1058
  raise Jsonata::Error.new('T2013', :position => expr[:position])
@@ -989,17 +1062,32 @@ module Jsonata
989
1062
  matches = evaluate(expr[:pattern], result, environment)
990
1063
  unless matches.nil?
991
1064
  matches = [matches] unless matches.kind_of?(Array)
1065
+ # only the copy can be changed, so check every match before changing any of them.
1066
+ copy = objects_within(result)
1067
+ matches.each do |matched|
1068
+ # (jsonata-js: a match that is the prototype of the result throws D1010; Ruby objects have no
1069
+ # prototype that a transform could change)
1070
+ # (jsonata-js: Object(matched) === matched, i.e. matched is a non-null object or a function)
1071
+ matched_type = Utils.typeof(matched)
1072
+ if !matched.equal?(NULL) && (matched_type == 'object' || matched_type == 'function') && !copy.key?(matched)
1073
+ raise Jsonata::Error.new('D1014', :position => expr[:position])
1074
+ end
1075
+ end
992
1076
  matches.each do |match|
993
1077
  # evaluate the update value for each match
994
1078
  update = evaluate(expr[:update], match, environment)
995
1079
  # update must be an object
996
1080
  unless update.nil?
997
- unless update.kind_of?(Hash)
998
- # throw type error
999
- raise Jsonata::Error.new('T2011', :position => expr[:update][:position], :value => update)
1081
+ if !update.kind_of?(Hash) || Utils.function?(update)
1082
+ raise Jsonata::Error.new('T2011',
1083
+ :position => expr[:update][:position],
1084
+ :value => Utils.function?(update) ? nil : update)
1000
1085
  end
1001
1086
 
1002
- # merge the update
1087
+ # merge the update. A property named __proto__ is set with defineProperty so that it
1088
+ # becomes an own data property rather than invoking the prototype setter (which would change
1089
+ # what the matched object inherits from); all other keys use plain assignment (fast path)
1090
+ # (Ruby specific: a Hash has no prototype setter, so plain assignment always sets an own entry)
1003
1091
  if match.kind_of?(Hash)
1004
1092
  Utils.keys(update).each do |prop|
1005
1093
  match[prop] = update[prop]
@@ -1102,9 +1190,9 @@ module Jsonata
1102
1190
  end
1103
1191
 
1104
1192
  # Apply procedure or function
1105
- # @param proc - Procedure
1106
- # @param args - Arguments
1107
- # @returns Result of procedure
1193
+ # @param proc [Object] Procedure
1194
+ # @param args [Array] Arguments
1195
+ # @return [Object] Result of procedure
1108
1196
  def apply(proc, args, input, environment)
1109
1197
  result = apply_inner(proc, args, input, environment)
1110
1198
  while Utils.lambda?(result) && result.thunk == true
@@ -1126,9 +1214,9 @@ module Jsonata
1126
1214
  end
1127
1215
 
1128
1216
  # Apply procedure or function
1129
- # @param proc - Procedure
1130
- # @param args - Arguments
1131
- # @returns Result of procedure
1217
+ # @param proc [Object] Procedure
1218
+ # @param args [Array] Arguments
1219
+ # @return [Object] Result of procedure
1132
1220
  def apply_inner(proc, args, input, environment)
1133
1221
  validated_args = args
1134
1222
  if Utils.truthy?(proc) && (proc.kind_of?(Lambda) || proc.kind_of?(NativeFunction))
@@ -1208,10 +1296,10 @@ module Jsonata
1208
1296
  end
1209
1297
 
1210
1298
  # Validate the arguments against the signature validator (if it exists)
1211
- # @param signature - validator function
1212
- # @param args - function arguments
1213
- # @param context - context value
1214
- # @returns validated arguments
1299
+ # @param signature [Lambda, NativeFunction, Proc] validator function
1300
+ # @param args [Array] function arguments
1301
+ # @param context [Object] context value
1302
+ # @return [Array] validated arguments
1215
1303
  def validate_arguments(signature, args, context)
1216
1304
  # nothing to validate
1217
1305
  return args if signature.nil?
@@ -1234,8 +1322,8 @@ module Jsonata
1234
1322
  end
1235
1323
 
1236
1324
  # Partially apply procedure
1237
- # @param proc - Procedure (a Lambda, or the AST of a lambda wrapping a native function)
1238
- # @returns Result of partially applied procedure
1325
+ # @param proc [Object] Procedure (a Lambda, or the AST of a lambda wrapping a native function)
1326
+ # @return [Lambda] Result of partially applied procedure
1239
1327
  def partial_apply_procedure(proc, args, environment)
1240
1328
  proc = Lambda.new(:arguments => proc[:arguments], :body => proc[:body]) if proc.kind_of?(Hash)
1241
1329
  # create a closure, bind the supplied parameters and return a function that takes the remaining (?) parameters
@@ -1258,8 +1346,8 @@ module Jsonata
1258
1346
  end
1259
1347
 
1260
1348
  # Partially apply native function
1261
- # @param native - Native function
1262
- # @returns Result of partially applying native function
1349
+ # @param native [Lambda, NativeFunction, Proc] Native function
1350
+ # @return [Lambda] Result of partially applying native function
1263
1351
  def partial_apply_native_function(native, args, environment)
1264
1352
  # create a lambda function that wraps and invokes the native function
1265
1353
  # get the list of declared arguments from the native function
@@ -1284,23 +1372,23 @@ module Jsonata
1284
1372
  end
1285
1373
 
1286
1374
  # Get native function arguments
1287
- # @param func - Function
1288
- # @returns Native function arguments
1375
+ # @param func [Lambda, NativeFunction, Proc] Function
1376
+ # @return [Object, Array] Native function arguments
1289
1377
  def get_native_function_arguments(func)
1290
1378
  Utils.parameter_names(func)
1291
1379
  end
1292
1380
 
1293
1381
  # Creates a function definition
1294
- # @param func - function implementation in Ruby
1295
- # @param signature - JSONata function signature definition
1296
- # @returns function definition
1382
+ # @param func [Lambda, NativeFunction, Proc] function implementation in Ruby
1383
+ # @param signature [String] JSONata function signature definition
1384
+ # @return [NativeFunction] function definition
1297
1385
  def define_function(func, signature = nil)
1298
1386
  NativeFunction.new(func, signature.nil? ? nil : Signature.new(signature))
1299
1387
  end
1300
1388
 
1301
1389
  # Create frame
1302
- # @param enclosing_environment - Enclosing environment
1303
- # @returns Created frame
1390
+ # @param enclosing_environment [Object] Enclosing environment
1391
+ # @return [Frame] Created frame
1304
1392
  def create_frame(enclosing_environment)
1305
1393
  Frame.new(enclosing_environment)
1306
1394
  end
@@ -1308,7 +1396,7 @@ module Jsonata
1308
1396
  # lookup a message template from the catalog and substitute the inserts.
1309
1397
  # Populates `err.message` with the substituted message. Leaves `err.message`
1310
1398
  # untouched if code lookup fails.
1311
- # @param err - error to populate
1399
+ # @param err [String] error to populate
1312
1400
  def populate_message(err)
1313
1401
  template = ERROR_CODES[err.code]
1314
1402
  return if template.nil?
@@ -1350,6 +1438,8 @@ module Jsonata
1350
1438
  'S0104' => 'The escape sequence \\u must be followed by 4 hex digits',
1351
1439
  'S0105' => 'Quoted property name must be terminated with a backquote (`)',
1352
1440
  'S0106' => 'Comment has no closing tag',
1441
+ 'S0107' => 'Template string must be terminated with {{value}}',
1442
+ 'S0108' => 'A } in template string text must be escaped as \\}',
1353
1443
  'S0201' => 'Syntax error: {{token}}',
1354
1444
  'S0202' => 'Expected {{value}}, got {{token}}',
1355
1445
  'S0203' => 'Expected {{value}} before end of expression',
@@ -1384,10 +1474,12 @@ module Jsonata
1384
1474
  'T1007' => 'Attempted to partially apply a non-function. Did you mean ${{{token}}}?',
1385
1475
  'T1008' => 'Attempted to partially apply a non-function',
1386
1476
  'D1009' => 'Multiple key definitions evaluate to same key: {{value}}',
1477
+ 'D1010' => 'Attempted to access the Javascript object prototype', # Javascript specific
1387
1478
  'T1010' => 'The matcher function argument passed to function {{token}} does not return the correct object structure',
1388
1479
  'D1011' => 'Stack overflow. Check for non-terminating recursive function. Consider rewriting as tail-recursive',
1389
1480
  'D1012' => 'Evaluation timeout after {{value}} milliseconds. Check for infinite loop',
1390
1481
  'D1013' => 'Object property names starting with _jsonata_ are reserved for internal use: {{value}}',
1482
+ 'D1014' => 'The location in a transform expression can only match objects in the copy that is being transformed',
1391
1483
  'T2001' => 'The left side of the {{token}} operator must evaluate to a number',
1392
1484
  'T2002' => 'The right side of the {{token}} operator must evaluate to a number',
1393
1485
  'T2003' => 'The left side of the range operator (..) must evaluate to an integer',
@@ -1403,6 +1495,7 @@ module Jsonata
1403
1495
  'T2013' => 'The transform expression clones the input object using the $clone() function. This has been overridden in the current scope by a non-function.',
1404
1496
  'D2014' => 'The size of the sequence allocated by the range operator (..) must not exceed 1e7. Attempted to allocate {{value}}.',
1405
1497
  'D2015' => 'The maximum sequence length of {{value}} was exceeded.',
1498
+ 'D2016' => 'The size of the string requested by the $pad function must not exceed 1e7. Attempted to allocate {{value}}.',
1406
1499
  'D3001' => 'Attempting to invoke string function on Infinity or NaN',
1407
1500
  'D3010' => 'Second argument of replace function cannot be an empty string',
1408
1501
  'D3011' => 'Fourth argument of replace function must evaluate to a positive number',
@@ -1443,7 +1536,8 @@ module Jsonata
1443
1536
  'D3138' => 'The $single() function expected exactly 1 matching result. Instead it matched more.',
1444
1537
  'D3139' => 'The $single() function expected exactly 1 matching result. Instead it matched 0.',
1445
1538
  'D3140' => 'Malformed URL passed to ${{{functionName}}}(): {{value}}',
1446
- 'D3141' => '{{{message}}}'
1539
+ 'D3141' => '{{{message}}}',
1540
+ 'D3142' => 'A width modifier in a date/time picture string cannot be greater than 100: {{value}}'
1447
1541
  }.freeze
1448
1542
 
1449
1543
  # A focus object for invoking functions that don't require one
@@ -1525,13 +1619,14 @@ module Jsonata
1525
1619
 
1526
1620
  # A compiled JSONata expression (jsonata-js: the object returned by `jsonata(expr, options)`)
1527
1621
  class Expression
1528
- # @param expr - JSONata expression
1529
- # @param options
1622
+ # @param expr [String] JSONata expression
1623
+ # @param options [Hash, nil] options
1530
1624
  # @option options [Boolean] :recover attempt to recover on parse error
1531
1625
  # @option options [Proc] :regex_engine callable(source, flags) returning an object that responds to `match(str, pos)`
1532
1626
  # @option options [Integer] :timeout evaluation timeout (milliseconds)
1533
1627
  # @option options [Integer] :stack max stack depth
1534
1628
  # @option options [Integer] :sequence max sequence length
1629
+ # @option options [Boolean] :inherited allow looking up the properties that objects inherit from their prototypes
1535
1630
  def initialize(expr, options = nil)
1536
1631
  @options = options
1537
1632
  begin
@@ -1544,19 +1639,16 @@ module Jsonata
1544
1639
  end
1545
1640
  @environment = Evaluator.create_frame(Evaluator::STATIC_FRAME)
1546
1641
 
1547
- @timestamp = current_time # will be overridden on each call to evalute()
1548
- @environment.bind('now', Evaluator.define_function(lambda do |picture, timezone|
1549
- Evaluator::FN.from_millis(millis(@timestamp), picture, timezone)
1550
- end, '<s?s?:s>'))
1551
- @environment.bind('millis', Evaluator.define_function(lambda do
1552
- millis(@timestamp)
1553
- end, '<:n>'))
1642
+ @environment.bind('now', Evaluator.define_function(Focus.instance_method(:expression_now), '<s?s?:s>'))
1643
+ @environment.bind('millis', Evaluator.define_function(Focus.instance_method(:expression_millis), '<:n>'))
1554
1644
  end
1555
1645
 
1556
1646
  # Evaluates the expression against the input, returning plain Ruby values
1557
1647
  # (JSON null and undefined are both returned as nil)
1558
- # @param input - Input data to evaluate against
1559
- # @param bindings - Hash of variable bindings
1648
+ # @param input [Object] Input data to evaluate against
1649
+ # @param bindings [Hash, nil] variable bindings
1650
+ # @return [Object] the result of the evaluation
1651
+ # @raise [Jsonata::Error] if the evaluation fails
1560
1652
  def evaluate(input = nil, bindings = nil, &)
1561
1653
  Utils.to_ruby(evaluate_raw(input.nil? ? nil : Utils.from_ruby(input), bindings, &))
1562
1654
  end
@@ -1564,6 +1656,10 @@ module Jsonata
1564
1656
  # Evaluates the expression, returning the internal representation of the result, in which JSON null is
1565
1657
  # represented by Jsonata::NULL and undefined by nil.
1566
1658
  # Nested nils in the input are treated as JSON null, a top-level nil input is treated as undefined.
1659
+ # @param input [Object] Input data to evaluate against
1660
+ # @param bindings [Hash, nil] variable bindings
1661
+ # @return [Object] the result of the evaluation
1662
+ # @raise [Jsonata::Error] if the evaluation fails
1567
1663
  def evaluate_raw(input = nil, bindings = nil, &callback)
1568
1664
  # throw if the expression compiled with syntax errors
1569
1665
  unless @errors.nil?
@@ -1584,8 +1680,7 @@ module Jsonata
1584
1680
 
1585
1681
  # capture the timestamp and put it in the execution environment
1586
1682
  # the $now() and $millis() functions will return this value - whenever it is called
1587
- @timestamp = current_time
1588
- exec_env.timestamp = @timestamp
1683
+ exec_env.timestamp = current_time
1589
1684
  exec_env.options = @options
1590
1685
 
1591
1686
  exec_env.base = exec_env
@@ -1632,12 +1727,18 @@ module Jsonata
1632
1727
  end
1633
1728
  end
1634
1729
 
1730
+ # Binds a value to a variable in the expression's environment
1731
+ # @param name [String, Symbol] the variable name (without the leading `$`)
1732
+ # @param value [Object] the value to bind
1635
1733
  def assign(name, value)
1636
1734
  @environment.bind(name.kind_of?(Symbol) && !name.to_s.start_with?('jsonata.') ? name.to_s : name,
1637
1735
  value.nil? ? nil : Utils.from_ruby(value))
1638
1736
  end
1639
1737
 
1640
1738
  # Registers a Ruby function, which may be given as a callable or a block
1739
+ # @param name [String, Symbol] the function name (without the leading `$`)
1740
+ # @param implementation [Proc, Method, nil] the function implementation, unless given as a block
1741
+ # @param signature [String, nil] JSONata function signature definition, e.g. `'<nn:n>'`
1641
1742
  # @example
1642
1743
  # expr.register_function('add', ->(a, b) { a + b }, '<nn:n>')
1643
1744
  # expr.register_function('greet', '<s:s>') { |name| "Hello, #{name}" }
@@ -1661,9 +1762,18 @@ module Jsonata
1661
1762
  def current_millis
1662
1763
  Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond)
1663
1764
  end
1765
+ end
1766
+
1767
+ # (Ruby specific) The implementations of $now() and $millis(). jsonata-js defines them as anonymous functions in
1768
+ # jsonata(), reading `this.environment.timestamp`; here they are Focus methods, so that they are invoked with the
1769
+ # Focus as `this`.
1770
+ class Focus
1771
+ def expression_now(picture, timezone)
1772
+ from_millis(expression_millis, picture, timezone)
1773
+ end
1664
1774
 
1665
- def millis(time)
1666
- (time.to_r * 1000).floor
1775
+ def expression_millis
1776
+ (environment.timestamp.to_r * 1000).floor
1667
1777
  end
1668
1778
  end
1669
1779
  end