rbjq 1.0.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.
@@ -0,0 +1,1357 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'date'
4
+ require 'time'
5
+ require_relative 'bessel'
6
+
7
+ module Rbjq
8
+ # Builtin functions implemented in Ruby.
9
+ module Builtins
10
+ NATIVES = {} # rubocop:disable Style/MutableConstant -- filled by fn/special below
11
+ INVALID = Interpreter::INVALID
12
+
13
+ module_function
14
+
15
+ # Special forms: receive closures (AST nodes) and full control.
16
+ def special(name, arity, &impl)
17
+ NATIVES["#{name}/#{arity}"] = impl
18
+ end
19
+
20
+ # Plain value functions: arguments are evaluated (cartesian product).
21
+ def fn(name, arity, &impl)
22
+ NATIVES["#{name}/#{arity}"] =
23
+ if arity.zero?
24
+ lambda do |_interp, input, path, _args, _env, &blk|
25
+ blk.call(impl.call(input), path && INVALID)
26
+ end
27
+ else
28
+ lambda do |interp, input, path, args, env, &blk|
29
+ interp.each_args(args, input, env) do |a|
30
+ blk.call(impl.call(input, *a), path && INVALID)
31
+ end
32
+ end
33
+ end
34
+ end
35
+
36
+ def err(msg)
37
+ raise JQError, msg
38
+ end
39
+
40
+ def num(v, _name = nil)
41
+ return v if Value.number?(v)
42
+
43
+ err("#{Value.desc(v)} number required")
44
+ end
45
+
46
+ # --------------------------------------------------------------- core
47
+
48
+ special('empty', 0) { |*| nil }
49
+
50
+ special('error', 0) { |_i, input, *| raise JQError, input }
51
+
52
+ special('error', 1) do |interp, input, _path, args, env|
53
+ interp.each_args(args, input, env) { |(msg)| raise JQError, msg } # rubocop:disable Lint/UnreachableLoop
54
+ end
55
+
56
+ special('not', 0) { |_i, input, path, _a, _e, &blk| blk.call(!Value.truthy?(input), path && INVALID) }
57
+
58
+ special('path', 1) do |interp, input, path, args, env, &blk|
59
+ interp.eval_node(args[0], input, [], env) do |v, p|
60
+ interp.check_path!(v, p)
61
+ blk.call(p, path && INVALID)
62
+ end
63
+ end
64
+
65
+ special('getpath', 1) do |interp, input, path, args, env, &blk|
66
+ interp.each_args(args, input, env) do |(p)|
67
+ v = begin
68
+ Ops.getpath(input, p)
69
+ rescue JQError
70
+ raise unless p.is_a?(Array)
71
+
72
+ raise
73
+ end
74
+ if path
75
+ interp.check_path!(input, path)
76
+ blk.call(v, path + p)
77
+ else
78
+ blk.call(v, nil)
79
+ end
80
+ end
81
+ end
82
+
83
+ fn('setpath', 2) { |input, p, v| Ops.setpath(input, p, v) }
84
+ fn('delpaths', 1) { |input, ps| Ops.delpaths(input, ps) }
85
+
86
+ special('select', 1) do |interp, input, path, args, env, &blk|
87
+ interp.eval_node(args[0], input, nil, env) do |c|
88
+ blk.call(input, path) if Value.truthy?(c)
89
+ end
90
+ end
91
+
92
+ special('recurse', 0) do |_interp, input, path, _args, _env, &blk|
93
+ stack = [[input, path]]
94
+ until stack.empty?
95
+ v, p = stack.pop
96
+ blk.call(v, p)
97
+ case v
98
+ when Array
99
+ (v.length - 1).downto(0) { |i| stack.push([v[i], p && (p + [i])]) }
100
+ when Hash
101
+ v.keys.reverse_each { |k| stack.push([v[k], p && (p + [k])]) }
102
+ end
103
+ end
104
+ end
105
+
106
+ special('recurse', 1) do |interp, input, path, args, env, &blk|
107
+ f = args[0]
108
+ stack = [[input, path]]
109
+ until stack.empty?
110
+ v, p = stack.pop
111
+ blk.call(v, p)
112
+ children = []
113
+ interp.eval_node(f, v, p, env) { |cv, cp| children << [cv, cp] }
114
+ children.reverse_each { |c| stack.push(c) }
115
+ end
116
+ end
117
+
118
+ # Same behavior as jq 1.7.1, whose manual tests expect
119
+ # `[repeat(.*2, error)?]` on 1 to give [2]: the outputs of f applied to
120
+ # the input are produced over and over.
121
+ special('repeat', 1) do |interp, input, path, args, env, &blk|
122
+ loop { interp.eval_node(args[0], input, path, env, &blk) }
123
+ end
124
+
125
+ special('nth', 2) do |interp, input, path, args, env, &blk|
126
+ interp.eval_node(args[0], input, nil, env) do |n|
127
+ num(n)
128
+ err("nth doesn't support negative indices") if n.negative?
129
+
130
+ count = 0
131
+ tag = Object.new
132
+ catch(tag) do
133
+ interp.eval_node(args[1], input, path, env) do |v, p|
134
+ if count >= n
135
+ blk.call(v, p)
136
+ throw tag
137
+ end
138
+ count += 1
139
+ end
140
+ end
141
+ end
142
+ end
143
+
144
+ fn('bsearch', 1) do |v, target|
145
+ err("#{Value.desc(v)} cannot be searched from") unless v.is_a?(Array)
146
+ lo = 0
147
+ hi = v.length - 1
148
+ found = nil
149
+ while lo <= hi
150
+ mid = (lo + hi) / 2
151
+ c = Value.compare(v[mid], target)
152
+ if c.zero?
153
+ found = mid
154
+ break
155
+ elsif c.negative?
156
+ lo = mid + 1
157
+ else
158
+ hi = mid - 1
159
+ end
160
+ end
161
+ found || (-1 - lo)
162
+ end
163
+
164
+ special('while', 2) do |interp, input, path, args, env, &blk|
165
+ cond, update = args
166
+ stack = [[input, path]]
167
+ until stack.empty?
168
+ v, p = stack.pop
169
+ items = []
170
+ interp.eval_node(cond, v, nil, env) do |c|
171
+ next unless Value.truthy?(c)
172
+
173
+ items << [:emit, v, p]
174
+ interp.eval_node(update, v, p, env) { |uv, up| items << [:eval, uv, up] }
175
+ end
176
+ # process in order: emit first, then recurse into each update result
177
+ items.reverse_each do |kind, wv, wp|
178
+ if kind == :emit
179
+ stack.push([:emit, wv, wp])
180
+ else
181
+ stack.push([wv, wp])
182
+ end
183
+ end
184
+ while !stack.empty? && stack.last[0] == :emit
185
+ _, ev, ep = stack.pop
186
+ blk.call(ev, ep)
187
+ end
188
+ end
189
+ end
190
+
191
+ special('until', 2) do |interp, input, path, args, env, &blk|
192
+ cond, update = args
193
+ stack = [[input, path]]
194
+ until stack.empty?
195
+ top = stack.pop
196
+ if top[0] == :emit
197
+ blk.call(top[1], top[2])
198
+ next
199
+ end
200
+ v, p = top
201
+ items = []
202
+ interp.eval_node(cond, v, nil, env) do |c|
203
+ if Value.truthy?(c)
204
+ items << [:emit, v, p]
205
+ else
206
+ interp.eval_node(update, v, p, env) { |uv, up| items << [uv, up] }
207
+ end
208
+ end
209
+ items.reverse_each { |item| stack.push(item) }
210
+ end
211
+ end
212
+
213
+ special('range', 1) do |interp, input, path, args, env, &blk|
214
+ inv = path && INVALID
215
+ interp.eval_node(args[0], input, nil, env) do |n|
216
+ err('Range bounds must be numeric') unless Value.number?(n)
217
+ i = 0
218
+ while i < n
219
+ blk.call(i, inv)
220
+ i += 1
221
+ end
222
+ end
223
+ end
224
+
225
+ special('range', 2) do |interp, input, path, args, env, &blk|
226
+ inv = path && INVALID
227
+ interp.eval_node(args[0], input, nil, env) do |from|
228
+ interp.eval_node(args[1], input, nil, env) do |upto|
229
+ err('Range bounds must be numeric') unless Value.number?(from) && Value.number?(upto)
230
+ i = from
231
+ while i < upto
232
+ blk.call(i, inv)
233
+ i = Value.normalize_number(i + 1)
234
+ end
235
+ end
236
+ end
237
+ end
238
+
239
+ special('range', 3) do |interp, input, path, args, env, &blk|
240
+ inv = path && INVALID
241
+ interp.eval_node(args[0], input, nil, env) do |from|
242
+ interp.eval_node(args[1], input, nil, env) do |upto|
243
+ interp.eval_node(args[2], input, nil, env) do |by|
244
+ err('Range bounds must be numeric') unless [from, upto, by].all? { |x| Value.number?(x) }
245
+ i = from
246
+ if by.positive?
247
+ while i < upto
248
+ blk.call(i, inv)
249
+ i = Value.normalize_number(i + by)
250
+ end
251
+ elsif by.negative?
252
+ while i > upto
253
+ blk.call(i, inv)
254
+ i = Value.normalize_number(i + by)
255
+ end
256
+ end
257
+ end
258
+ end
259
+ end
260
+ end
261
+
262
+ special('limit', 2) do |interp, input, path, args, env, &blk|
263
+ interp.eval_node(args[0], input, nil, env) do |n|
264
+ num(n)
265
+ if n.positive?
266
+ count = 0
267
+ tag = Object.new
268
+ catch(tag) do
269
+ interp.eval_node(args[1], input, path, env) do |v, p|
270
+ count += 1
271
+ blk.call(v, p)
272
+ throw tag if count >= n
273
+ end
274
+ end
275
+ elsif n.negative?
276
+ err("limit doesn't support negative count")
277
+ end
278
+ end
279
+ end
280
+
281
+ special('skip', 2) do |interp, input, path, args, env, &blk|
282
+ interp.eval_node(args[0], input, nil, env) do |n|
283
+ num(n)
284
+ err("skip doesn't support negative count") if n.negative?
285
+
286
+ count = 0
287
+ interp.eval_node(args[1], input, path, env) do |v, p|
288
+ blk.call(v, p) if count >= n
289
+ count += 1
290
+ end
291
+ end
292
+ end
293
+
294
+ special('last', 1) do |interp, input, path, args, env, &blk|
295
+ got = nil
296
+ interp.eval_node(args[0], input, nil, env) { |v| got = [v] }
297
+ blk.call(got[0], path && INVALID) if got
298
+ end
299
+
300
+ special('first', 1) do |interp, input, path, args, env, &blk|
301
+ tag = Object.new
302
+ got = nil
303
+ catch(tag) do
304
+ interp.eval_node(args[0], input, path, env) do |v, p|
305
+ got = [v, p]
306
+ throw tag
307
+ end
308
+ end
309
+ blk.call(*got) if got
310
+ end
311
+
312
+ special('isempty', 1) do |interp, input, path, args, env, &blk|
313
+ found, = interp.first_value(args[0], input, env)
314
+ blk.call(!found, path && INVALID)
315
+ end
316
+
317
+ special('input', 0) do |interp, _input, path, _args, _env, &blk|
318
+ blk.call(interp.next_input, path && INVALID)
319
+ end
320
+
321
+ special('inputs', 0) do |interp, _input, path, _args, _env, &blk|
322
+ provider = interp.input_provider
323
+ next unless provider
324
+
325
+ loop do
326
+ v = provider.call
327
+ break if v.equal?(JSONParser::EOF)
328
+
329
+ blk.call(v, path && INVALID)
330
+ end
331
+ end
332
+
333
+ special('debug', 0) do |interp, input, path, _args, _env, &blk|
334
+ (interp.options[:stderr] || $stderr).write("#{Encoder.dump(['DEBUG:', input])}\n")
335
+ blk.call(input, path)
336
+ end
337
+
338
+ special('stderr', 0) do |interp, input, path, _args, _env, &blk|
339
+ (interp.options[:stderr] || $stderr).write(Encoder.dump(input))
340
+ blk.call(input, path)
341
+ end
342
+
343
+ special('input_filename', 0) do |interp, _input, path, _args, _env, &blk|
344
+ blk.call(interp.current_filename, path && INVALID)
345
+ end
346
+
347
+ special('input_line_number', 0) do |interp, _input, path, _args, _env, &blk|
348
+ blk.call(interp.options[:line_proc]&.call || 0, path && INVALID)
349
+ end
350
+
351
+ special('halt', 0) { |*| raise HaltError.new(nil, 0, false) }
352
+
353
+ special('halt_error', 1) do |interp, input, _path, args, env|
354
+ interp.each_args(args, input, env) do |(code)| # rubocop:disable Lint/UnreachableLoop
355
+ err('halt_error/1: number required') unless Value.number?(code)
356
+ raise HaltError.new(input, code.to_i, true)
357
+ end
358
+ end
359
+
360
+ special('builtins', 0) do |_interp, _input, path, _args, _env, &blk|
361
+ names = (NATIVES.keys + PRELUDE_KEYS).reject { |k| k.start_with?('_') }.uniq
362
+ blk.call(names, path && INVALID)
363
+ end
364
+
365
+ fn('now', 0) { |_| Time.now.to_f }
366
+
367
+ special('get_jq_origin', 0) do |interp, _input, path, _args, _env, &blk|
368
+ blk.call(interp.options.fetch(:jq_origin) { File.expand_path('../../exe', __dir__) }, path && INVALID)
369
+ end
370
+
371
+ special('get_prog_origin', 0) do |interp, _input, path, _args, _env, &blk|
372
+ blk.call(interp.options.fetch(:prog_origin) { Dir.pwd }, path && INVALID)
373
+ end
374
+
375
+ def ltrimstr(v, pre)
376
+ err('startswith() requires string inputs') unless v.is_a?(String) && pre.is_a?(String)
377
+ v.start_with?(pre) ? v[pre.length..] : v
378
+ end
379
+
380
+ def rtrimstr(v, suf)
381
+ err('endswith() requires string inputs') unless v.is_a?(String) && suf.is_a?(String)
382
+ v.end_with?(suf) ? v[0, v.length - suf.length] : v
383
+ end
384
+
385
+ fn('ltrimstr', 1) { |v, pre| ltrimstr(v, pre) }
386
+ fn('rtrimstr', 1) { |v, suf| rtrimstr(v, suf) }
387
+ fn('trimstr', 1) { |v, x| rtrimstr(ltrimstr(v, x), x) }
388
+
389
+ # ---------------------------------------------------------- types etc
390
+
391
+ fn('type', 0) { |v| Value.type_name(v) }
392
+
393
+ fn('length', 0) do |v|
394
+ case v
395
+ when nil then 0
396
+ when true, false then err("#{Value.desc(v)} has no length")
397
+ when Integer, Float then Value.normalize_number(v.abs)
398
+ when String, Array, Hash then v.length
399
+ end
400
+ end
401
+
402
+ fn('utf8bytelength', 0) do |v|
403
+ err("#{Value.desc(v)} only strings have UTF-8 byte length") unless v.is_a?(String)
404
+ v.bytesize
405
+ end
406
+
407
+ fn('keys', 0) do |v|
408
+ case v
409
+ when Hash then v.keys.sort_by(&:b)
410
+ when Array then (0...v.length).to_a
411
+ else err("#{Value.desc(v)} has no keys")
412
+ end
413
+ end
414
+
415
+ fn('keys_unsorted', 0) do |v|
416
+ case v
417
+ when Hash then v.keys
418
+ when Array then (0...v.length).to_a
419
+ else err("#{Value.desc(v)} has no keys")
420
+ end
421
+ end
422
+
423
+ fn('has', 1) do |v, k|
424
+ if v.is_a?(Hash) && k.is_a?(String)
425
+ v.key?(k)
426
+ elsif v.is_a?(Array) && Value.number?(k)
427
+ k >= 0 && k < v.length
428
+ elsif v.nil?
429
+ false
430
+ else
431
+ err("Cannot check whether #{Value.type_name(v)} has a #{Value.type_name(k)} key")
432
+ end
433
+ end
434
+
435
+ fn('contains', 1) do |a, b|
436
+ if Value.kind_order(a) != Value.kind_order(b)
437
+ err("#{Value.desc(a)} and #{Value.desc(b)} cannot have their containment checked")
438
+ end
439
+
440
+ contains?(a, b)
441
+ end
442
+
443
+ def contains?(a, b, depth = 0)
444
+ err('Containment check too deep') if (a.is_a?(Hash) || a.is_a?(Array)) && depth > Value::MAX_DEPTH
445
+
446
+ if a.is_a?(Hash) && b.is_a?(Hash)
447
+ b.all? { |k, bv| a.key?(k) && contains?(a[k], bv, depth + 1) }
448
+ elsif a.is_a?(Array) && b.is_a?(Array)
449
+ b.all? { |bv| a.any? { |av| contains?(av, bv, depth + 1) } }
450
+ elsif a.is_a?(String) && b.is_a?(String)
451
+ a.include?(b)
452
+ elsif Value.kind_order(a) == Value.kind_order(b)
453
+ Value.equal?(a, b)
454
+ else
455
+ false
456
+ end
457
+ end
458
+
459
+ fn('add', 0) do |v|
460
+ vals = case v
461
+ when Array then v
462
+ when Hash then v.values
463
+ else err("Cannot iterate over #{Value.desc(v)}")
464
+ end
465
+ vals.reduce(nil) { |acc, x| Ops.add(acc, x) }
466
+ end
467
+
468
+ fn('tostring', 0) { |v| Ops.tostring(v) }
469
+ fn('tojson', 0) { |v| Encoder.dump(v) }
470
+
471
+ fn('fromjson', 0) do |v|
472
+ err("#{Value.desc(v)} only strings can be parsed") unless v.is_a?(String)
473
+ begin
474
+ JSONParser.parse(v)
475
+ rescue ParseError => e
476
+ msg = e.message
477
+ msg += " (while parsing '#{v}')" unless msg.include?('while parsing')
478
+ err(msg)
479
+ end
480
+ end
481
+
482
+ TONUMBER_RE = /\A[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?\z/
483
+
484
+ fn('tonumber', 0) do |v|
485
+ next v if Value.number?(v)
486
+
487
+ err("#{Value.desc(v)} cannot be parsed as a number") unless v.is_a?(String)
488
+ case v
489
+ when 'nan', 'NaN', '-nan', '-NaN' then Float::NAN
490
+ when 'infinity', 'Infinity' then Float::MAX
491
+ when '-infinity', '-Infinity' then -Float::MAX
492
+ else
493
+ err("#{Value.desc(v)} cannot be parsed as a number") unless v.match?(TONUMBER_RE)
494
+ JSONParser.new(v).send(:parse_number, v)
495
+ end
496
+ end
497
+
498
+ fn('toboolean', 0) do |v|
499
+ case v
500
+ when true, false then v
501
+ when 'true' then true
502
+ when 'false' then false
503
+ else err("#{Value.desc(v)} cannot be parsed as a boolean")
504
+ end
505
+ end
506
+
507
+ fn('ascii_downcase', 0) do |v|
508
+ err('explode input must be a string') unless v.is_a?(String)
509
+ v.tr('A-Z', 'a-z')
510
+ end
511
+
512
+ fn('ascii_upcase', 0) do |v|
513
+ err('explode input must be a string') unless v.is_a?(String)
514
+ v.tr('a-z', 'A-Z')
515
+ end
516
+
517
+ fn('explode', 0) do |v|
518
+ err('explode input must be a string') unless v.is_a?(String)
519
+ v.codepoints
520
+ end
521
+
522
+ fn('implode', 0) do |v|
523
+ err('implode input must be an array') unless v.is_a?(Array)
524
+ v.map do |cp|
525
+ unless Value.number?(cp) && !(cp.is_a?(Float) && cp.nan?)
526
+ err("#{Value.desc(cp)} can't be imploded, unicode codepoint needs to be numeric")
527
+ end
528
+
529
+ cp = cp.to_i
530
+ cp = 0xFFFD if cp.negative? || cp > 0x10FFFF || cp.between?(0xD800, 0xDFFF)
531
+ cp.chr(Encoding::UTF_8)
532
+ end.join.force_encoding(Encoding::UTF_8)
533
+ end
534
+
535
+ fn('startswith', 1) do |v, s|
536
+ err('startswith() requires string inputs') unless v.is_a?(String) && s.is_a?(String)
537
+ v.start_with?(s)
538
+ end
539
+
540
+ fn('endswith', 1) do |v, s|
541
+ err('endswith() requires string inputs') unless v.is_a?(String) && s.is_a?(String)
542
+ v.end_with?(s)
543
+ end
544
+
545
+ WS_CHARS = "\t\n\v\f\r \u0085   - 

   "
546
+ WS_L = /\A[#{WS_CHARS}]+/
547
+ WS_R = /[#{WS_CHARS}]+\z/
548
+
549
+ def trim_input(v)
550
+ err('trim input must be a string') unless v.is_a?(String)
551
+ v
552
+ end
553
+
554
+ fn('trim', 0) { |v| trim_input(v).sub(WS_L, '').sub(WS_R, '') }
555
+ fn('ltrim', 0) { |v| trim_input(v).sub(WS_L, '') }
556
+ fn('rtrim', 0) { |v| trim_input(v).sub(WS_R, '') }
557
+
558
+ fn('split', 1) do |v, sep|
559
+ err('split input and separator must be strings') unless v.is_a?(String) && sep.is_a?(String)
560
+ Ops.split_string(v, sep)
561
+ end
562
+
563
+ fn('join', 1) do |v, sep|
564
+ vals = case v
565
+ when Array then v
566
+ when Hash then v.values
567
+ else err("Cannot iterate over #{Value.desc(v)}")
568
+ end
569
+ acc = nil
570
+ vals.each do |x|
571
+ acc = acc.nil? ? '' : Ops.add(acc, sep)
572
+ s = case x
573
+ when nil then ''
574
+ when true, false, Integer, Float then Encoder.dump(x)
575
+ else x # arrays and objects make the addition fail, like jq
576
+ end
577
+ acc = Ops.add(acc, s)
578
+ end
579
+ acc.nil? ? '' : acc
580
+ end
581
+
582
+ def flatten(arr, depth)
583
+ arr.each_with_object([]) do |x, out|
584
+ if x.is_a?(Array) && depth != 0
585
+ out.concat(flatten(x, depth - 1))
586
+ else
587
+ out << x
588
+ end
589
+ end
590
+ end
591
+
592
+ def flatten_input(v)
593
+ case v
594
+ when Array then v
595
+ when Hash then v.values
596
+ else err("Cannot iterate over #{Value.desc(v)}")
597
+ end
598
+ end
599
+
600
+ fn('flatten', 0) { |v| flatten(flatten_input(v), -1) }
601
+
602
+ fn('flatten', 1) do |v, d|
603
+ err('flatten depth must not be negative') if Value.number?(d) && d.negative?
604
+ flatten(flatten_input(v), d.to_i)
605
+ end
606
+
607
+ def require_array(v, what)
608
+ err("#{Value.desc(v)} cannot be #{what}, as it is not an array") unless v.is_a?(Array)
609
+ end
610
+
611
+ fn('sort', 0) do |v|
612
+ require_array(v, 'sorted')
613
+ Value.sort(v)
614
+ end
615
+
616
+ def sort_by_keys(v, keys)
617
+ require_array(v, 'sorted')
618
+ sorted = v.each_with_index.sort do |(_, i), (_, j)|
619
+ c = Value.compare(keys[i], keys[j])
620
+ c.zero? ? i <=> j : c
621
+ end
622
+ sorted.map { |(x, i)| [x, keys[i]] }
623
+ end
624
+
625
+ fn('_sort_by_impl', 1) { |v, keys| sort_by_keys(v, keys).map(&:first) }
626
+
627
+ fn('_group_by_impl', 1) do |v, keys|
628
+ groups = []
629
+ last = nil
630
+ sort_by_keys(v, keys).each do |x, k|
631
+ if groups.empty? || !Value.equal?(last, k)
632
+ groups << [x]
633
+ last = k
634
+ else
635
+ groups.last << x
636
+ end
637
+ end
638
+ groups
639
+ end
640
+
641
+ fn('_unique_by_impl', 1) do |v, keys|
642
+ out = []
643
+ last = nil
644
+ first = true
645
+ sort_by_keys(v, keys).each do |x, k|
646
+ next unless first || !Value.equal?(last, k)
647
+
648
+ out << x
649
+ last = k
650
+ first = false
651
+ end
652
+ out
653
+ end
654
+
655
+ fn('_min_by_impl', 1) do |v, keys|
656
+ not_iterable(v, keys) unless v.is_a?(Array)
657
+ best = nil
658
+ bk = nil
659
+ v.each_with_index do |x, i|
660
+ if i.zero? || Value.compare(keys[i], bk).negative?
661
+ best = x
662
+ bk = keys[i]
663
+ end
664
+ end
665
+ best
666
+ end
667
+
668
+ fn('_max_by_impl', 1) do |v, keys|
669
+ not_iterable(v, keys) unless v.is_a?(Array)
670
+ best = nil
671
+ bk = nil
672
+ v.each_with_index do |x, i|
673
+ if i.zero? || Value.compare(keys[i], bk) >= 0
674
+ best = x
675
+ bk = keys[i]
676
+ end
677
+ end
678
+ best
679
+ end
680
+
681
+ def not_iterable(v, keys = v)
682
+ err("#{Value.desc(v)} and #{Value.desc(keys)} cannot be iterated over")
683
+ end
684
+
685
+ fn('min', 0) do |v|
686
+ not_iterable(v) unless v.is_a?(Array)
687
+ v.each_with_index.reduce(nil) { |m, (x, i)| i.zero? || Value.compare(x, m).negative? ? x : m }
688
+ end
689
+
690
+ fn('max', 0) do |v|
691
+ not_iterable(v) unless v.is_a?(Array)
692
+ v.each_with_index.reduce(nil) { |m, (x, i)| i.zero? || Value.compare(x, m) >= 0 ? x : m }
693
+ end
694
+
695
+ fn('unique', 0) do |v|
696
+ require_array(v, 'sorted')
697
+ out = []
698
+ Value.sort(v).each { |x| out << x if out.empty? || !Value.equal?(out.last, x) }
699
+ out
700
+ end
701
+
702
+ # codepoint offsets of every (possibly overlapping) occurrence
703
+ def strindices(v, i)
704
+ out = []
705
+ return out if i.empty?
706
+
707
+ pos = 0
708
+ while (idx = v.index(i, pos))
709
+ out << idx
710
+ pos = idx + 1
711
+ end
712
+ out
713
+ end
714
+
715
+ fn('_strindices', 1) do |v, i|
716
+ err("#{Value.desc(v)} cannot be searched, as it is not a string") unless v.is_a?(String)
717
+ err("#{Value.desc(i)} is not a string") unless i.is_a?(String)
718
+ strindices(v, i)
719
+ end
720
+
721
+ # def indices($i): if type == "array" and ($i|type) == "array" then .[$i]
722
+ # elif type == "array" then .[[$i]]
723
+ # elif type == "string" and ($i|type) == "string" then _strindices($i)
724
+ # else .[$i] end;
725
+ fn('indices', 1) do |v, i|
726
+ if v.is_a?(Array)
727
+ Ops.index(v, i.is_a?(Array) ? i : [i])
728
+ elsif v.is_a?(String) && i.is_a?(String)
729
+ strindices(v, i)
730
+ else
731
+ Ops.index(v, i)
732
+ end
733
+ end
734
+
735
+ fn('to_entries', 0) do |v|
736
+ case v
737
+ when Hash then v.map { |k, x| { 'key' => k, 'value' => x } }
738
+ when Array then v.each_with_index.map { |x, i| { 'key' => i, 'value' => x } }
739
+ else err("#{Value.desc(v)} has no keys")
740
+ end
741
+ end
742
+
743
+ fn('from_entries', 0) do |v|
744
+ vals = case v
745
+ when Array then v
746
+ when Hash then v.values
747
+ else err("Cannot iterate over #{Value.desc(v)}")
748
+ end
749
+ vals.each_with_object({}) do |e, h|
750
+ k = %w[key Key name Name].reduce(nil) { |acc, n| Value.truthy?(acc) ? acc : Ops.index(e, n) }
751
+ err("Cannot use #{Value.desc(k)} as object key") unless k.is_a?(String)
752
+ has_value = case e
753
+ when Hash then e.key?('value')
754
+ when nil then false
755
+ else err("Cannot check whether #{Value.type_name(e)} has a string key")
756
+ end
757
+ h[k] = has_value ? e['value'] : Ops.index(e, 'Value')
758
+ end
759
+ end
760
+
761
+ fn('format', 1) do |v, f|
762
+ err("#{Value.desc(f)} is not a valid format") unless f.is_a?(String)
763
+ Formats.apply(f, v)
764
+ end
765
+
766
+ fn('infinite', 0) { |_| Float::INFINITY }
767
+ fn('nan', 0) { |_| Float::NAN }
768
+ fn('isinfinite', 0) { |v| v.is_a?(Float) && v.infinite? ? true : false }
769
+ fn('isnan', 0) { |v| v.is_a?(Float) && v.nan? }
770
+ fn('isnormal', 0) do |v|
771
+ next false unless Value.number?(v)
772
+
773
+ f = v.to_f
774
+ f.finite? && !f.zero? && f.abs >= Float::MIN
775
+ end
776
+
777
+ fn('have_literal_numbers', 0) { |_| true }
778
+ fn('have_decnum', 0) { |_| false }
779
+
780
+ # ------------------------------------------------------------- math
781
+
782
+ def mathcall
783
+ r = yield
784
+ r = r.to_f if r.is_a?(Rational)
785
+ Value.normalize_number(r)
786
+ rescue Math::DomainError
787
+ Float::NAN
788
+ rescue FloatDomainError
789
+ Float::NAN
790
+ end
791
+
792
+ # Kahan's accurate expm1 / log1p
793
+ def expm1(x)
794
+ # |x| <= 1: sum the series exactly so that the result is correctly rounded
795
+ if x.finite? && x.abs <= 1
796
+ return x if x.zero?
797
+
798
+ r = Rational(x)
799
+ term = r
800
+ sum = r
801
+ k = 1
802
+ while term.abs > sum.abs * Rational(1, 10**25)
803
+ k += 1
804
+ term = term * r / k
805
+ sum += term
806
+ end
807
+ return sum.to_f
808
+ end
809
+
810
+ u = Math.exp(x)
811
+ return x if u == 1.0
812
+ return -1.0 if u - 1.0 == -1.0
813
+ return u if u.infinite?
814
+
815
+ (u - 1.0) * x / Math.log(u)
816
+ end
817
+
818
+ def log1p(x)
819
+ u = 1.0 + x
820
+ return x if u == 1.0
821
+ return Math.log(u) if u.infinite? || u <= 0
822
+
823
+ Math.log(u) * x / (u - 1.0)
824
+ end
825
+
826
+ # C rounding functions keep the sign of zero: ceil(-0.5) is -0
827
+ def signed(x, r)
828
+ r.zero? && (x.negative? || (x.zero? && (1.0 / x).negative?)) ? -0.0 : r
829
+ end
830
+
831
+ def round_half_even(f)
832
+ return f unless f.finite?
833
+
834
+ f.round(half: :even).to_f
835
+ end
836
+
837
+ MATH1 = {
838
+ 'floor' => lambda { |x|
839
+ if x.is_a?(Integer)
840
+ x
841
+ else
842
+ (x.finite? ? x.floor.to_f : x)
843
+ end
844
+ },
845
+ 'ceil' => lambda { |x|
846
+ if x.is_a?(Integer)
847
+ x
848
+ else
849
+ Builtins.signed(x, x.finite? ? x.ceil.to_f : x)
850
+ end
851
+ },
852
+ 'round' => lambda { |x|
853
+ if x.is_a?(Integer)
854
+ x
855
+ else
856
+ Builtins.signed(x, x.finite? ? x.round.to_f : x)
857
+ end
858
+ },
859
+ 'trunc' => lambda { |x|
860
+ if x.is_a?(Integer)
861
+ x
862
+ else
863
+ Builtins.signed(x, x.finite? ? x.truncate.to_f : x)
864
+ end
865
+ },
866
+ 'nearbyint' => ->(x) { x.is_a?(Integer) ? x : Builtins.signed(x, Builtins.round_half_even(x)) },
867
+ 'rint' => ->(x) { x.is_a?(Integer) ? x : Builtins.signed(x, Builtins.round_half_even(x)) },
868
+ 'fabs' => lambda(&:abs),
869
+ 'sqrt' => ->(x) { Math.sqrt(x) },
870
+ 'cbrt' => ->(x) { Math.cbrt(x) },
871
+ 'exp' => ->(x) { Math.exp(x) },
872
+ 'exp2' => ->(x) { 2.0**x },
873
+ 'exp10' => ->(x) { 10.0**x },
874
+ 'erf' => ->(x) { Math.erf(x) },
875
+ 'erfc' => ->(x) { Math.erfc(x) },
876
+ 'j0' => ->(x) { Bessel.jn(0, x) },
877
+ 'j1' => ->(x) { Bessel.jn(1, x) },
878
+ 'y0' => ->(x) { Bessel.y0(x) },
879
+ 'y1' => ->(x) { Bessel.y1(x) },
880
+ 'expm1' => ->(x) { Builtins.expm1(x.to_f) },
881
+ 'log' => ->(x) { x.zero? ? -Float::INFINITY : Math.log(x) },
882
+ 'log2' => ->(x) { x.zero? ? -Float::INFINITY : Math.log2(x) },
883
+ 'log10' => ->(x) { x.zero? ? -Float::INFINITY : Math.log10(x) },
884
+ 'log1p' => ->(x) { Builtins.log1p(x.to_f) },
885
+ 'logb' => lambda { |x|
886
+ if x.zero?
887
+ -Float::INFINITY
888
+ else
889
+ (x.to_f.finite? ? Math.frexp(x)[1] - 1 : x.abs.to_f)
890
+ end
891
+ },
892
+ 'significand' => ->(x) { x.zero? || !x.to_f.finite? ? x : Math.frexp(x)[0] * 2 },
893
+ 'gamma' => ->(x) { Math.lgamma(x)[0] },
894
+ 'lgamma' => ->(x) { Math.lgamma(x)[0] },
895
+ 'tgamma' => ->(x) { Math.gamma(x) },
896
+ 'sin' => ->(x) { Math.sin(x) },
897
+ 'cos' => ->(x) { Math.cos(x) },
898
+ 'tan' => ->(x) { Math.tan(x) },
899
+ 'asin' => ->(x) { Math.asin(x) },
900
+ 'acos' => ->(x) { Math.acos(x) },
901
+ 'atan' => ->(x) { Math.atan(x) },
902
+ 'sinh' => ->(x) { Math.sinh(x) },
903
+ 'cosh' => ->(x) { Math.cosh(x) },
904
+ 'tanh' => ->(x) { Math.tanh(x) },
905
+ 'asinh' => ->(x) { Math.asinh(x) },
906
+ 'acosh' => ->(x) { Math.acosh(x) },
907
+ 'atanh' => ->(x) { Math.atanh(x) }
908
+ }.freeze
909
+
910
+ MATH1.each do |name, f|
911
+ fn(name, 0) { |v| mathcall { f.call(num(v)) } }
912
+ end
913
+
914
+ fn('frexp', 0) do |v|
915
+ num(v)
916
+ f = v.to_f
917
+ if f.zero? || !f.finite?
918
+ [Value.normalize_number(f), 0]
919
+ else
920
+ m, e = Math.frexp(f)
921
+ [Value.normalize_number(m), e]
922
+ end
923
+ end
924
+
925
+ fn('modf', 0) do |v|
926
+ num(v)
927
+ f = v.to_f
928
+ if f.infinite?
929
+ [0.0, f]
930
+ else
931
+ i = f.truncate.to_f
932
+ [Value.normalize_number(f - i), Value.normalize_number(i)]
933
+ end
934
+ end
935
+
936
+ fn('lgamma_r', 0) do |v|
937
+ r, s = Math.lgamma(num(v))
938
+ [Value.normalize_number(r), s]
939
+ end
940
+
941
+ MATH2 = {
942
+ 'pow' => ->(a, b) { a.to_f**b },
943
+ 'atan2' => ->(a, b) { Math.atan2(a, b) },
944
+ 'fmin' => ->(a, b) { [a, b].min },
945
+ 'fmax' => ->(a, b) { [a, b].max },
946
+ 'fmod' => ->(a, b) { b.zero? ? Float::NAN : a.to_f.remainder(b) },
947
+ 'hypot' => ->(a, b) { Math.hypot(a, b) },
948
+ 'copysign' => lambda { |a, b|
949
+ b.to_f.negative? || (b.to_f.zero? && (1.0 / b.to_f).negative?) ? -a.to_f.abs : a.to_f.abs
950
+ },
951
+ 'drem' => ->(a, b) { b.zero? ? Float::NAN : a - (b * Builtins.round_half_even(a.to_f / b)) },
952
+ 'remainder' => ->(a, b) { b.zero? ? Float::NAN : a - (b * Builtins.round_half_even(a.to_f / b)) },
953
+ 'fdim' => ->(a, b) { a > b ? a - b : 0 },
954
+ 'ldexp' => ->(a, b) { Math.ldexp(a, b.to_i) },
955
+ 'scalb' => ->(a, b) { a * (2.0**b) },
956
+ 'scalbln' => ->(a, b) { Math.ldexp(a, b.to_i) },
957
+ 'nextafter' => lambda { |a, b|
958
+ if a == b
959
+ b.to_f
960
+ else
961
+ (b > a ? a.to_f.next_float : a.to_f.prev_float)
962
+ end
963
+ },
964
+ 'nexttoward' => lambda { |a, b|
965
+ if a == b
966
+ b.to_f
967
+ else
968
+ (b > a ? a.to_f.next_float : a.to_f.prev_float)
969
+ end
970
+ }
971
+ }.freeze
972
+
973
+ MATH2.each do |name, f|
974
+ fn(name, 2) { |_v, a, b| mathcall { f.call(num(a), num(b)) } }
975
+ end
976
+
977
+ fn('fma', 3) { |_v, a, b, c| mathcall { (num(a) * num(b)) + num(c) } }
978
+ fn('jn', 2) { |_v, n, x| mathcall { Bessel.jn(num(n), num(x)) } }
979
+ fn('yn', 2) { |_v, n, x| mathcall { Bessel.yn(num(n), num(x)) } }
980
+
981
+ # ------------------------------------------------------------- regex
982
+
983
+ def translate_regex(re)
984
+ out = +''
985
+ i = 0
986
+ in_class = false
987
+ has_named = re.match?(/\(\?<[a-zA-Z_]/)
988
+ gen = 0
989
+ while i < re.length
990
+ c = re[i]
991
+ if c == '\\'
992
+ out << re[i, 2]
993
+ i += 2
994
+ next
995
+ end
996
+ if in_class
997
+ in_class = false if c == ']'
998
+ out << c
999
+ elsif c == '['
1000
+ in_class = true
1001
+ out << c
1002
+ if re[i + 1] == '^'
1003
+ out << '^'
1004
+ i += 1
1005
+ end
1006
+ if re[i + 1] == ']'
1007
+ out << '\]' # a leading ] belongs to the class
1008
+ i += 1
1009
+ end
1010
+ elsif c == '^'
1011
+ out << '\\A'
1012
+ elsif c == '$'
1013
+ out << '\z'
1014
+ elsif c == '(' && has_named && re[i + 1] != '?'
1015
+ gen += 1
1016
+ out << "(?<__rbjq_#{gen}>"
1017
+ else
1018
+ out << c
1019
+ end
1020
+ i += 1
1021
+ end
1022
+ out
1023
+ end
1024
+
1025
+ def compile_regex(re, flags)
1026
+ err("#{Value.desc(re)} is not a string") unless re.is_a?(String)
1027
+ err("#{Value.desc(flags)} is not a string") unless flags.nil? || flags.is_a?(String)
1028
+
1029
+ global = false
1030
+ noempty = false
1031
+ opts = 0
1032
+ (flags || '').each_char do |f|
1033
+ case f
1034
+ when 'g' then global = true
1035
+ when 'i' then opts |= Regexp::IGNORECASE
1036
+ when 'x' then opts |= Regexp::EXTENDED
1037
+ when 's' then nil
1038
+ when 'p' then opts |= Regexp::MULTILINE
1039
+ when 'n' then noempty = true
1040
+ when 'l' then nil
1041
+ else err("#{flags} is not a valid modifier string")
1042
+ end
1043
+ end
1044
+ begin
1045
+ regexp = Regexp.new(translate_regex(re), opts)
1046
+ rescue RegexpError => e
1047
+ err("Regex failure: #{e.message.sub(%r{: /.*\z}m, '')}")
1048
+ end
1049
+ names = {}
1050
+ regexp.named_captures.each do |name, idxs|
1051
+ idxs.each { |i| names[i] = name.start_with?('__rbjq_') ? nil : name }
1052
+ end
1053
+ [regexp, global, noempty, names]
1054
+ end
1055
+
1056
+ def match_all(str, re, flags)
1057
+ err("#{Value.desc(str)} cannot be matched, as it is not a string") unless str.is_a?(String)
1058
+ regexp, global, noempty, names = compile_regex(re, flags)
1059
+ results = []
1060
+ pos = 0
1061
+ while pos <= str.length
1062
+ m = regexp.match(str, pos)
1063
+ break unless m
1064
+
1065
+ if m[0].empty?
1066
+ results << m unless noempty
1067
+ pos = m.begin(0) + 1
1068
+ else
1069
+ results << m
1070
+ pos = m.end(0)
1071
+ end
1072
+ break unless global
1073
+ end
1074
+ [results, names]
1075
+ end
1076
+
1077
+ def match_object(m, names)
1078
+ caps = (1...m.size).map do |i|
1079
+ if m[i].nil?
1080
+ { 'offset' => -1, 'string' => nil, 'length' => 0, 'name' => names[i] }
1081
+ else
1082
+ { 'offset' => m.begin(i), 'length' => m[i].length, 'string' => m[i], 'name' => names[i] }
1083
+ end
1084
+ end
1085
+ { 'offset' => m.begin(0), 'length' => m[0].length, 'string' => m[0], 'captures' => caps }
1086
+ end
1087
+
1088
+ fn('_match_impl', 3) do |v, re, flags, test|
1089
+ if test
1090
+ err("#{Value.desc(v)} cannot be matched, as it is not a string") unless v.is_a?(String)
1091
+ regexp, _, noempty, = compile_regex(re, flags)
1092
+ noempty ? !match_all(v, re, flags)[0].empty? : regexp.match?(v)
1093
+ else
1094
+ ms, names = match_all(v, re, flags)
1095
+ ms.map { |m| match_object(m, names) }
1096
+ end
1097
+ end
1098
+
1099
+ def capture_object(m, names)
1100
+ h = {}
1101
+ (1...m.size).each do |i|
1102
+ n = names[i]
1103
+ h[n] = m[i] if n
1104
+ end
1105
+ h
1106
+ end
1107
+
1108
+ def sub_impl(interp, input, path, str_node, env, re, flags, &blk)
1109
+ ms, names = match_all(input, re, flags)
1110
+ if ms.empty?
1111
+ blk.call(input, path && INVALID)
1112
+ return
1113
+ end
1114
+ # Like jq 1.7.1: the n-th output of the replacement is used for every
1115
+ # match, giving one result per output.
1116
+ results = []
1117
+ prev = 0
1118
+ ms.each do |m|
1119
+ gap = input[prev...m.begin(0)]
1120
+ inserts = []
1121
+ interp.eval_node(str_node, capture_object(m, names), nil, env) { |s| inserts << s }
1122
+ inserts.each_with_index do |ins, ix|
1123
+ results[ix] = Ops.add(Ops.add(results[ix], gap), ins)
1124
+ end
1125
+ prev = m.end(0)
1126
+ end
1127
+ rest = input[prev..]
1128
+ results = results.map { |res| Ops.add(res, rest) }.select { |res| Value.truthy?(res) }
1129
+ results = [input] if results.empty?
1130
+ results.each { |res| blk.call(res, path && INVALID) }
1131
+ end
1132
+
1133
+ special('sub', 2) do |interp, input, path, args, env, &blk|
1134
+ interp.eval_node(args[0], input, nil, env) do |re|
1135
+ sub_impl(interp, input, path, args[1], env, re, nil, &blk)
1136
+ end
1137
+ end
1138
+
1139
+ special('sub', 3) do |interp, input, path, args, env, &blk|
1140
+ interp.eval_node(args[2], input, nil, env) do |flags|
1141
+ interp.eval_node(args[0], input, nil, env) do |re|
1142
+ sub_impl(interp, input, path, args[1], env, re, flags, &blk)
1143
+ end
1144
+ end
1145
+ end
1146
+
1147
+ special('gsub', 2) do |interp, input, path, args, env, &blk|
1148
+ interp.eval_node(args[0], input, nil, env) do |re|
1149
+ sub_impl(interp, input, path, args[1], env, re, 'g', &blk)
1150
+ end
1151
+ end
1152
+
1153
+ special('gsub', 3) do |interp, input, path, args, env, &blk|
1154
+ interp.eval_node(args[2], input, nil, env) do |flags|
1155
+ interp.eval_node(args[0], input, nil, env) do |re|
1156
+ sub_impl(interp, input, path, args[1], env, re, "#{flags}g", &blk)
1157
+ end
1158
+ end
1159
+ end
1160
+
1161
+ fn('split', 2) do |v, re, flags|
1162
+ ms, = match_all(v, re, "#{flags}g")
1163
+ out = []
1164
+ prev = 0
1165
+ ms.each do |m|
1166
+ out << v[prev...m.begin(0)]
1167
+ prev = m.end(0)
1168
+ end
1169
+ out << v[prev..]
1170
+ out
1171
+ end
1172
+
1173
+ # -------------------------------------------------------------- dates
1174
+
1175
+ def broken_down(t, frac = 0)
1176
+ sec = t.sec + frac
1177
+ [t.year, t.month - 1, t.day, t.hour, t.min, Value.normalize_number(sec), t.wday, t.yday - 1]
1178
+ end
1179
+
1180
+ def time_from_number(n, local: false)
1181
+ i = n.floor
1182
+ frac = n - i
1183
+ t = Time.at(i)
1184
+ t = local ? t.localtime : t.utc
1185
+ [t, Value.normalize_number(frac)]
1186
+ end
1187
+
1188
+ def days_from_civil(y, m, d)
1189
+ y -= 1 if m <= 2
1190
+ era = (y >= 0 ? y : y - 399) / 400
1191
+ yoe = y - (era * 400)
1192
+ doy = (((153 * (m + (m > 2 ? -3 : 9))) + 2) / 5) + d - 1
1193
+ doe = (yoe * 365) + (yoe / 4) - (yoe / 100) + doy
1194
+ (era * 146_097) + doe - 719_468
1195
+ end
1196
+
1197
+ # [year, month, mday, hours, minutes, seconds, ...] with missing fields as 0
1198
+ def tm_fields(bd, name)
1199
+ err("#{name} requires parsed datetime inputs") unless bd.all? { |x| Value.number?(x) }
1200
+ f = bd[0, 6].map(&:floor)
1201
+ f[0] ||= 1900
1202
+ f.fill(0, f.length...6)
1203
+ end
1204
+
1205
+ def timegm(bd)
1206
+ y, mon, d, h, mi, s = tm_fields(bd, 'mktime')
1207
+ y += mon.div(12)
1208
+ mon %= 12
1209
+ days = days_from_civil(y, mon + 1, 1) + (d - 1)
1210
+ (days * 86_400) + (h * 3600) + (mi * 60) + s
1211
+ end
1212
+
1213
+ # jq's set_tm_wday / set_tm_yday, which also handle a day of month of 0
1214
+ def tm_wday(year, mon, mday)
1215
+ century = year / 100
1216
+ y = year % 100
1217
+ y -= 1 if mon < 2
1218
+ m = mon - 1
1219
+ m += 12 if m < 1
1220
+ wday = (mday + ((2.6 * m) - 0.2).floor + y + (y / 4.0).floor + (century / 4.0).floor - (2 * century)).remainder(7)
1221
+ wday.negative? ? wday + 7 : wday
1222
+ end
1223
+
1224
+ CUMULATIVE_DAYS = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334].freeze
1225
+
1226
+ def tm_yday(year, mon, mday)
1227
+ leap = mon > 1 && (((year % 4).zero? && (year % 100 != 0)) || (year % 400).zero?) ? 1 : 0
1228
+ CUMULATIVE_DAYS[mon.abs % 12] + leap + mday - 1
1229
+ end
1230
+
1231
+ fn('gmtime', 0) do |v|
1232
+ err('gmtime() requires numeric inputs') unless Value.number?(v)
1233
+ t, frac = time_from_number(v)
1234
+ broken_down(t, frac)
1235
+ end
1236
+
1237
+ fn('localtime', 0) do |v|
1238
+ err('localtime() requires numeric inputs') unless Value.number?(v)
1239
+ t, frac = time_from_number(v, local: true)
1240
+ broken_down(t, frac)
1241
+ end
1242
+
1243
+ fn('mktime', 0) do |v|
1244
+ err('mktime requires array inputs') unless v.is_a?(Array)
1245
+ secs = timegm(v)
1246
+ err('invalid gmtime representation') if secs < MIN_TIME
1247
+
1248
+ secs
1249
+ end
1250
+
1251
+ DAY_NAMES = %w[Sunday Monday Tuesday Wednesday Thursday Friday Saturday].freeze
1252
+ MONTH_NAMES = %w[January February March April May June July August September October November December].freeze
1253
+
1254
+ # The broken-down time [year, month, mday, hours, minutes, seconds, wday, yday]
1255
+ # that jq hands to strftime(3): fields are used as given (not normalized);
1256
+ # missing ones are 0 (the year is 1900).
1257
+ def strftime_fields(v, name, local)
1258
+ return broken_down(time_from_number(v, local: local)[0]).map(&:floor) if Value.number?(v)
1259
+
1260
+ err("#{name} requires parsed datetime inputs") unless v.is_a?(Array)
1261
+ err("#{name} requires parsed datetime inputs") unless v.all? { |x| Value.number?(x) }
1262
+
1263
+ f = v[0, 8].map(&:floor)
1264
+ f[0] ||= 1900
1265
+ f.fill(0, f.length...8)
1266
+ # jq normalizes the fields with timegm(3), which fails before 1900;
1267
+ # then the fields are formatted as given
1268
+ secs = timegm(f)
1269
+ return f if secs < MIN_TIME
1270
+
1271
+ t = Time.at(secs)
1272
+ t = local ? Time.local(t.utc.year, t.utc.month, t.utc.day, t.utc.hour, t.utc.min, t.utc.sec) : t.utc
1273
+ broken_down(t).map(&:floor)
1274
+ end
1275
+
1276
+ MIN_TIME = -2_208_988_800 # 1900-01-01T00:00:00Z
1277
+
1278
+ # strftime(3) in the C locale over raw fields. Directives that need a
1279
+ # normalized date (week numbers etc.) are delegated to Time#strftime.
1280
+ def format_time(fields, fmt, local)
1281
+ year, mon, mday, hour, min, sec, wday, yday = fields
1282
+ normalized = lambda do
1283
+ t = Time.at(timegm(fields)).utc
1284
+ local ? Time.local(t.year, t.month, t.day, t.hour, t.min, t.sec) : t
1285
+ end
1286
+ day = DAY_NAMES[wday % 7]
1287
+ month = MONTH_NAMES[mon % 12]
1288
+ fmt.gsub(/%([-_0^#]?)([a-zA-Z%+])/) do
1289
+ flag = Regexp.last_match(1)
1290
+ c = Regexp.last_match(2)
1291
+ next normalized.call.strftime("%#{flag}#{c}") unless flag.empty?
1292
+
1293
+ case c
1294
+ when 'Y' then year.to_s
1295
+ when 'C' then format('%02d', year / 100)
1296
+ when 'y' then format('%02d', year % 100)
1297
+ when 'm' then format('%02d', mon + 1)
1298
+ when 'd' then format('%02d', mday)
1299
+ when 'e' then format('%2d', mday)
1300
+ when 'H' then format('%02d', hour)
1301
+ when 'k' then format('%2d', hour)
1302
+ when 'I' then format('%02d', (hour % 12).zero? ? 12 : hour % 12)
1303
+ when 'l' then format('%2d', (hour % 12).zero? ? 12 : hour % 12)
1304
+ when 'M' then format('%02d', min)
1305
+ when 'S' then format('%02d', sec)
1306
+ when 'p' then hour < 12 ? 'AM' : 'PM'
1307
+ when 'j' then format('%03d', yday + 1)
1308
+ when 'a' then day[0, 3]
1309
+ when 'A' then day
1310
+ when 'b', 'h' then month[0, 3]
1311
+ when 'B' then month
1312
+ when 'u' then (wday % 7).zero? ? '7' : (wday % 7).to_s
1313
+ when 'w' then (wday % 7).to_s
1314
+ when 'n' then "\n"
1315
+ when 't' then "\t"
1316
+ when '%' then '%'
1317
+ when 'D' then format_time(fields, '%m/%d/%y', local)
1318
+ when 'F' then format_time(fields, '%Y-%m-%d', local)
1319
+ when 'T' then format_time(fields, '%H:%M:%S', local)
1320
+ when 'R' then format_time(fields, '%H:%M', local)
1321
+ when 'r' then format_time(fields, '%I:%M:%S %p', local)
1322
+ when 'c' then format_time(fields, '%a %b %e %H:%M:%S %Y', local)
1323
+ when 'x' then format_time(fields, '%m/%d/%y', local)
1324
+ when 'X' then format_time(fields, '%H:%M:%S', local)
1325
+ when 's' then (local ? normalized.call.to_i : timegm(fields)).to_s
1326
+ when 'Z' then local ? normalized.call.strftime('%Z') : 'UTC'
1327
+ when 'z' then local ? normalized.call.strftime('%z') : '+0000'
1328
+ else normalized.call.strftime("%#{c}")
1329
+ end
1330
+ end
1331
+ end
1332
+
1333
+ fn('strftime', 1) do |v, fmt|
1334
+ err('strftime/1 requires a string format') unless fmt.is_a?(String)
1335
+ format_time(strftime_fields(v, 'strftime/1', false), fmt, false)
1336
+ end
1337
+
1338
+ fn('strflocaltime', 1) do |v, fmt|
1339
+ err('strflocaltime/1 requires a string format') unless fmt.is_a?(String)
1340
+ format_time(strftime_fields(v, 'strflocaltime/1', true), fmt, true)
1341
+ end
1342
+
1343
+ fn('strptime', 1) do |v, fmt|
1344
+ err('strptime/1 requires string inputs and arguments') unless v.is_a?(String) && fmt.is_a?(String)
1345
+ h = Date._strptime(v, fmt)
1346
+ err("date \"#{v}\" does not match format \"#{fmt}\"") if h.nil? || h.key?(:leftover)
1347
+ next broken_down(Time.at(h[:seconds]).utc) if h[:seconds]
1348
+
1349
+ # like strptime(3): fields that are not parsed stay 0 (the year is 1900)
1350
+ year = h[:year] || 1900
1351
+ mon = (h[:mon] || 1) - 1
1352
+ mday = h[:mday] || 0
1353
+ [year, mon, mday, h[:hour] || 0, h[:min] || 0, h[:sec] || 0,
1354
+ tm_wday(year, mon, mday), tm_yday(year, mon, mday)]
1355
+ end
1356
+ end
1357
+ end