barefoot_js 0.40.1 → 0.40.2

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 949fd035bff68603576788c43d9f94e354632d2c9e23ced564a5a22c83d901d4
4
- data.tar.gz: b01b798e43b952abbe9728e4bfdeeb58922dd93718ded181d649e79233b3c472
3
+ metadata.gz: 3e7609794c40dfdc1fd9ecd6b973d59639bc45b257b2879061c442cbeda5f291
4
+ data.tar.gz: ecf9220ef1060aa926d4351278a74871f0e714665255aa5725231df5558d50d4
5
5
  SHA512:
6
- metadata.gz: 6a93a544672bd9897f2a3c995ccb15490c1c932837c088f1b957198dd671f35137c6f79fc6ffb72aed8001c787d992021573000cc922b0a5d36d801337a83344
7
- data.tar.gz: 377c648e844b16fe943e8062fd004e8c06b6e8b2e8fcc019b444657fb09d49a0634ac1ac9a6e8fe08746b0a670e93c1f586b2de857df9683f5a3f012287a92f3
6
+ metadata.gz: 5f969c14e65bed747637648df2b1f69b3f81d39738ee5b1efe079b8c78923f3f271d1e7fd867638997e6e6367e35313b8f036d6b59fa27b5fcfd0d696547ea0c
7
+ data.tar.gz: 206dec8621e2651be6ad29f9f2597abbeb4302ae0adf2666f419e7cf1bc587d60583e225b88b79d189743e7713a5c717ae15dcab9f2c3dad7f3fde371c723027
@@ -180,6 +180,12 @@ module BarefootJS
180
180
  return number_to_string(v) if v.is_a?(Numeric)
181
181
  return v ? 'true' : 'false' if v.is_a?(TrueClass) || v.is_a?(FalseClass)
182
182
  return 'null' if v.nil?
183
+ # Array.prototype.toString is join(","): a nil element prints as "",
184
+ # and a nested array flattens through its own join. A plain object
185
+ # prints as "[object Object]".
186
+ return v.map { |el| el.nil? ? '' : to_string(el) }.join(',') if v.is_a?(Array)
187
+ return '[object Object]' if v.is_a?(Hash)
188
+
183
189
  raise EvalUnsupported, "cannot coerce #{v.class} to string"
184
190
  end
185
191
 
@@ -199,13 +205,17 @@ module BarefootJS
199
205
  # Number <-> String helpers
200
206
  # ---------------------------------------------------------------------
201
207
 
202
- HEX_STRING_RE = /\A0[xX][0-9a-fA-F]+\z/
208
+ # JS's NonDecimalIntegerLiteral: an unsigned `0x` / `0o` / `0b` integer.
209
+ RADIX_STRING_RES = { 16 => /\A0[xX][0-9a-fA-F]+\z/, 8 => /\A0[oO][0-7]+\z/, 2 => /\A0[bB][01]+\z/ }.freeze
203
210
  NUMERIC_STRING_RE = /\A[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?\z/
204
211
 
205
212
  def parse_numeric_string(t)
206
213
  return Float::INFINITY if t == 'Infinity' || t == '+Infinity'
207
214
  return -Float::INFINITY if t == '-Infinity'
208
- return Integer(t, 16) if t =~ HEX_STRING_RE
215
+ # JS rounds the mathematical value once to the nearest double, ties to
216
+ # even (#3824 step 3); Ruby's exact Integer#to_f does the same, and a
217
+ # value past the largest double is Infinity.
218
+ RADIX_STRING_RES.each { |base, re| return Integer(t, base).to_f if t =~ re }
209
219
 
210
220
  if t =~ NUMERIC_STRING_RE
211
221
  # Ruby's Float() rejects a trailing decimal point ("5.", "5.e3"),
@@ -309,11 +319,12 @@ module BarefootJS
309
319
  def binary(op, l, r)
310
320
  case op
311
321
  when '+'
312
- # JS `+`: string concatenation once either operand is a string,
313
- # numeric addition otherwise.
314
- return to_string(l) + to_string(r) if l.is_a?(String) || r.is_a?(String)
322
+ # JS `+`: string concatenation once either operand is a string after
323
+ # ToPrimitive (an array or object converts to its ToString), numeric
324
+ # addition otherwise.
325
+ return to_string(l) + to_string(r) if concatenates?(l) || concatenates?(r)
315
326
 
316
- to_number(l) + to_number(r)
327
+ add(to_number(l), to_number(r))
317
328
  when '-' then to_number(l) - to_number(r)
318
329
  when '*' then to_number(l) * to_number(r)
319
330
  when '/' then divide(l, r)
@@ -325,14 +336,31 @@ module BarefootJS
325
336
  raise EvalUnsupported, "binary operator '#{op}' is not in the evaluator subset"
326
337
  end
327
338
  end
328
- private_class_method :binary
339
+
340
+ # JS string order, by UTF-16 code unit. Ruby's String#<=> compares UTF-8
341
+ # bytes, which is code point order: the two differ where an astral
342
+ # character (whose leading surrogate is 0xD800-0xDBFF) meets a BMP
343
+ # character above the surrogates ("😀" < "。" is true in JS). Big-endian
344
+ # UTF-16 bytes compare in code-unit order.
345
+ def compare_utf16(l, r)
346
+ return l <=> r if l.ascii_only? && r.ascii_only?
347
+
348
+ utf16_be(l) <=> utf16_be(r)
349
+ end
350
+
351
+ def utf16_be(s)
352
+ s = s.dup.force_encoding(Encoding::UTF_8) if s.encoding == Encoding::BINARY
353
+ s.encode(Encoding::UTF_16BE, invalid: :replace, undef: :replace).b
354
+ end
355
+
356
+ private_class_method :compare_utf16, :utf16_be
329
357
 
330
358
  def relational(op, l, r)
331
359
  # JS Abstract Relational Comparison: both strings -> compare by code
332
360
  # unit; otherwise coerce both to numbers (a NaN operand is false).
333
361
  c =
334
362
  if l.is_a?(String) && r.is_a?(String)
335
- l < r ? -1 : (l > r ? 1 : 0)
363
+ compare_utf16(l, r)
336
364
  else
337
365
  ln = to_number(l).to_f
338
366
  rn = to_number(r).to_f
@@ -348,7 +376,6 @@ module BarefootJS
348
376
  else false
349
377
  end
350
378
  end
351
- private_class_method :relational
352
379
 
353
380
  def strict_eq(l, r)
354
381
  if non_primitive?(l) || non_primitive?(r)
@@ -362,7 +389,6 @@ module BarefootJS
362
389
 
363
390
  false
364
391
  end
365
- private_class_method :strict_eq
366
392
 
367
393
  def non_primitive?(v)
368
394
  v.is_a?(Array) || v.is_a?(Hash)
@@ -428,12 +454,33 @@ module BarefootJS
428
454
  def unary(op, v)
429
455
  case op
430
456
  when '!' then !truthy?(v)
431
- when '-' then -to_number(v)
457
+ when '-' then negate(to_number(v))
432
458
  when '+' then to_number(v)
433
459
  else raise EvalUnsupported, "unary operator '#{op}' is not in the evaluator subset"
434
460
  end
435
461
  end
436
- private_class_method :unary
462
+
463
+ def concatenates?(v)
464
+ v.is_a?(String) || v.is_a?(Array) || v.is_a?(Hash)
465
+ end
466
+ private_class_method :concatenates?
467
+
468
+ # add(a, b) -- JS numeric `+`, an IEEE double sum. Two Integers add
469
+ # exactly in Ruby; past 2^53 the exact sum is rounded once to the nearest
470
+ # double, which is what IEEE addition of the two (exactly held) operands
471
+ # gives (`2**53 + 1` is `2**53`).
472
+ def add(a, b)
473
+ sum = a + b
474
+ sum.is_a?(Integer) && sum.abs > 2**53 ? sum.to_f : sum
475
+ end
476
+ private_class_method :add
477
+
478
+ # negate(n) -- JS unary `-` over a number: an Integer zero has no sign, so
479
+ # a zero negates as a Float (`-0.0` from `0`, `0.0` from `-0.0`).
480
+ def negate(n)
481
+ n.zero? ? -n.to_f : -n
482
+ end
483
+ private_class_method :negate
437
484
 
438
485
  # ---------------------------------------------------------------------
439
486
  # Nested `.map`/`.filter` callback calls (#2094) -- the evaluator
@@ -581,23 +628,79 @@ module BarefootJS
581
628
  end
582
629
  private_class_method :read_property
583
630
 
631
+ # JS `obj[index]` in a callback body: `index_value` over a receiver that
632
+ # can be indexed. Reading through null / undefined throws in JS, so it
633
+ # is outside the subset here.
584
634
  def read_index(obj, index)
585
- if obj.is_a?(Array)
586
- f = to_number(index).to_f
587
- return nil unless f.finite? && f == f.to_i
588
-
589
- i = f.to_i
590
- return nil if i.negative? || i >= obj.length
591
-
592
- obj[i]
593
- elsif obj.is_a?(Hash)
594
- read_property(obj, to_string(index))
595
- else
635
+ unless obj.is_a?(Array) || obj.is_a?(Hash) || obj.is_a?(String)
596
636
  raise EvalUnsupported, "cannot index #{obj.nil? ? 'null' : obj.class}"
597
637
  end
638
+
639
+ index_value(obj, index)
598
640
  end
599
641
  private_class_method :read_index
600
642
 
643
+ # index_value(obj, index) -> JS `obj[index]`, shared with the template
644
+ # helper `bf.get` (which delegates here, so a template read and a
645
+ # callback read cannot disagree on a key). The key goes through
646
+ # ToPropertyKey (`to_string`: nil is "null", `-0` is "0", `1.0` is
647
+ # "1"). A Hash reads its own key (Symbol first: rows deserialize with
648
+ # `symbolize_names: true`). An Array, and a String (by UTF-16 code
649
+ # unit), are read only through a canonical array index: "1" reads
650
+ # element 1, while "01", "1e0", "-0", "1.1" and "-1" are ordinary
651
+ # property names (spec/js-primitive-semantics.md, "ToPropertyKey and
652
+ # index read"). Any other receiver reads nil.
653
+ def index_value(obj, index)
654
+ key = property_key(index)
655
+ return nil if key.nil?
656
+
657
+ case obj
658
+ when Hash
659
+ sym = key.to_sym
660
+ return obj[sym] if obj.key?(sym)
661
+
662
+ obj.key?(key) ? obj[key] : nil
663
+ when Array, String
664
+ return nil unless key.match?(/\A(?:0|[1-9][0-9]*)\z/)
665
+
666
+ i = key.to_i
667
+ return utf16_unit_at(obj, i) if obj.is_a?(String)
668
+
669
+ # An index past the end reads nil. Checking before `Array#[]` also
670
+ # keeps an oversized key ("9223372036854775808", 1e20) from raising
671
+ # RangeError: a Bignum cannot be converted to a C long.
672
+ i < obj.length ? obj[i] : nil
673
+ end
674
+ end
675
+
676
+ # JS ToPropertyKey of a primitive key (a Symbol a Ruby caller passes is
677
+ # its name); nil for a key outside the subset (an array or object key),
678
+ # which reads nothing.
679
+ def property_key(index)
680
+ return index.to_s if index.is_a?(Symbol)
681
+
682
+ to_string(index)
683
+ rescue EvalUnsupported
684
+ nil
685
+ end
686
+ private_class_method :property_key
687
+
688
+ # The UTF-16 code unit of `str` at index `i` (JS `str[i]`), or nil past
689
+ # the end. One half of a surrogate pair reads as U+FFFD: a lone
690
+ # surrogate cannot be written out as UTF-8
691
+ # (spec/js-primitive-semantics.md, "Out of scope").
692
+ def utf16_unit_at(str, i)
693
+ pos = 0
694
+ str.each_char do |c|
695
+ width = c.ord > 0xFFFF ? 2 : 1
696
+ return width == 1 ? c : "\uFFFD" if i < pos + width
697
+
698
+ pos += width
699
+ end
700
+ nil
701
+ end
702
+ private_class_method :utf16_unit_at
703
+
601
704
  # ---------------------------------------------------------------------
602
705
  # Evaluator-driven higher-order folds -- the runtime half `bf.rb` calls
603
706
  # into for sort_eval / reduce_eval / filter_eval / etc.
data/lib/barefoot_js.rb CHANGED
@@ -209,6 +209,12 @@ module BarefootJS
209
209
  value ? 'true' : 'false'
210
210
  end
211
211
 
212
+ # A JSX text child's value: JSX renders nothing for a boolean (#3824
213
+ # step 5). Any other value passes through to the text sink.
214
+ def display(value)
215
+ value == true || value == false ? '' : value
216
+ end
217
+
212
218
  def text_start(slot_id)
213
219
  "<!--bf:#{slot_id}-->"
214
220
  end
@@ -509,23 +515,24 @@ module BarefootJS
509
515
 
510
516
  NUMERIC_STRING_RE = /\A\s*[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?\s*\z/.freeze
511
517
 
518
+ # JS `JSON.stringify`. A number is written as JS writes it
519
+ # (`Evaluator.number_to_string`): an integral Float has no `.0`, -0 is
520
+ # `0`, an exponent is unpadded (`-4e-8`, `-4e+21`), and NaN / Infinity
521
+ # are `null`, at any depth (#3787). Ruby's encoder would write `-2.0` /
522
+ # `-4.0e-08` and raise on a non-finite Float. Arrays and Hashes are
523
+ # walked here in insertion order, as `JSON.generate` does; strings and
524
+ # other leaves go through the backend's encoder.
512
525
  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
526
  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
527
+ when Integer, Float
528
+ value.to_f.finite? ? Evaluator.number_to_string(value) : 'null'
529
+ when Array then "[#{value.map { |el| json(el) }.join(',')}]"
530
+ when Hash
531
+ members = value.map { |k, v| "#{backend.encode_json(k.to_s)}:#{json(v)}" }
532
+ "{#{members.join(',')}}"
533
+ else backend.encode_json(value)
526
534
  end
527
535
  end
528
- private :json_unsign_zeros
529
536
 
530
537
  # JS `String(v)` mirror, EXCEPT `nil` renders as '' (not the literal
531
538
  # "null") so an unset prop doesn't surface as literal text in
@@ -585,6 +592,71 @@ module BarefootJS
585
592
  Evaluator.truthy?(value)
586
593
  end
587
594
 
595
+ # Boxes for a value-position JS `l || r` / `l && r` (#3824): the adapter
596
+ # spells `l || r` as `(bf.keep_truthy(l) || [r])[0]` and `l && r` as
597
+ # `(bf.keep_falsy(l) || [r])[0]`. `keep_truthy` is the one-element array
598
+ # `[value]` when `value` is JS-truthy and nil otherwise (`keep_falsy` the
599
+ # reverse), so Ruby's `||` stops at the box exactly when JS returns
600
+ # `value` itself and builds `[r]` only otherwise (the short circuit);
601
+ # `[0]` unboxes the operand. Each operand appears once, so a chain grows
602
+ # linearly.
603
+ def keep_truthy(value)
604
+ Evaluator.truthy?(value) ? [value] : nil
605
+ end
606
+
607
+ def keep_falsy(value)
608
+ Evaluator.truthy?(value) ? nil : [value]
609
+ end
610
+
611
+ # JS primitive helpers (spec/js-primitive-semantics.md, "Operation
612
+ # table"): ToNumber, ToString, `===`, the relational operators, binary
613
+ # `+` and unary `-`. Each delegates to the shared evaluator's primitive
614
+ # of the same operation, so a template helper call and a callback body
615
+ # share one implementation. Unlike `number` and `string` (display
616
+ # helpers: nil -> NaN / ""), nil reads as JS null here (0 / "null").
617
+ def to_number(value)
618
+ Evaluator.to_number(value)
619
+ end
620
+
621
+ def to_string(value)
622
+ Evaluator.to_string(value)
623
+ end
624
+
625
+ # The evaluator refuses a non-primitive `===` operand (its subset
626
+ # contract). A template reaches this helper only with operands the
627
+ # compiler could not type, since it refuses a proven object or array
628
+ # (BF101, #3824 step 8), so an object or array that still arrives here
629
+ # compares by reference, as JS `===` does.
630
+ def strict_eq(left, right)
631
+ Evaluator.strict_eq(left, right)
632
+ rescue Evaluator::EvalUnsupported
633
+ left.equal?(right)
634
+ end
635
+
636
+ def lt(left, right)
637
+ Evaluator.relational('<', left, right)
638
+ end
639
+
640
+ def le(left, right)
641
+ Evaluator.relational('<=', left, right)
642
+ end
643
+
644
+ def gt(left, right)
645
+ Evaluator.relational('>', left, right)
646
+ end
647
+
648
+ def ge(left, right)
649
+ Evaluator.relational('>=', left, right)
650
+ end
651
+
652
+ def plus(left, right)
653
+ Evaluator.binary('+', left, right)
654
+ end
655
+
656
+ def neg(value)
657
+ Evaluator.unary('-', value)
658
+ end
659
+
588
660
  # JS `Number(v)` mirror: numeric / boolean inputs convert as expected;
589
661
  # non-numeric / nil yield real numeric NaN so downstream arithmetic
590
662
  # propagates correctly (`Math.floor(NaN) === NaN`).
@@ -926,54 +998,14 @@ module BarefootJS
926
998
  end
927
999
 
928
1000
  # 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.
1001
+ # `hash[key]` (`emitIndexAccessRuby`, expr/operand.ts). A dynamic key's
1002
+ # shape is only known at run time (#2491), so this dispatches on the
1003
+ # receiver's runtime class. It is the shared evaluator's `index_value`,
1004
+ # so a template read and a callback read share one JS ToPropertyKey
1005
+ # implementation (spec/js-primitive-semantics.md, "ToPropertyKey and
1006
+ # index read").
941
1007
  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
1008
+ Evaluator.index_value(collection, key)
977
1009
  end
978
1010
 
979
1011
  # `isValidElement(x)` -- the framework "is this a renderable element (not
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: barefoot_js
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.40.1
4
+ version: 0.40.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - kobaken