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.
@@ -64,6 +64,9 @@ module Jsonata
64
64
  't' => "\t"
65
65
  }.freeze
66
66
 
67
+ # opening and closing delimiters of template strings
68
+ TEMPLATE_DELIMITERS = {"«" => "»", '<<' => '>>'}.freeze
69
+
67
70
  WHITESPACE = " \t\n\r\v"
68
71
 
69
72
  # The value of a regex literal token
@@ -79,6 +82,7 @@ module Jsonata
79
82
  @path = path
80
83
  @position = 0
81
84
  @length = path.length
85
+ @templates = []
82
86
  end
83
87
 
84
88
  def call(prefix = false)
@@ -86,6 +90,11 @@ module Jsonata
86
90
  end
87
91
 
88
92
  def next(prefix = false)
93
+ template = @templates.last
94
+ if template && template[:depth].zero? && char_at(@position) != '{'
95
+ # template text; a '{' falls through to be lexed as an operator, starting an embedded expression
96
+ return next_template_token(template)
97
+ end
89
98
  return nil if @position >= @length
90
99
 
91
100
  current_char = char_at(@position)
@@ -115,6 +124,18 @@ module Jsonata
115
124
  @position += 1
116
125
  return create('regex', scan_regex)
117
126
  end
127
+ # test for the start of a template string: '«', or '<<' in prefix position
128
+ # (in infix position '<' is the less-than operator, so "a"<<<b>> is "a" < <<b>>)
129
+ open = if current_char == '<'
130
+ prefix == true ? '' : (@path[@position, 2] || '')
131
+ else
132
+ current_char
133
+ end
134
+ if TEMPLATE_DELIMITERS.key?(open)
135
+ @position += open.length
136
+ @templates.push({:close => TEMPLATE_DELIMITERS[open], :depth => 0})
137
+ return create('template', open)
138
+ end
118
139
  # handle double-char operators
119
140
  two_chars = @path[@position, 2]
120
141
  if %w[.. := != >= <= ** ~> ?: ??].include?(two_chars)
@@ -124,6 +145,15 @@ module Jsonata
124
145
  # test for single char operators
125
146
  if OPERATORS.key?(current_char)
126
147
  @position += 1
148
+ if template
149
+ # track braces inside an embedded expression; the '}' that brings the depth
150
+ # back to zero closes the expression and resumes the template text
151
+ if current_char == '{'
152
+ template[:depth] += 1
153
+ elsif current_char == '}'
154
+ template[:depth] -= 1
155
+ end
156
+ end
127
157
  return create('operator', current_char)
128
158
  end
129
159
  # test for string literals
@@ -136,29 +166,7 @@ module Jsonata
136
166
  current_char = char_at(@position)
137
167
  if current_char == '\\' # escape sequence
138
168
  @position += 1
139
- current_char = char_at(@position)
140
- if ESCAPES.key?(current_char)
141
- qstr << ESCAPES[current_char]
142
- elsif current_char == 'u'
143
- # \u should be followed by 4 hex digits
144
- octets = @path[@position + 1, 4] || ''
145
- if /\A[0-9a-fA-F]+\z/.match?(octets)
146
- codepoint = octets.to_i(16)
147
- @position += 4
148
- # Ruby strings cannot hold UTF-16 surrogate pairs, so combine them here
149
- low = @path[@position + 1, 6]
150
- if (0xD800..0xDBFF).cover?(codepoint) && low&.match?(/\A\\u[dD][c-fC-F][0-9a-fA-F]{2}\z/)
151
- codepoint = 0x10000 + ((codepoint - 0xD800) << 10) + (low[2..].to_i(16) - 0xDC00)
152
- @position += 6
153
- end
154
- qstr << Utils.from_char_code(codepoint)
155
- else
156
- raise Jsonata::Error.new('S0104', :position => @position)
157
- end
158
- else
159
- # illegal escape sequence
160
- raise Jsonata::Error.new('S0103', :position => @position, :token => current_char)
161
- end
169
+ qstr << scan_escape
162
170
  elsif current_char == quote_type
163
171
  @position += 1
164
172
  return create('string', qstr)
@@ -285,6 +293,79 @@ module Jsonata
285
293
  end
286
294
  raise Jsonata::Error.new('S0302', :position => @position)
287
295
  end
296
+
297
+ # decode the escape sequence whose '\' has just been scanned; position is on the escaped character.
298
+ # 'extra' lists additional characters that may be escaped as themselves
299
+ def scan_escape(extra = nil)
300
+ current_char = char_at(@position)
301
+ return ESCAPES[current_char] if ESCAPES.key?(current_char)
302
+ return current_char if current_char != '' && extra&.include?(current_char)
303
+
304
+ if current_char == 'u'
305
+ # \u should be followed by 4 hex digits
306
+ octets = @path[@position + 1, 4] || ''
307
+ if /\A[0-9a-fA-F]{4}\z/.match?(octets)
308
+ @position += 4
309
+ codepoint = octets.to_i(16)
310
+ # Ruby strings cannot hold UTF-16 surrogate pairs, so combine them here (Ruby specific)
311
+ low = @path[@position + 1, 6]
312
+ if (0xD800..0xDBFF).cover?(codepoint) && low&.match?(/\A\\u[dD][c-fC-F][0-9a-fA-F]{2}\z/)
313
+ codepoint = 0x10000 + ((codepoint - 0xD800) << 10) + (low[2..].to_i(16) - 0xDC00)
314
+ @position += 6
315
+ end
316
+ return Utils.from_char_code(codepoint)
317
+ end
318
+ raise Jsonata::Error.new('S0104', :position => @position)
319
+ end
320
+ # illegal escape sequence
321
+ raise Jsonata::Error.new('S0103', :position => @position, :token => current_char)
322
+ end
323
+
324
+ # Template strings «...» and <<...>> are tokenized as:
325
+ # (template) [ (template-text) | '{' <tokens> '}' ]* (template-end)
326
+ # The tokenizer keeps a stack with one entry per open template (they can nest inside {}).
327
+ # Each entry counts the unmatched '{' in the current embedded expression; when it is
328
+ # zero the tokenizer is scanning literal text, otherwise it is scanning JSONata tokens.
329
+ # The count only changes where '{' and '}' are lexed as operators (see below), and the
330
+ # '{' that starts an embedded expression is lexed that way too, taking the count to one.
331
+ # Keeping this state here means every caller of the lexer (including remainingTokens)
332
+ # gets the right tokens without having to know about templates.
333
+ # Reaching the end of input inside template text is not an error here: the lexer returns
334
+ # null like it does at the end of any expression, and the parser reports the unterminated
335
+ # template (S0107), so that it can be recovered from in recover mode.
336
+ TEMPLATE_ESCAPES = "{}<>«»"
337
+ private_constant :TEMPLATE_ESCAPES
338
+
339
+ def template_close?(template)
340
+ # the first '>>' closes a <<...>> template, so '<<a>>>b' is '<<a>>' followed by '>'
341
+ @path[@position, template[:close].length] == template[:close]
342
+ end
343
+
344
+ def next_template_token(template)
345
+ return nil if @position >= @length
346
+
347
+ if template_close?(template)
348
+ @position += template[:close].length
349
+ @templates.pop
350
+ return create('template-end', template[:close])
351
+ end
352
+ # literal text up to the next unescaped '{' or the closing delimiter
353
+ text = +''
354
+ while @position < @length && char_at(@position) != '{' && !template_close?(template)
355
+ current_char = char_at(@position)
356
+ if current_char == '\\'
357
+ @position += 1
358
+ text << scan_escape(TEMPLATE_ESCAPES)
359
+ elsif current_char == '}'
360
+ # a literal '}' must be escaped, so that a stray brace is reported rather than kept as text
361
+ raise Jsonata::Error.new('S0108', :position => @position + 1, :token => current_char)
362
+ else
363
+ text << current_char
364
+ end
365
+ @position += 1
366
+ end
367
+ create('template-text', text)
368
+ end
288
369
  end
289
370
 
290
371
  # An entry in the symbol table
@@ -429,6 +510,8 @@ module Jsonata
429
510
  when 'regex'
430
511
  type = 'regex'
431
512
  sym = @symbol_table['(regex)']
513
+ when 'template', 'template-text', 'template-end'
514
+ sym = @symbol_table["(#{type})"]
432
515
  else
433
516
  return handle_error(Jsonata::Error.new('S0205', :position => next_token[:position], :token => value))
434
517
  end
@@ -438,10 +521,14 @@ module Jsonata
438
521
  @node
439
522
  end
440
523
 
524
+ # prefix operators whose nud parses an operand, so the token after them is in prefix position
525
+ STARTS_OPERAND = {'-' => true, '(' => true, '[' => true, '{' => true, '|' => true}.freeze
526
+ private_constant :STARTS_OPERAND
527
+
441
528
  # Pratt's algorithm
442
529
  def expression(rbp)
443
530
  t = @node
444
- advance(nil, true)
531
+ advance(nil, !(t[:type] == 'operator' && STARTS_OPERAND[t[:value]]))
445
532
  left = symbol_of(t).nud.call(t)
446
533
  while rbp < node_lbp(@node)
447
534
  t = @node
@@ -514,6 +601,8 @@ module Jsonata
514
601
  symbol(']')
515
602
  symbol('}')
516
603
  symbol('..') # range operator
604
+ symbol('(template-text)') # only valid inside a template string
605
+ symbol('(template-end)')
517
606
  infix('.') # map operator
518
607
  infix('+') # numeric addition
519
608
  infix('-') # numeric subtraction
@@ -550,6 +639,41 @@ module Jsonata
550
639
  this
551
640
  end
552
641
 
642
+ # template string: «text {expr} text» or <<text {expr} text>>
643
+ # produces a 'template' node whose parts are, in order, literal text (plain strings) and
644
+ # embedded expressions ({expression, position}, where position is that of the opening '{')
645
+ prefix('(template)') do |this|
646
+ error_count = @errors.length
647
+ this[:type] = 'template'
648
+ this[:parts] = []
649
+ # (jsonata-js: for (;;) with return statements; here each exit breaks out of the loop and returns this)
650
+ loop do
651
+ if node_id(@node) == '(template-text)'
652
+ this[:parts].push(@node[:value])
653
+ advance
654
+ elsif node_id(@node) == '{'
655
+ position = @node[:position]
656
+ advance
657
+ if node_id(@node) != '}' # empty {} contributes nothing
658
+ this[:parts].push({:expression => expression(0), :position => position})
659
+ end
660
+ advance('}')
661
+ elsif node_id(@node) == '(template-end)'
662
+ advance(nil, true)
663
+ break
664
+ elsif node_id(@node) == '(end)' && @errors.length == error_count
665
+ # the input ended inside the template text
666
+ handle_error(Jsonata::Error.new('S0107', :position => @node[:position], :value => TEMPLATE_DELIMITERS[this[:value]]))
667
+ break
668
+ else
669
+ # recover mode only: an error inside {} has already been recorded and the
670
+ # remaining tokens consumed, so return what has been parsed so far
671
+ break
672
+ end
673
+ end
674
+ this
675
+ end
676
+
553
677
  infixr('(error)', 10) do |this, left|
554
678
  this[:lhs] = left
555
679
 
@@ -916,6 +1040,13 @@ module Jsonata
916
1040
  end
917
1041
  end
918
1042
 
1043
+ # add a processed expression to a block (expressions in parentheses)
1044
+ def block_expression(block, part)
1045
+ push_ancestry(block, part)
1046
+ block[:consarray] = true if part[:consarray] || (part[:type] == 'path' && part[:steps][0][:consarray])
1047
+ part
1048
+ end
1049
+
919
1050
  def resolve_ancestry(path)
920
1051
  index = path[:steps].length - 1
921
1052
  laststep = path[:steps][index]
@@ -959,11 +1090,20 @@ module Jsonata
959
1090
  when '.'
960
1091
  lstep = process_ast(expr[:lhs])
961
1092
 
962
- result = if lstep[:type] == 'path'
963
- lstep
964
- else
965
- {:type => 'path', :steps => [lstep]}
966
- end
1093
+ if lstep[:type] == 'path' && lstep.key?(:group)
1094
+ # a reduce terminates its path, so the steps that follow it start a new path, as if
1095
+ # the grouped path was in parentheses - i.e. a{k:v}.x is the same as (a{k:v}).x
1096
+ block = {:type => 'block', :position => expr[:lhs][:position]}
1097
+ block[:expressions] = [block_expression(block, lstep)]
1098
+ result = {:type => 'path', :steps => [block]}
1099
+ # but unlike in parentheses, the parent references that the grouped path can't
1100
+ # resolve itself are passed on to be resolved by the enclosing expression
1101
+ push_ancestry(result, block)
1102
+ elsif lstep[:type] == 'path'
1103
+ result = lstep
1104
+ else
1105
+ result = {:type => 'path', :steps => [lstep]}
1106
+ end
967
1107
  result[:seeking_parent] = [lstep[:slot]] if lstep[:type] == 'parent'
968
1108
  rest = process_ast(expr[:rhs])
969
1109
  if rest[:type] == 'path'
@@ -1140,6 +1280,15 @@ module Jsonata
1140
1280
  }
1141
1281
  body = process_ast(expr[:body])
1142
1282
  result[:body] = tail_call_optimize(body)
1283
+ when 'template'
1284
+ result = {:type => expr[:type], :value => expr[:value], :position => expr[:position]}
1285
+ result[:parts] = expr[:parts].map do |part|
1286
+ next part if part.kind_of?(String) # literal text
1287
+
1288
+ part_ast = process_ast(part[:expression])
1289
+ push_ancestry(result, part_ast)
1290
+ {:expression => part_ast, :position => part[:position]}
1291
+ end
1143
1292
  when 'condition'
1144
1293
  result = {:type => expr[:type], :position => expr[:position]}
1145
1294
  result[:condition] = process_ast(expr[:condition])
@@ -1159,10 +1308,7 @@ module Jsonata
1159
1308
  result = {:type => expr[:type], :position => expr[:position]}
1160
1309
  # array of expressions - process each one
1161
1310
  result[:expressions] = expr[:expressions].map do |item|
1162
- part = process_ast(item)
1163
- push_ancestry(result, part)
1164
- result[:consarray] = true if part[:consarray] || (part[:type] == 'path' && part[:steps][0][:consarray])
1165
- part
1311
+ block_expression(result, process_ast(item))
1166
1312
  end
1167
1313
  # TODO scan the array of expressions to see if any of them assign variables
1168
1314
  # if so, need to mark the block as one that needs to create a new frame
@@ -24,7 +24,7 @@ module Jsonata
24
24
  attr_reader :definition
25
25
 
26
26
  # Parses a function signature definition and returns a validation function
27
- # @param signature - the signature between the <angle brackets>
27
+ # @param signature [String] the signature between the <angle brackets>
28
28
  def initialize(signature)
29
29
  @definition = signature
30
30
  # create a Regex that represents this signature and return a function that when invoked,
data/lib/jsonata/utils.rb CHANGED
@@ -42,8 +42,8 @@ module Jsonata
42
42
  module_function
43
43
 
44
44
  # Check if value is a finite number
45
- # @param n - number to evaluate
46
- # @returns true if n is a finite number
45
+ # @param n [Float] number to evaluate
46
+ # @return [Boolean] true if n is a finite number
47
47
  def numeric?(n)
48
48
  is_num = false
49
49
  if n.kind_of?(Numeric)
@@ -78,7 +78,7 @@ module Jsonata
78
78
  value.kind_of?(JArray) && value.sequence == true
79
79
  end
80
80
 
81
- # @returns true if it is a function (lambda or built-in)
81
+ # @return [Boolean] true if it is a function (lambda or built-in)
82
82
  def function?(arg)
83
83
  arg.kind_of?(Lambda) || arg.kind_of?(NativeFunction) || callable?(arg)
84
84
  end
@@ -151,7 +151,7 @@ module Jsonata
151
151
  end
152
152
 
153
153
  # Compares two values for equality
154
- # @returns true if they are deep equal
154
+ # @return [Boolean] true if they are deep equal
155
155
  def deep_equal?(lhs, rhs)
156
156
  return true if lhs.equal?(rhs)
157
157
 
@@ -202,7 +202,7 @@ module Jsonata
202
202
  str.chars
203
203
  end
204
204
 
205
- # @returns the keys (property names) of the object
205
+ # @return [Array] the keys (property names) of the object
206
206
  def keys(arg)
207
207
  case arg
208
208
  when Hash then arg.keys
@@ -211,6 +211,78 @@ module Jsonata
211
211
  end
212
212
  end
213
213
 
214
+ # Returns a string of zeros
215
+ # @param count [Numeric] the number of zeros
216
+ # @return [String] the zeros, or an empty string if count is not positive
217
+ def zeros(count)
218
+ count.positive? ? '0' * count : ''
219
+ end
220
+
221
+ # Returns the decimal digits of a finite number. As XPath F&O 3.1 section 4.7.5 requires, these are the digits
222
+ # of the shortest decimal that converts back to the same number (which Number.prototype.toString produces),
223
+ # rather than the digits of its exact binary value (which toFixed uses)
224
+ # @param value [Numeric] the number; its sign is ignored
225
+ # @return [Hash] the digits without leading zeros, and the power of ten of the
226
+ # last one
227
+ def decimal_digits(value)
228
+ parts = number_to_s(value.abs).split('e')
229
+ mantissa = parts[0].split('.')
230
+ fraction = mantissa[1] || ''
231
+ digits = (mantissa[0] + fraction).sub(/\A0+/, '')
232
+ if digits == ''
233
+ return {:digits => '0', :exponent => 0}
234
+ end
235
+
236
+ {:digits => digits, :exponent => (parts[1] ? Integer(parts[1], 10) : 0) - fraction.length}
237
+ end
238
+
239
+ # Rounds decimal digits half-to-even to the given number of decimal places
240
+ # @param number [Hash] the digits, and the power of ten of the last one
241
+ # @param dp [Numeric] the number of decimal places
242
+ # @return [Hash] the rounded digits
243
+ def round_decimal_digits(number, dp)
244
+ drop_count = -number[:exponent] - dp
245
+ if drop_count <= 0
246
+ return number
247
+ end
248
+
249
+ digits = zeros(drop_count - number[:digits].length) + number[:digits]
250
+ kept = digits[0, digits.length - drop_count]
251
+ dropped = digits[(digits.length - drop_count)..]
252
+ last_kept = kept.length.positive? ? Integer(kept[-1], 10) : 0
253
+ if dropped[0] > '5' || (dropped[0] == '5' && (dropped[1..].match?(/[1-9]/) || last_kept.odd?))
254
+ # add one to the kept digits
255
+ ii = kept.length - 1
256
+ ii -= 1 while ii >= 0 && kept[ii] == '9'
257
+ kept = (ii.negative? ? '1' : kept[0, ii] + (Integer(kept[ii], 10) + 1).to_s) + zeros(kept.length - ii - 1)
258
+ end
259
+ # (jsonata-js: kept.replace(/^0+/, '') || '0')
260
+ kept = kept.sub(/\A0+/, '')
261
+ {:digits => kept.empty? ? '0' : kept, :exponent => -dp}
262
+ end
263
+
264
+ # Writes decimal digits out in full (never exponent notation), with exactly the given number of decimal places.
265
+ # The digits must already be rounded to that number of decimal places
266
+ # @param number [Hash] the digits, and the power of ten of the last one
267
+ # @param dp [Numeric] the number of decimal places
268
+ # @return [String] the decimal string
269
+ def decimal_digits_to_string(number, dp)
270
+ digits = number[:digits]
271
+ if number[:exponent] >= 0
272
+ integer_part = digits + zeros(number[:exponent])
273
+ fractional_part = ''
274
+ else
275
+ digits = zeros(-number[:exponent] - digits.length) + digits
276
+ integer_part = digits[0, digits.length + number[:exponent]]
277
+ fractional_part = digits[(digits.length + number[:exponent])..]
278
+ end
279
+ # (jsonata-js: integerPart.replace(/^0+/, '') || '0')
280
+ integer_part = integer_part.sub(/\A0+/, '')
281
+ integer_part = '0' if integer_part.empty?
282
+ fractional_part += zeros(dp - fractional_part.length)
283
+ dp.positive? ? "#{integer_part}.#{fractional_part}" : integer_part
284
+ end
285
+
214
286
  ##################################################################
215
287
  # JavaScript emulation helpers (not part of utils.js)
216
288
  ##################################################################
@@ -386,7 +458,7 @@ module Jsonata
386
458
  URI_RESERVED = ';/?:@&=+$,#'
387
459
 
388
460
  # Equivalent of encodeURI / encodeURIComponent
389
- # @param unescaped - the set of characters that are not escaped
461
+ # @param unescaped [String] the set of characters that are not escaped
390
462
  def encode_uri(str, unescaped)
391
463
  raise URIError unless str.valid_encoding?
392
464
 
@@ -400,7 +472,7 @@ module Jsonata
400
472
  end
401
473
 
402
474
  # Equivalent of decodeURI / decodeURIComponent
403
- # @param reserved - the set of characters whose escape sequences are not decoded
475
+ # @param reserved [String] the set of characters whose escape sequences are not decoded
404
476
  def decode_uri(str, reserved)
405
477
  result = +''
406
478
  k = 0
@@ -454,8 +526,8 @@ module Jsonata
454
526
  end
455
527
 
456
528
  # Translates a JavaScript regular expression into a Ruby Regexp
457
- # @param source - the JavaScript regex pattern
458
- # @param flags - the JavaScript regex flags (only 'i' and 'm' are significant)
529
+ # @param source [String] the JavaScript regex pattern
530
+ # @param flags [String] the JavaScript regex flags (only 'i' and 'm' are significant)
459
531
  def js_regexp(source, flags = '')
460
532
  multiline = flags.include?('m')
461
533
  out = +''
@@ -524,8 +596,8 @@ module Jsonata
524
596
  end
525
597
 
526
598
  # JSON.stringify with JavaScript semantics
527
- # @param replacer - optional proc(value) returning the replaced value
528
- # @param space - number of spaces to indent
599
+ # @param replacer [Proc, nil] optional proc(value) returning the replaced value
600
+ # @param space [Integer] number of spaces to indent
529
601
  def json_stringify(value, replacer = nil, space = 0)
530
602
  value = replacer.call(value) if replacer
531
603
  stringify_value(value, replacer, space, '')
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Jsonata
4
- VERSION = '2.2.2.1'
4
+ VERSION = '2.3.0'
5
5
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: jsonata
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.2.2.1
4
+ version: 2.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jason Frey
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-10-28 00:00:00.000000000 Z
11
+ date: 2026-11-29 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: manageiq-style
@@ -78,13 +78,13 @@ files:
78
78
  - lib/jsonata/signature.rb
79
79
  - lib/jsonata/utils.rb
80
80
  - lib/jsonata/version.rb
81
- homepage: https://github.com/Fryguy/jsonata-rb
81
+ homepage: https://github.com/yourusername/jsonata-rb
82
82
  licenses:
83
83
  - MIT
84
84
  metadata:
85
- homepage_uri: https://github.com/Fryguy/jsonata-rb
86
- source_code_uri: https://github.com/Fryguy/jsonata-rb
87
- changelog_uri: https://github.com/Fryguy/jsonata-rb/blob/main/CHANGELOG.md
85
+ homepage_uri: https://github.com/yourusername/jsonata-rb
86
+ source_code_uri: https://github.com/yourusername/jsonata-rb
87
+ changelog_uri: https://github.com/yourusername/jsonata-rb/blob/main/CHANGELOG.md
88
88
  rubygems_mfa_required: 'true'
89
89
  post_install_message:
90
90
  rdoc_options: []