barefoot_js 0.40.1 → 0.41.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.
data/lib/barefoot_js.rb CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  require 'set'
4
4
  require 'time'
5
+ require 'barefoot_js/undefined'
5
6
  require 'barefoot_js/evaluator'
6
7
  require 'barefoot_js/search_params'
7
8
 
@@ -24,7 +25,10 @@ require 'barefoot_js/search_params'
24
25
  # directly than Perl's blurred numeric-string scalars, so this port needs
25
26
  # none of the `JSON::PP::Boolean` sentinel-detection machinery the Perl
26
27
  # runtime carries -- a Ruby `true`/`false` IS a boolean, distinguishable
27
- # from `0`/`1` for free.
28
+ # from `0`/`1` for free. Host `nil` is JS `null`; JS `undefined` is
29
+ # `BarefootJS::UNDEF` (barefoot_js/undefined.rb), so a props Hash has JS's
30
+ # four states: a key left out (absent), `UNDEF` (present `undefined`), `nil`
31
+ # (`null`) and a value.
28
32
  module BarefootJS
29
33
  # Marker wrapper for a string that is ALREADY finished HTML and must not
30
34
  # be re-escaped by `Context#h` -- e.g. a named-slot / children capture
@@ -43,6 +47,13 @@ module BarefootJS
43
47
  # `register_components_from_manifest` construct a fresh child instance
44
48
  # per nested render, chaining scope/slot identity off the caller.
45
49
  class Context
50
+ # The default of a helper's optional argument: the call passed none. JS
51
+ # reads an omitted argument as `undefined`, so `omitted?` accepts `UNDEF`
52
+ # too; an explicit `nil` is JS `null`, which each helper coerces like any
53
+ # other value.
54
+ OMITTED = Object.new.freeze
55
+ private_constant :OMITTED
56
+
46
57
  # ---------------------------------------------------------------------
47
58
  # Minimal get/set accessors (Perl-style: no-arg reads, one-arg writes,
48
59
  # matching BarefootJS.pm's hand-rolled accessor base so the exact same
@@ -116,7 +127,7 @@ module BarefootJS
116
127
  # BarefootJS.pm's docstring on the client reconciliation contract.
117
128
  def data_key_attr
118
129
  k = _data_key
119
- return '' if k.nil?
130
+ return '' if BarefootJS.nullish?(k)
120
131
 
121
132
  escaped = k.to_s.gsub('&', '&').gsub('"', '"')
122
133
  %( data-key="#{escaped}")
@@ -142,7 +153,7 @@ module BarefootJS
142
153
  # (e.g. a blog paragraph) terminates the single-quoted attribute and
143
154
  # truncates the hydration payload. The browser entity-decodes the
144
155
  # attribute value, so the client's JSON.parse sees the original text.
145
- json = html_escape(backend.encode_json(client_props))
156
+ json = html_escape(backend.encode_json(json_ready(client_props)))
146
157
  %( bf-p='#{json}')
147
158
  end
148
159
 
@@ -172,7 +183,7 @@ module BarefootJS
172
183
  ''
173
184
  end
174
185
 
175
- def use_context(name, default = nil)
186
+ def use_context(name, default = UNDEF)
176
187
  stack = CONTEXT_STACKS[name]
177
188
  stack.empty? ? default : stack.last
178
189
  end
@@ -206,7 +217,13 @@ module BarefootJS
206
217
  # callers must have already classified the expression as boolean-
207
218
  # result; non-boolean attribute bindings never reach this helper.
208
219
  def bool_str(value)
209
- value ? 'true' : 'false'
220
+ value && !BarefootJS.undefined?(value) ? 'true' : 'false'
221
+ end
222
+
223
+ # A JSX text child's value: JSX renders nothing for a boolean (#3824
224
+ # step 5). Any other value passes through to the text sink.
225
+ def display(value)
226
+ value == true || value == false ? '' : value
210
227
  end
211
228
 
212
229
  def text_start(slot_id)
@@ -225,7 +242,7 @@ module BarefootJS
225
242
  mount = _bf_mount
226
243
  host_segment = "|h=#{host}|m=#{mount || ''}" if host && !host.empty?
227
244
  props_json = ''
228
- props_json = "|#{backend.encode_json(_props)}" if _props && !_props.empty?
245
+ props_json = "|#{backend.encode_json(json_ready(_props))}" if _props && !_props.empty?
229
246
  "<!--bf-scope:#{scope_id}#{host_segment}#{props_json}-->"
230
247
  end
231
248
 
@@ -344,14 +361,14 @@ module BarefootJS
344
361
  end
345
362
  end
346
363
 
347
- # Whether this component's caller passed the prop `name`, even as `nil`:
348
- # JS's `name in props`, which a template can't ask of its vars (every
349
- # declared prop is seeded, so an omitted one and a `nil` one read the
350
- # same). A `{...props}` spread onto a child carries a param only when
351
- # this is true. The keys are those `render_child` recorded for a child
352
- # and `_props` for the root; with neither recorded (a root rendered
353
- # without `_props`), `fallback`, the template's own "not nil" test,
354
- # decides.
364
+ # Whether this component's caller passed the prop `name`, even as `nil`
365
+ # (`null`) or `UNDEF`: JS's `name in props`, which a template can't ask of
366
+ # its vars (every declared prop is seeded, so an omitted one reads as its
367
+ # default or `UNDEF`, as a present `undefined` one does). A `{...props}`
368
+ # spread onto a child carries a param only when this is true. The keys
369
+ # are those `render_child` recorded for a child and `_props` for the
370
+ # root; with neither recorded (a root rendered without `_props`),
371
+ # `fallback`, the template's own "not undefined" test, decides.
355
372
  def passed?(name, fallback)
356
373
  stack = Thread.current[:barefoot_js_caller_keys]
357
374
  keys = stack && !stack.empty? ? stack.last : _props&.keys&.map(&:to_s)
@@ -394,7 +411,7 @@ module BarefootJS
394
411
  child_bf = self.class.new(parent.backend)
395
412
  slot_id = props.delete(:_bf_slot)
396
413
  data_key = props.delete(:key)
397
- child_bf._data_key(data_key) unless data_key.nil?
414
+ child_bf._data_key(data_key) unless BarefootJS.nullish?(data_key)
398
415
  child_bf._scope_id(
399
416
  slot_id ? "#{host_scope}_#{slot_id}" : "#{template_name}_#{rand.to_s[2, 6]}",
400
417
  )
@@ -438,9 +455,12 @@ module BarefootJS
438
455
  # Each entry shape: `{ value:, propName:, isRestProps: }`. For
439
456
  # `isRestProps`, the rest bag passes through unchanged (or the static
440
457
  # `{}` if the caller didn't supply one). For ordinary entries the
441
- # caller's `props[propName]` wins when present, otherwise the static
442
- # `value` does. `propName`-less entries (signal / memo locals) always
443
- # use the static value.
458
+ # caller's `props[propName]` wins when present -- `nil` (JS `null`)
459
+ # included -- and an absent or `UNDEF` prop takes the static `value`, or
460
+ # `UNDEF` when the entry has none (the manifest writes `value` only for a
461
+ # prop with a default; spec/js-undefined-value.md, decision 6).
462
+ # `propName`-less entries (signal / memo locals) always use the static
463
+ # value.
444
464
  #
445
465
  # Public (not `private_class_method`): `register_components_from_manifest`
446
466
  # above uses it for the `ui/*` registry path, but a page that composes
@@ -456,11 +476,11 @@ module BarefootJS
456
476
  extra = {}
457
477
  defaults.each do |name, d|
458
478
  unless d.is_a?(Hash)
459
- extra[name] = d
479
+ extra[name] = BarefootJS.decode_undefined(d)
460
480
  next
461
481
  end
462
482
  if d[:isRestProps]
463
- extra[name] = props.key?(name) ? props[name] : d[:value]
483
+ extra[name] = props.key?(name) ? props[name] : static_fallback(d)
464
484
  next
465
485
  end
466
486
  # `propName` rides in from the JSON manifest as a String -- JSON has
@@ -473,15 +493,23 @@ module BarefootJS
473
493
  # rendering empty) (#2157).
474
494
  prop_name = d[:propName]&.to_sym
475
495
  extra[name] =
476
- if !prop_name.nil? && props.key?(prop_name) && !props[prop_name].nil?
496
+ if !prop_name.nil? && props.key?(prop_name) && !BarefootJS.undefined?(props[prop_name])
477
497
  props[prop_name]
478
498
  else
479
- d[:value]
499
+ static_fallback(d)
480
500
  end
481
501
  end
482
502
  extra
483
503
  end
484
504
 
505
+ # An `ssrDefaults` entry's seed when the caller's prop is absent or
506
+ # `UNDEF`: its `value` (a `{"$undef": true}` sentinel in it is `UNDEF`),
507
+ # or `UNDEF` when it has none.
508
+ def self.static_fallback(entry)
509
+ entry.key?(:value) ? BarefootJS.decode_undefined(entry[:value]) : UNDEF
510
+ end
511
+ private_class_method :static_fallback
512
+
485
513
  # -----------------------------------------------------------------
486
514
  # Streaming SSR (Out-of-Order)
487
515
  # -----------------------------------------------------------------
@@ -509,32 +537,60 @@ module BarefootJS
509
537
 
510
538
  NUMERIC_STRING_RE = /\A\s*[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?\s*\z/.freeze
511
539
 
540
+ # JS `JSON.stringify`. A number is written as JS writes it
541
+ # (`Evaluator.number_to_string`): an integral Float has no `.0`, -0 is
542
+ # `0`, an exponent is unpadded (`-4e-8`, `-4e+21`), and NaN / Infinity
543
+ # are `null`, at any depth (#3787). Ruby's encoder would write `-2.0` /
544
+ # `-4.0e-08` and raise on a non-finite Float. Arrays and Hashes are
545
+ # walked here in insertion order, as `JSON.generate` does; strings and
546
+ # other leaves go through the backend's encoder. `undefined` follows
547
+ # `JSON.stringify` too: a member holding it is skipped, an element is
548
+ # written as `null`, and at the top level the result is `UNDEF` itself
549
+ # (no string), which prints nothing and omits an attribute.
512
550
  def json(value)
513
- backend.encode_json(json_unsign_zeros(value))
514
- end
515
-
516
- # JS `JSON.stringify` writes -0 as `0` at any depth (`[-4 % 2, 1]` ->
517
- # `[0,1]`), but Ruby's encoder spells a Float zero `-0.0` / `0.0` --
518
- # the `-0.0` that `Evaluator.remainder` gives for a negative dividend.
519
- # Float zeros become Integer 0, inside Arrays and Hash values too.
520
- def json_unsign_zeros(value)
521
551
  case value
522
- when Float then value.zero? ? 0 : value
523
- when Array then value.map { |el| json_unsign_zeros(el) }
524
- when Hash then value.transform_values { |v| json_unsign_zeros(v) }
525
- else value
552
+ when Undefined then value
553
+ when Integer, Float
554
+ value.to_f.finite? ? Evaluator.number_to_string(value) : 'null'
555
+ when Array then "[#{value.map { |el| BarefootJS.undefined?(el) ? 'null' : json(el) }.join(',')}]"
556
+ when Hash
557
+ members = value.reject { |_, v| BarefootJS.undefined?(v) }.map { |k, v| "#{backend.encode_json(k.to_s)}:#{json(v)}" }
558
+ "{#{members.join(',')}}"
559
+ else backend.encode_json(value)
526
560
  end
527
561
  end
528
- private :json_unsign_zeros
562
+
563
+ # JS `undefined` as a template spells it (`bf.undefined`): the
564
+ # `undefined` identifier, an omitted method argument's default, the
565
+ # result of a `?.` over a nullish receiver.
566
+ def undefined
567
+ UNDEF
568
+ end
569
+
570
+ # The nil tests (spec/js-undefined-value.md, decisions 3 and 7): JS
571
+ # `x === undefined`, `x === null` and the loose `x == null`. A template
572
+ # spells a nil-test plan through them.
573
+ def is_undefined(value)
574
+ BarefootJS.undefined?(value)
575
+ end
576
+
577
+ def is_null(value)
578
+ BarefootJS.null?(value)
579
+ end
580
+
581
+ def is_nullish(value)
582
+ BarefootJS.nullish?(value)
583
+ end
529
584
 
530
585
  # JS `String(v)` mirror, EXCEPT `nil` renders as '' (not the literal
531
586
  # "null") so an unset prop doesn't surface as literal text in
532
587
  # user-facing HTML -- the same divergence the Go/Perl adapters document
533
- # for their `string` helper. This is the canonical JS-ish stringifier
534
- # used throughout this file (join, spread_attrs, `h`, reduce's string
535
- # fold, ...).
588
+ # for their `string` helper; `undefined` renders as '' too, as a JSX
589
+ # text child does. This is the canonical display stringifier used
590
+ # throughout this file (join, spread_attrs, `h`, reduce's string fold,
591
+ # ...); JS ToString itself is `to_string`.
536
592
  def string(value)
537
- return '' if value.nil?
593
+ return '' if BarefootJS.nullish?(value)
538
594
  return value ? 'true' : 'false' if value.is_a?(TrueClass) || value.is_a?(FalseClass)
539
595
  return Evaluator.number_to_string(value) if value.is_a?(Numeric)
540
596
  # JS `Array.prototype.toString` is `this.join(',')`, applied
@@ -547,6 +603,23 @@ module BarefootJS
547
603
  value.to_s
548
604
  end
549
605
 
606
+ # JS `l - r` / `l * r` over operands the compiler could not prove numbers:
607
+ # ToNumber of both (`undefined` is NaN, `null` 0).
608
+ def sub(left, right)
609
+ Evaluator.binary('-', left, right)
610
+ end
611
+
612
+ def mul(left, right)
613
+ Evaluator.binary('*', left, right)
614
+ end
615
+
616
+ # JS `o?.k`: `undefined` over a nullish receiver, the read of `k`
617
+ # (`get`) otherwise. Ruby's `nil&.[](:k)` gives `nil`, JS's `null?.k`
618
+ # `undefined`; and `&.` calls through on `UNDEF`.
619
+ def get_opt(collection, key)
620
+ BarefootJS.nullish?(collection) ? UNDEF : get(collection, key)
621
+ end
622
+
550
623
  # HTML-escaping helper for text interpolation (`<%= bf.h(expr) %>` --
551
624
  # stdlib ERB does not auto-escape). JS-style stringification via
552
625
  # `string` (numbers per JS Number#toString, nil -> "", booleans ->
@@ -585,11 +658,86 @@ module BarefootJS
585
658
  Evaluator.truthy?(value)
586
659
  end
587
660
 
661
+ # Boxes for a value-position JS `l || r` / `l && r` (#3824): the adapter
662
+ # spells `l || r` as `(bf.keep_truthy(l) || [r])[0]` and `l && r` as
663
+ # `(bf.keep_falsy(l) || [r])[0]`. `keep_truthy` is the one-element array
664
+ # `[value]` when `value` is JS-truthy and nil otherwise (`keep_falsy` the
665
+ # reverse), so Ruby's `||` stops at the box exactly when JS returns
666
+ # `value` itself and builds `[r]` only otherwise (the short circuit);
667
+ # `[0]` unboxes the operand. Each operand appears once, so a chain grows
668
+ # linearly.
669
+ def keep_truthy(value)
670
+ Evaluator.truthy?(value) ? [value] : nil
671
+ end
672
+
673
+ def keep_falsy(value)
674
+ Evaluator.truthy?(value) ? nil : [value]
675
+ end
676
+
677
+ # The box for a value-position JS `l ?? r` (#3839): the adapter spells it
678
+ # as `(bf.keep_nonnil(l) || [r])[0]`, so each operand appears once and a
679
+ # chain grows linearly (`l.nil? ? r : l` rendered `l` twice). Only the
680
+ # two nils (`null`, `undefined`) are absent; `0`, `''` and `false` are
681
+ # kept, as in JS.
682
+ def keep_nonnil(value)
683
+ BarefootJS.nullish?(value) ? nil : [value]
684
+ end
685
+
686
+ # JS primitive helpers (spec/js-primitive-semantics.md, "Operation
687
+ # table"): ToNumber, ToString, `===`, the relational operators, binary
688
+ # `+` and unary `-`. Each delegates to the shared evaluator's primitive
689
+ # of the same operation, so a template helper call and a callback body
690
+ # share one implementation. Unlike `number` and `string` (display
691
+ # helpers: nil -> NaN / ""), nil reads as JS null here (0 / "null") and
692
+ # `UNDEF` as JS undefined (NaN / "undefined").
693
+ def to_number(value)
694
+ Evaluator.to_number(value)
695
+ end
696
+
697
+ def to_string(value)
698
+ Evaluator.to_string(value)
699
+ end
700
+
701
+ # The evaluator refuses a non-primitive `===` operand (its subset
702
+ # contract). A template reaches this helper only with operands the
703
+ # compiler could not type, since it refuses a proven object or array
704
+ # (BF101, #3824 step 8), so an object or array that still arrives here
705
+ # compares by reference, as JS `===` does.
706
+ def strict_eq(left, right)
707
+ Evaluator.strict_eq(left, right)
708
+ rescue Evaluator::EvalUnsupported
709
+ left.equal?(right)
710
+ end
711
+
712
+ def lt(left, right)
713
+ Evaluator.relational('<', left, right)
714
+ end
715
+
716
+ def le(left, right)
717
+ Evaluator.relational('<=', left, right)
718
+ end
719
+
720
+ def gt(left, right)
721
+ Evaluator.relational('>', left, right)
722
+ end
723
+
724
+ def ge(left, right)
725
+ Evaluator.relational('>=', left, right)
726
+ end
727
+
728
+ def plus(left, right)
729
+ Evaluator.binary('+', left, right)
730
+ end
731
+
732
+ def neg(value)
733
+ Evaluator.unary('-', value)
734
+ end
735
+
588
736
  # JS `Number(v)` mirror: numeric / boolean inputs convert as expected;
589
737
  # non-numeric / nil yield real numeric NaN so downstream arithmetic
590
738
  # propagates correctly (`Math.floor(NaN) === NaN`).
591
739
  def number(value)
592
- return Float::NAN if value.nil?
740
+ return Float::NAN if BarefootJS.nullish?(value)
593
741
  return value ? 1 : 0 if value.is_a?(TrueClass) || value.is_a?(FalseClass)
594
742
  return value if value.is_a?(Numeric)
595
743
  return Float(value.strip) if value.is_a?(String) && value.strip =~ NUMERIC_STRING_RE
@@ -597,18 +745,20 @@ module BarefootJS
597
745
  Float::NAN
598
746
  end
599
747
 
748
+ # The `Math` helpers coerce through JS ToNumber (`null` is 0, `undefined`
749
+ # NaN), as `Math.floor(null)` is 0.
600
750
  def floor(value)
601
- n = number(value)
751
+ n = js_number(value)
602
752
  finite_number?(n) ? n.floor : n
603
753
  end
604
754
 
605
755
  def ceil(value)
606
- n = number(value)
756
+ n = js_number(value)
607
757
  finite_number?(n) ? n.ceil : n
608
758
  end
609
759
 
610
760
  def round(value)
611
- n = number(value)
761
+ n = js_number(value)
612
762
  finite_number?(n) ? (n + 0.5).floor : n
613
763
  end
614
764
 
@@ -617,8 +767,8 @@ module BarefootJS
617
767
  # may return a plain Integer (no `#nan?`), so guard like
618
768
  # `finite_number?` above rather than calling `#nan?` unconditionally.
619
769
  def min(a, b)
620
- x = number(a)
621
- y = number(b)
770
+ x = js_number(a)
771
+ y = js_number(b)
622
772
  return x if nan_number?(x)
623
773
  return y if nan_number?(y)
624
774
 
@@ -626,8 +776,8 @@ module BarefootJS
626
776
  end
627
777
 
628
778
  def max(a, b)
629
- x = number(a)
630
- y = number(b)
779
+ x = js_number(a)
780
+ y = js_number(b)
631
781
  return x if nan_number?(x)
632
782
  return y if nan_number?(y)
633
783
 
@@ -636,7 +786,7 @@ module BarefootJS
636
786
 
637
787
  # `Math.abs()` (#2168 math-methods).
638
788
  def abs(value)
639
- n = number(value)
789
+ n = js_number(value)
640
790
  nan_number?(n) ? n : n.abs
641
791
  end
642
792
 
@@ -835,9 +985,8 @@ module BarefootJS
835
985
  return recv.any? { |item| Evaluator.same_value_zero?(item, elem) } if recv.is_a?(Array)
836
986
  return false if recv.is_a?(Hash)
837
987
 
838
- s = recv.nil? ? '' : string(recv)
839
- needle = elem.nil? ? '' : string(elem)
840
- s.include?(needle)
988
+ # The needle is JS ToString'd (`"anullb".includes(null)` is true).
989
+ string(recv).include?(js_string(elem))
841
990
  end
842
991
 
843
992
  # `.filter(fn)` / `.every(fn)` / `.some(fn)` / `.find(fn)` /
@@ -864,10 +1013,12 @@ module BarefootJS
864
1013
  recv.any? { |item| pred.call(item) }
865
1014
  end
866
1015
 
1016
+ # A miss is `undefined`, as JS `.find()` gives.
867
1017
  def find(recv, pred)
868
- return nil unless recv.is_a?(Array)
1018
+ return UNDEF unless recv.is_a?(Array)
869
1019
 
870
- recv.find { |item| pred.call(item) }
1020
+ recv.each { |item| return item if pred.call(item) }
1021
+ UNDEF
871
1022
  end
872
1023
 
873
1024
  def find_index(recv, pred)
@@ -878,10 +1029,10 @@ module BarefootJS
878
1029
  end
879
1030
 
880
1031
  def find_last(recv, pred)
881
- return nil unless recv.is_a?(Array)
1032
+ return UNDEF unless recv.is_a?(Array)
882
1033
 
883
1034
  recv.reverse_each { |item| return item if pred.call(item) }
884
- nil
1035
+ UNDEF
885
1036
  end
886
1037
 
887
1038
  def find_last_index(recv, pred)
@@ -893,20 +1044,21 @@ module BarefootJS
893
1044
 
894
1045
  # `String.prototype.toLowerCase()` / `.toUpperCase()`.
895
1046
  def lc(s)
896
- s.nil? ? '' : string(s).downcase
1047
+ string(s).downcase
897
1048
  end
898
1049
 
899
1050
  def uc(s)
900
- s.nil? ? '' : string(s).upcase
1051
+ string(s).upcase
901
1052
  end
902
1053
 
903
- # `Array.prototype.join(sep)` with JS semantics: separator defaults to
904
- # ",", undefined/null elements render as empty.
905
- def join(recv, sep = nil)
1054
+ # `Array.prototype.join(sep)` with JS semantics: an omitted or
1055
+ # `undefined` separator is ",", any other one is ToString'd (`null` joins
1056
+ # with "null"); undefined/null elements render as empty.
1057
+ def join(recv, sep = OMITTED)
906
1058
  return '' unless recv.is_a?(Array)
907
1059
 
908
- sep = ',' if sep.nil?
909
- recv.map { |el| string(el) }.join(sep)
1060
+ sep_s = omitted?(sep) ? ',' : js_string(sep)
1061
+ recv.map { |el| string(el) }.join(sep_s)
910
1062
  end
911
1063
 
912
1064
  # `.length` works on both arrays (element count) and strings. The
@@ -916,64 +1068,24 @@ module BarefootJS
916
1068
  # Plane (astral, U+10000-U+10FFFF -- e.g. '👍') is a surrogate PAIR in
917
1069
  # UTF-16, so it counts as 2, not 1; '日本語' is 3 either way (BMP-only).
918
1070
  # An object's `.length` is its own `length` property (`{ length: 3 }`),
919
- # nil when it has none (#3449).
1071
+ # `undefined` when it has none (#3449).
920
1072
  def length(recv)
921
1073
  return recv.length if recv.is_a?(Array)
922
- return recv.key?(:length) ? recv[:length] : recv['length'] if recv.is_a?(Hash)
923
- return 0 if recv.nil?
1074
+ return Evaluator.index_value(recv, :length) if recv.is_a?(Hash)
1075
+ return 0 if BarefootJS.nullish?(recv)
924
1076
 
925
1077
  string(recv).each_char.sum { |c| c.ord > 0xFFFF ? 2 : 1 }
926
1078
  end
927
1079
 
928
1080
  # Runtime-polymorphic element/key access for `arr[index]` /
929
- # `hash[key]` (`emitIndexAccessRuby`, expr/operand.ts). Row hashes
930
- # deserialize with `symbolize_names: true`, so a dynamic key whose
931
- # runtime value is a String (e.g. a destructured `.map()` param used
932
- # as a key, `tone[k]`) misses a Symbol-keyed Hash outright -- and the
933
- # shared analyzer can't tell at compile time whether an index will
934
- # turn out to be a string key or a numeric index (it types a
935
- # destructured param `{kind:'unknown'}`), so no compile-time branch
936
- # can pick the right access form (#2491). Mirrors `getFieldValue`'s
937
- # (Go adapter, bf.go) case-tolerant lookup and Twig's `attribute()`:
938
- # for a Hash, try the key as-is, then as a Symbol, then as a String;
939
- # for an Array, index numerically; anything else has no lookup to
940
- # perform.
1081
+ # `hash[key]` (`emitIndexAccessRuby`, expr/operand.ts). A dynamic key's
1082
+ # shape is only known at run time (#2491), so this dispatches on the
1083
+ # receiver's runtime class. It is the shared evaluator's `index_value`,
1084
+ # so a template read and a callback read share one JS ToPropertyKey
1085
+ # implementation (spec/js-primitive-semantics.md, "ToPropertyKey and
1086
+ # index read").
941
1087
  def get(collection, key)
942
- return nil if key.nil?
943
-
944
- case collection
945
- when Hash
946
- return collection[key] if collection.key?(key)
947
-
948
- sym = key.to_s.to_sym
949
- return collection[sym] if sym && collection.key?(sym)
950
-
951
- str = key.to_s
952
- return collection[str] if collection.key?(str)
953
-
954
- nil
955
- when Array
956
- # Only an INTEGRAL index reads an element. `key.to_i` would be
957
- # wrong on both ends: it coerces a non-numeric String to 0
958
- # (`arr["nope"]` must be nil, not the first element) and it
959
- # truncates a fractional number (JS `arr[1.2]` is a property
960
- # lookup, i.e. undefined -- not index 1).
961
- idx =
962
- case key
963
- when Integer then key
964
- when Numeric then (key % 1).zero? ? key.to_i : nil
965
- when String then (key =~ /\A(?:0|[1-9]\d*)\z/ ? key.to_i : nil)
966
- end
967
- return nil if idx.nil?
968
-
969
- # JS-semantics negative index is "not found" (`arr[-1] ===
970
- # undefined`), NOT Ruby's native from-the-end wraparound -- guard
971
- # it explicitly so this stays a superset of bracket access rather
972
- # than a divergent one.
973
- return nil if idx.negative?
974
-
975
- collection[idx]
976
- end
1088
+ Evaluator.index_value(collection, key)
977
1089
  end
978
1090
 
979
1091
  # `isValidElement(x)` -- the framework "is this a renderable element (not
@@ -1087,25 +1199,19 @@ module BarefootJS
1087
1199
  array_index_of(recv, elem, true)
1088
1200
  end
1089
1201
 
1090
- # `Array.prototype.at(i)` -- negative indices count from the end;
1091
- # out-of-bounds -> nil (renders as '' via `h`, matching JS `undefined`).
1092
- # A String receiver is indexed in UTF-16 code units (#3613). Half of a
1093
- # surrogate pair, a lone surrogate in JS, comes back as U+FFFD: a
1094
- # UTF-8 Ruby String can't hold one, so the halves compare equal and
1095
- # don't rejoin (limitation `string-at-lone-surrogate`).
1096
- def at(recv, i)
1202
+ # `Array.prototype.at(i)` -- negative indices count from the end; the
1203
+ # index is ToIntegerOrInfinity'd, so an omitted, `undefined` or `null`
1204
+ # one reads element 0; out-of-bounds -> `undefined`. A String receiver
1205
+ # is indexed in UTF-16 code units (#3613). Half of a surrogate pair, a
1206
+ # lone surrogate in JS, comes back as U+FFFD: a UTF-8 Ruby String can't
1207
+ # hold one, so the halves compare equal and don't rejoin (limitation
1208
+ # `string-at-lone-surrogate`).
1209
+ def at(recv, i = OMITTED)
1097
1210
  return utf16_at(recv, i) if recv.is_a?(String)
1098
- return nil unless recv.is_a?(Array)
1099
- return nil if i.nil?
1100
-
1101
- idx = i.to_i
1102
- len = recv.length
1103
- return nil if len.zero?
1211
+ return UNDEF unless recv.is_a?(Array)
1104
1212
 
1105
- idx = len + idx if idx.negative?
1106
- return nil if idx.negative? || idx >= len
1107
-
1108
- recv[idx]
1213
+ idx = relative_index(i, recv.length)
1214
+ idx.nil? ? UNDEF : recv[idx]
1109
1215
  end
1110
1216
 
1111
1217
  # `Array.prototype.concat(other)` -- merges two arrays in order into a
@@ -1127,22 +1233,17 @@ module BarefootJS
1127
1233
  # a UTF-8-encoded string, matching JS except for astral-plane input
1128
1234
  # (the same divergence boundary every other adapter's pad/trim
1129
1235
  # helpers already accept).
1130
- def slice(recv, start, end_ = nil)
1236
+ # Both bounds are ToIntegerOrInfinity'd (`null` is 0); an omitted or
1237
+ # `undefined` end is the length.
1238
+ def slice(recv, start = OMITTED, end_ = OMITTED)
1131
1239
  return [] unless recv.is_a?(Array) || recv.is_a?(String)
1132
1240
 
1133
1241
  empty = recv.is_a?(String) ? '' : []
1134
1242
  len = recv.length
1135
1243
  return empty if len.zero?
1136
1244
 
1137
- s = start.nil? ? 0 : start.to_i
1138
- s = len + s if s.negative?
1139
- s = 0 if s.negative?
1140
- s = len if s > len
1141
-
1142
- e = end_.nil? ? len : end_.to_i
1143
- e = len + e if e.negative?
1144
- e = 0 if e.negative?
1145
- e = len if e > len
1245
+ s = clamp_relative(to_integer_or_infinity(start), len)
1246
+ e = omitted?(end_) ? len : clamp_relative(to_integer_or_infinity(end_), len)
1146
1247
 
1147
1248
  return empty if s >= e
1148
1249
 
@@ -1192,6 +1293,9 @@ module BarefootJS
1192
1293
  # value to `0` -- and only then delegates to `flat`'s recursion. Mirrors
1193
1294
  # Go's `FlatDynamicDepth`/`coerceFlatDepth` (adapter-go-template/runtime/bf.go).
1194
1295
  def flat_dynamic(recv, depth)
1296
+ # An `undefined` depth is the default, 1; `null` coerces to 0.
1297
+ return flat(recv, 1) if omitted?(depth)
1298
+
1195
1299
  flat(recv, coerce_flat_depth(depth))
1196
1300
  end
1197
1301
 
@@ -1221,7 +1325,7 @@ module BarefootJS
1221
1325
 
1222
1326
  # `String.prototype.trim()`.
1223
1327
  def trim(recv)
1224
- return '' if recv.nil? || recv.is_a?(Array) || recv.is_a?(Hash)
1328
+ return '' if BarefootJS.nullish?(recv) || recv.is_a?(Array) || recv.is_a?(Hash)
1225
1329
 
1226
1330
  string(recv).gsub(/\A\p{Space}+|\p{Space}+\z/, '')
1227
1331
  end
@@ -1230,25 +1334,27 @@ module BarefootJS
1230
1334
  # siblings of `trim` above (#2183 follow-up), same `\p{Space}` regex
1231
1335
  # restricted to one side.
1232
1336
  def trim_start(recv)
1233
- return '' if recv.nil? || recv.is_a?(Array) || recv.is_a?(Hash)
1337
+ return '' if BarefootJS.nullish?(recv) || recv.is_a?(Array) || recv.is_a?(Hash)
1234
1338
 
1235
1339
  string(recv).sub(/\A\p{Space}+/, '')
1236
1340
  end
1237
1341
 
1238
1342
  def trim_end(recv)
1239
- return '' if recv.nil? || recv.is_a?(Array) || recv.is_a?(Hash)
1343
+ return '' if BarefootJS.nullish?(recv) || recv.is_a?(Array) || recv.is_a?(Hash)
1240
1344
 
1241
1345
  string(recv).sub(/\p{Space}+\z/, '')
1242
1346
  end
1243
1347
 
1244
1348
  # `Number.prototype.toFixed(digits)` -- fixed-decimal string with
1245
1349
  # zero-padding, rounding half toward +Infinity (matching `round`).
1246
- def to_fixed(value, digits = 0)
1350
+ # An omitted or `undefined` digit count is 0, as ToIntegerOrInfinity
1351
+ # makes `null` too.
1352
+ def to_fixed(value, digits = OMITTED)
1247
1353
  n = number(value)
1248
1354
  return 'NaN' if n.respond_to?(:nan?) && n.nan?
1249
1355
  return n.negative? ? '-Infinity' : 'Infinity' if n.respond_to?(:infinite?) && n.infinite?
1250
1356
 
1251
- digits = 0 if digits.nil? || digits.negative?
1357
+ digits = [to_integer_or_infinity(digits), 0].max
1252
1358
  factor = 10.0**digits
1253
1359
  rounded = (n * factor + 0.5).floor
1254
1360
  format("%.#{digits}f", rounded / factor)
@@ -1259,35 +1365,35 @@ module BarefootJS
1259
1365
  # string in a single-element Array; trailing empty fields are kept
1260
1366
  # (JS parity -- Ruby's `String#split(str, -1)` already matches this,
1261
1367
  # and (unlike a Regexp) a String separator is matched literally).
1262
- def split(recv, sep = nil, limit = nil)
1263
- s = (recv.nil? || recv.is_a?(Array) || recv.is_a?(Hash)) ? '' : string(recv)
1368
+ # An omitted or `undefined` separator yields `[s]`; any other one is
1369
+ # ToString'd (`null` splits on "null"). An omitted or `undefined` limit
1370
+ # is unbounded; any other one is ToUint32'd (`null` is 0).
1371
+ def split(recv, sep = OMITTED, limit = OMITTED)
1372
+ s = (recv.is_a?(Array) || recv.is_a?(Hash)) ? '' : string(recv)
1264
1373
  parts =
1265
- if sep.nil?
1374
+ if omitted?(sep)
1266
1375
  [s]
1267
- elsif string(sep).empty?
1268
- s.chars
1269
- elsif s.empty?
1270
- ['']
1271
1376
  else
1272
- s.split(string(sep), -1)
1273
- end
1274
- unless limit.nil?
1275
- n = limit.to_i
1276
- if n.zero?
1277
- parts = []
1278
- elsif n.positive? && n < parts.length
1279
- parts = parts[0...n]
1377
+ sep_s = js_string(sep)
1378
+ if sep_s.empty?
1379
+ s.chars
1380
+ elsif s.empty?
1381
+ ['']
1382
+ else
1383
+ s.split(sep_s, -1)
1384
+ end
1280
1385
  end
1281
- end
1386
+ parts = parts[0, to_uint32(limit)] unless omitted?(limit)
1282
1387
  parts
1283
1388
  end
1284
1389
 
1285
1390
  # `String.prototype.startsWith(prefix, position?)`.
1286
- def starts_with(recv, prefix, position = nil)
1287
- s = recv.nil? ? '' : string(recv)
1288
- p = prefix.nil? ? '' : string(prefix)
1391
+ # An omitted or `undefined` position is 0; `null` is 0 too.
1392
+ def starts_with(recv, prefix, position = OMITTED)
1393
+ s = string(recv)
1394
+ p = js_string(prefix)
1289
1395
  # `position` counts UTF-16 code units, like JS (#3613).
1290
- unless position.nil?
1396
+ unless omitted?(position)
1291
1397
  units = utf16_units(s)
1292
1398
  return utf16_has_at?(units, utf16_units(p), clamp_index(to_integer_or_infinity(position), units.length))
1293
1399
  end
@@ -1295,11 +1401,12 @@ module BarefootJS
1295
1401
  end
1296
1402
 
1297
1403
  # `String.prototype.endsWith(suffix, endPosition?)`.
1298
- def ends_with(recv, suffix, end_position = nil)
1299
- s = recv.nil? ? '' : string(recv)
1300
- x = suffix.nil? ? '' : string(suffix)
1404
+ # An omitted or `undefined` endPosition is the length; `null` is 0.
1405
+ def ends_with(recv, suffix, end_position = OMITTED)
1406
+ s = string(recv)
1407
+ x = js_string(suffix)
1301
1408
  # `endPosition` counts UTF-16 code units, like JS (#3613).
1302
- unless end_position.nil?
1409
+ unless omitted?(end_position)
1303
1410
  units = utf16_units(s)
1304
1411
  needle = utf16_units(x)
1305
1412
  return utf16_has_at?(units, needle, clamp_index(to_integer_or_infinity(end_position), units.length) - needle.length)
@@ -1311,9 +1418,9 @@ module BarefootJS
1311
1418
  # form only, replacing the FIRST occurrence, literally (no regex
1312
1419
  # metacharacters, no `$1`-style replacement interpolation).
1313
1420
  def replace(recv, pattern, replacement)
1314
- s = recv.nil? ? '' : string(recv)
1315
- o = pattern.nil? ? '' : string(pattern)
1316
- n = replacement.nil? ? '' : string(replacement)
1421
+ s = string(recv)
1422
+ o = js_string(pattern)
1423
+ n = js_string(replacement)
1317
1424
  return n + s if o.empty?
1318
1425
 
1319
1426
  idx = s.index(o)
@@ -1334,9 +1441,9 @@ module BarefootJS
1334
1441
  # first and after the last character (`"abc".replaceAll("", "X")` ->
1335
1442
  # "XaXbXcX"), matching JS.
1336
1443
  def replace_all(recv, pattern, replacement)
1337
- s = recv.nil? ? '' : string(recv)
1338
- o = pattern.nil? ? '' : string(pattern)
1339
- n = replacement.nil? ? '' : string(replacement)
1444
+ s = string(recv)
1445
+ o = js_string(pattern)
1446
+ n = js_string(replacement)
1340
1447
  return ([''] + s.chars + ['']).join(n) if o.empty?
1341
1448
 
1342
1449
  # `+''` (not the frozen `''` literal under frozen_string_literal)
@@ -1396,19 +1503,21 @@ module BarefootJS
1396
1503
  # `String.prototype.repeat(n)` -- a count <= 0 degrades to '' rather
1397
1504
  # than raising (JS throws RangeError for negative counts; SSR
1398
1505
  # templates degrade instead of dying mid-render).
1399
- def repeat(recv, count)
1400
- s = recv.nil? ? '' : string(recv)
1401
- n = count.nil? ? 0 : count.to_i
1506
+ def repeat(recv, count = OMITTED)
1507
+ s = string(recv)
1508
+ n = to_integer_or_infinity(count)
1402
1509
  n.positive? ? s * n : ''
1403
1510
  end
1404
1511
 
1405
- # `String.prototype.padStart` / `padEnd`.
1406
- def pad_start(recv, target, pad_str = nil)
1407
- pad_string(recv.nil? ? '' : string(recv), target, pad_str, true)
1512
+ # `String.prototype.padStart` / `padEnd`. An omitted or `undefined` pad
1513
+ # string is a space; any other one is ToString'd (`null` pads with
1514
+ # "null").
1515
+ def pad_start(recv, target = OMITTED, pad_str = OMITTED)
1516
+ pad_string(string(recv), target, pad_str, true)
1408
1517
  end
1409
1518
 
1410
- def pad_end(recv, target, pad_str = nil)
1411
- pad_string(recv.nil? ? '' : string(recv), target, pad_str, false)
1519
+ def pad_end(recv, target = OMITTED, pad_str = OMITTED)
1520
+ pad_string(string(recv), target, pad_str, false)
1412
1521
  end
1413
1522
 
1414
1523
  # `Array.prototype.sort(cmp)` / `.toSorted(cmp)` -- fixed comparator
@@ -1429,7 +1538,10 @@ module BarefootJS
1429
1538
  end
1430
1539
  return recv.dup if spec.empty?
1431
1540
 
1432
- decorated = recv.each_with_index.map do |item, idx|
1541
+ # JS moves every `undefined` element to the end without handing it to
1542
+ # the comparator.
1543
+ defined, tail = recv.partition { |item| !BarefootJS.undefined?(item) }
1544
+ decorated = defined.each_with_index.map do |item, idx|
1433
1545
  keys = spec.map { |sp| sp[:key_kind] == 'field' ? field_value(item, sp[:key]) : item }
1434
1546
  [keys, item, idx]
1435
1547
  end
@@ -1446,7 +1558,7 @@ module BarefootJS
1446
1558
  result.zero? ? (x[2] <=> y[2]) : result
1447
1559
  end
1448
1560
 
1449
- sorted.map { |pair| pair[1] }
1561
+ sorted.map { |pair| pair[1] } + tail
1450
1562
  end
1451
1563
 
1452
1564
  # Fold an array into a scalar via the arithmetic-fold catalogue
@@ -1557,7 +1669,7 @@ module BarefootJS
1557
1669
  next if key_s == 'children'
1558
1670
 
1559
1671
  val = bag[key]
1560
- next if val.nil?
1672
+ next if BarefootJS.nullish?(val)
1561
1673
 
1562
1674
  if val.is_a?(TrueClass) || val.is_a?(FalseClass)
1563
1675
  next unless val
@@ -1587,6 +1699,41 @@ module BarefootJS
1587
1699
 
1588
1700
  private
1589
1701
 
1702
+ # JS ToNumber for a helper argument: `Evaluator.to_number`, with a value
1703
+ # outside its subset (an array or object) reading NaN instead of raising
1704
+ # mid-render.
1705
+ def js_number(value)
1706
+ Evaluator.to_number(value)
1707
+ rescue Evaluator::EvalUnsupported
1708
+ Float::NAN
1709
+ end
1710
+
1711
+ # JS ToString for a helper argument (a needle, a separator, a pattern):
1712
+ # `Evaluator.to_string`, which spells `null` / `undefined` as JS does.
1713
+ def js_string(value)
1714
+ Evaluator.to_string(value)
1715
+ rescue Evaluator::EvalUnsupported
1716
+ string(value)
1717
+ end
1718
+
1719
+ # Whether an optional argument takes its JS default: omitted or
1720
+ # `undefined`, never `null` (JS coerces an explicit `null` like any
1721
+ # other value: `[1, 2].slice(0, null)` is `[]`).
1722
+ def omitted?(value)
1723
+ OMITTED.equal?(value) || BarefootJS.undefined?(value)
1724
+ end
1725
+
1726
+ # `value` as `JSON.stringify` sees it: a member holding `undefined` is
1727
+ # dropped and an `undefined` element is `null`, at any depth. A host's
1728
+ # `encode_json` never receives `UNDEF`.
1729
+ def json_ready(value)
1730
+ case value
1731
+ when Hash then value.each_with_object({}) { |(k, v), out| out[k] = json_ready(v) unless BarefootJS.undefined?(v) }
1732
+ when Array then value.map { |v| BarefootJS.undefined?(v) ? nil : json_ready(v) }
1733
+ else value
1734
+ end
1735
+ end
1736
+
1590
1737
  def finite_number?(n)
1591
1738
  !(n.respond_to?(:nan?) && n.nan?) && !(n.respond_to?(:infinite?) && n.infinite?)
1592
1739
  end
@@ -1631,14 +1778,14 @@ module BarefootJS
1631
1778
  end
1632
1779
 
1633
1780
  def style_to_css(value)
1634
- return nil if value.nil?
1781
+ return nil if BarefootJS.nullish?(value)
1635
1782
  unless value.is_a?(Hash)
1636
1783
  s = string(value)
1637
1784
  return s.empty? ? nil : s
1638
1785
  end
1639
1786
  parts = value.keys.sort_by(&:to_s).filter_map do |key|
1640
1787
  v = value[key]
1641
- next if v.nil?
1788
+ next if BarefootJS.nullish?(v)
1642
1789
 
1643
1790
  prop = key.to_s.gsub(/([A-Z])/) { "-#{Regexp.last_match(1).downcase}" }
1644
1791
  "#{prop}:#{string(v)}"
@@ -1657,8 +1804,13 @@ module BarefootJS
1657
1804
  escaped.tr(' ', '+')
1658
1805
  end
1659
1806
 
1807
+ # A row field's value: JS `item.key`, `undefined` when the row has no
1808
+ # such field (or is no object).
1660
1809
  def field_value(item, key)
1661
- item.is_a?(Hash) ? item[field_key(key)] : nil
1810
+ return UNDEF unless item.is_a?(Hash)
1811
+
1812
+ k = field_key(key)
1813
+ item.key?(k) ? item[k] : UNDEF
1662
1814
  end
1663
1815
 
1664
1816
  def field_key(key)
@@ -1672,7 +1824,7 @@ module BarefootJS
1672
1824
  end
1673
1825
 
1674
1826
  def numeric_value(v)
1675
- return 0 if v.nil?
1827
+ return 0 if BarefootJS.nullish?(v)
1676
1828
  return v if v.is_a?(Numeric)
1677
1829
  return Float(v.strip) if v.is_a?(String) && v.strip =~ NUMERIC_STRING_RE
1678
1830
 
@@ -1730,14 +1882,18 @@ module BarefootJS
1730
1882
  def compare_sort_key(av, bv, compare_type)
1731
1883
  case compare_type
1732
1884
  when 'string'
1733
- (av.nil? ? '' : string(av)) <=> (bv.nil? ? '' : string(bv))
1885
+ string(av) <=> string(bv)
1734
1886
  when 'auto'
1735
1887
  if numeric_like?(av) && numeric_like?(bv)
1736
1888
  numeric_value(av) <=> numeric_value(bv)
1737
1889
  else
1738
- (av.nil? ? '' : string(av)) <=> (bv.nil? ? '' : string(bv))
1890
+ string(av) <=> string(bv)
1739
1891
  end
1740
1892
  else
1893
+ # `a - b` over an `undefined` key is NaN, which the sort reads as
1894
+ # "equal".
1895
+ return 0 if BarefootJS.undefined?(av) || BarefootJS.undefined?(bv)
1896
+
1741
1897
  numeric_value(av) <=> numeric_value(bv)
1742
1898
  end
1743
1899
  end
@@ -1748,12 +1904,14 @@ module BarefootJS
1748
1904
  indices = reverse ? (recv.length - 1).downto(0).to_a : (0...recv.length).to_a
1749
1905
  indices.each do |i|
1750
1906
  item = recv[i]
1751
- if item.nil?
1752
- return i if elem.nil?
1907
+ # Strict equality tells the nils apart: `null` matches only `null`,
1908
+ # `undefined` only `undefined`.
1909
+ if BarefootJS.nullish?(item) || BarefootJS.nullish?(elem)
1910
+ return i if item.equal?(elem)
1753
1911
 
1754
1912
  next
1755
1913
  end
1756
- return i if !elem.nil? && item == elem
1914
+ return i if item == elem
1757
1915
  end
1758
1916
  -1
1759
1917
  end
@@ -1772,7 +1930,7 @@ module BarefootJS
1772
1930
  # the caller's range check treats it as out of range instead of
1773
1931
  # `Float#to_i` raising FloatDomainError.
1774
1932
  def to_integer_or_infinity(value)
1775
- n = number(value)
1933
+ n = js_number(value)
1776
1934
  return 0 if n.respond_to?(:nan?) && n.nan?
1777
1935
  return MAX_SAFE_INDEX if n >= MAX_SAFE_INDEX
1778
1936
  return -MAX_SAFE_INDEX if n <= -MAX_SAFE_INDEX
@@ -1788,7 +1946,7 @@ module BarefootJS
1788
1946
 
1789
1947
  def utf16_index_of(recv, elem, reverse)
1790
1948
  hay = utf16_units(recv)
1791
- needle = utf16_units(string(elem))
1949
+ needle = utf16_units(js_string(elem))
1792
1950
  last = hay.length - needle.length
1793
1951
  indices = reverse ? last.downto(0) : 0.upto(last)
1794
1952
  indices.each { |i| return i if utf16_has_at?(hay, needle, i) }
@@ -1796,17 +1954,37 @@ module BarefootJS
1796
1954
  end
1797
1955
 
1798
1956
  def utf16_at(recv, i)
1799
- return nil if i.nil?
1800
-
1801
1957
  units = utf16_units(recv)
1802
- idx = to_integer_or_infinity(i)
1803
- idx += units.length if idx.negative?
1804
- return nil if idx.negative? || idx >= units.length
1958
+ idx = relative_index(i, units.length)
1959
+ return UNDEF if idx.nil?
1805
1960
 
1806
1961
  u = units[idx]
1807
1962
  (0xD800..0xDFFF).cover?(u) ? "\uFFFD" : [u].pack('U')
1808
1963
  end
1809
1964
 
1965
+ # `Array.prototype.at`'s index: ToIntegerOrInfinity, counted from the
1966
+ # end when negative; nil when it falls outside `[0, length)`.
1967
+ def relative_index(value, length)
1968
+ idx = to_integer_or_infinity(value)
1969
+ idx += length if idx.negative?
1970
+ idx >= 0 && idx < length ? idx : nil
1971
+ end
1972
+
1973
+ # A `slice` bound: counted from the end when negative, clamped to
1974
+ # `[0, length]`.
1975
+ def clamp_relative(idx, length)
1976
+ idx += length if idx.negative?
1977
+ clamp_index(idx, length)
1978
+ end
1979
+
1980
+ # JS `ToUint32` (`split`'s limit): NaN and the infinities are 0.
1981
+ def to_uint32(value)
1982
+ n = js_number(value).to_f
1983
+ return 0 if n.nan? || n.infinite?
1984
+
1985
+ n.truncate % (2**32)
1986
+ end
1987
+
1810
1988
  def clamp_index(n, len)
1811
1989
  n = 0 if n.negative?
1812
1990
  n = len if n > len
@@ -1814,11 +1992,11 @@ module BarefootJS
1814
1992
  end
1815
1993
 
1816
1994
  def pad_string(s, target, pad_str, at_start)
1817
- pad_str = pad_str.nil? ? ' ' : string(pad_str)
1995
+ pad_str = omitted?(pad_str) ? ' ' : js_string(pad_str)
1818
1996
  return s if pad_str.empty?
1819
1997
 
1820
1998
  len = s.length
1821
- t = target.nil? ? 0 : target.to_i
1999
+ t = to_integer_or_infinity(target)
1822
2000
  return s if len >= t
1823
2001
 
1824
2002
  need = t - len