barefoot_js 0.40.2 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3e7609794c40dfdc1fd9ecd6b973d59639bc45b257b2879061c442cbeda5f291
4
- data.tar.gz: ecf9220ef1060aa926d4351278a74871f0e714665255aa5725231df5558d50d4
3
+ metadata.gz: 1facdd75f69a2a25ffc64d5b955ee60ca9e8761928448f2e70820e78384a5649
4
+ data.tar.gz: 30fd742f41f075dc877d4e7f530e5f963f539e285141c84d4205f8a9a4497efe
5
5
  SHA512:
6
- metadata.gz: 5f969c14e65bed747637648df2b1f69b3f81d39738ee5b1efe079b8c78923f3f271d1e7fd867638997e6e6367e35313b8f036d6b59fa27b5fcfd0d696547ea0c
7
- data.tar.gz: 206dec8621e2651be6ad29f9f2597abbeb4302ae0adf2666f419e7cf1bc587d60583e225b88b79d189743e7713a5c717ae15dcab9f2c3dad7f3fde371c723027
6
+ metadata.gz: 9290a45b87194f0572dd07675ac064e253d0641986841dce7bcb67e4ec147382d5976eec218f2fcd32e25b1f1abc406b4997102193b25c32471a54ca39a05dcf
7
+ data.tar.gz: dbf4857d8ea62f952f2fbf3823c3f6b2dd7f6cf00f106531b1787252fb447bff671196b86d625522fc436f5ba8fbde42a3f4fd132fe9de4bde253c2be7118b92
data/README.md CHANGED
@@ -22,6 +22,21 @@ bf = BarefootJS::Context.new(backend)
22
22
 
23
23
  Values are JSON-shaped Ruby data with symbol hash keys throughout (props, env hashes, array-of-hash records).
24
24
 
25
+ ### `null` and `undefined`
26
+
27
+ Ruby's `nil` is JS `null`. JS `undefined` is `BarefootJS::UNDEF`, a frozen singleton. A props Hash already has the four states a JS prop has, so no wrapper type is needed:
28
+
29
+ | JS | Props Hash |
30
+ | --- | --- |
31
+ | prop not passed | key left out |
32
+ | `undefined` passed (`c={props.c}` with `c` unset) | `{ c: BarefootJS::UNDEF }` |
33
+ | `null` | `{ c: nil }` |
34
+ | a value | `{ c: 'x' }` |
35
+
36
+ A destructure default applies to the first two only. JSON decoded with `JSON.parse(..., symbolize_names: true)` gives `nil` for `null` and leaves a missing key out, which is what you want.
37
+
38
+ `UNDEF.nil?` is true and it prints as `''`, but Ruby cannot make it falsy: `if value` and `value || default` treat it as present. Test with `BarefootJS.undefined?`, `BarefootJS.null?` and `BarefootJS.nullish?` (`== null`) instead.
39
+
25
40
  ## Documentation
26
41
 
27
42
  - [barefootjs.dev](https://barefootjs.dev/) — core documentation
@@ -85,10 +85,15 @@ module BarefootJS
85
85
  end
86
86
 
87
87
  # Render `<name>.erb` (relative to `path`) with `child_bf` bound as
88
- # `bf` and `vars` (a Hash, symbol-keyed) bound as `v`.
88
+ # `bf` and `vars` (a Hash, symbol-keyed) bound as `v`. A template reads
89
+ # a var the host did not set as JS `undefined` (`BarefootJS::UNDEF`),
90
+ # through a copy of `vars` whose default is `UNDEF`; the host's own Hash
91
+ # is left as it is.
89
92
  def render_named(name, child_bf, vars)
90
93
  template = load_template(name)
91
- Renderer.new(child_bf, vars || {}).render(template)
94
+ bound = (vars || {}).dup
95
+ bound.default = BarefootJS::UNDEF
96
+ Renderer.new(child_bf, bound).render(template)
92
97
  end
93
98
 
94
99
  private
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'json'
4
+ require 'barefoot_js/undefined'
4
5
 
5
6
  module BarefootJS
6
7
  # Lightweight evaluator for the pure `ParsedExpr` subset, scoped to
@@ -32,6 +33,12 @@ module BarefootJS
32
33
  # `object-literal` property keys) are plain Ruby Strings coming out of the
33
34
  # parser; they are converted to Symbols at the point they touch a
34
35
  # SYMBOL-keyed Hash (env or object value).
36
+ #
37
+ # JS `undefined` is `BarefootJS::UNDEF` (barefoot_js/undefined.rb); host
38
+ # `nil` is JS `null`. A missing field, an out-of-range or non-canonical
39
+ # index, the unbound `undefined` identifier, an omitted builtin argument
40
+ # and a `find` with no result read as `UNDEF` (spec/js-undefined-value.md,
41
+ # section 2).
35
42
  module Evaluator
36
43
  # Thrown when a node/operator/builtin/identifier is outside the subset.
37
44
  class EvalUnsupported < StandardError; end
@@ -50,7 +57,12 @@ module BarefootJS
50
57
  when 'identifier'
51
58
  name = node[:name]
52
59
  key = name.to_sym
53
- raise EvalUnsupported, "unbound identifier '#{name}'" unless env.key?(key)
60
+ unless env.key?(key)
61
+ # The unshadowed `undefined` identifier is the constant.
62
+ return UNDEF if name == 'undefined'
63
+
64
+ raise EvalUnsupported, "unbound identifier '#{name}'"
65
+ end
54
66
  env[key]
55
67
  when 'binary'
56
68
  binary(node[:op], evaluate(node[:left], env), evaluate(node[:right], env))
@@ -62,7 +74,7 @@ module BarefootJS
62
74
  case op
63
75
  when '&&' then truthy?(left) ? evaluate(node[:right], env) : left
64
76
  when '||' then truthy?(left) ? left : evaluate(node[:right], env)
65
- else left.nil? ? evaluate(node[:right], env) : left # '??'
77
+ else BarefootJS.nullish?(left) ? evaluate(node[:right], env) : left # '??' coalesces both nils
66
78
  end
67
79
  when 'conditional'
68
80
  truthy?(evaluate(node[:test], env)) ? evaluate(node[:consequent], env) : evaluate(node[:alternate], env)
@@ -135,9 +147,11 @@ module BarefootJS
135
147
  # `.join(sep?)` (#2094) -- a nested `.flatMap(p => p.tags.map(...))
136
148
  # .join(...)` projection composes a `.join` on top of a nested
137
149
  # `.map`, so it must be executable in the same evaluator subset as
138
- # `.includes`. Default separator "," (JS); a `nil` element joins
139
- # as "" (not the string "null"). Mirrors Go's `evalJoin`.
140
- sep = args.empty? ? ',' : to_string(evaluate(args[0], env))
150
+ # `.includes`. An omitted or `undefined` separator is "," (JS), a
151
+ # `null` one is ToString'd ("null"); a nil element joins as "" (not
152
+ # the string "null" / "undefined"). Mirrors Go's `evalJoin`.
153
+ sep_value = args.empty? ? UNDEF : evaluate(args[0], env)
154
+ sep = BarefootJS.undefined?(sep_value) ? ',' : to_string(sep_value)
141
155
  array_join(evaluate(node[:object], env), sep)
142
156
  else
143
157
  # Every other array/string method (`slice`, `flat`, ...) is
@@ -164,7 +178,8 @@ module BarefootJS
164
178
  # ---------------------------------------------------------------------
165
179
 
166
180
  def to_number(v)
167
- return 0 if v.nil?
181
+ return 0 if BarefootJS.null?(v)
182
+ return Float::NAN if BarefootJS.undefined?(v)
168
183
  return v ? 1 : 0 if v.is_a?(TrueClass) || v.is_a?(FalseClass)
169
184
  return v if v.is_a?(Numeric)
170
185
  if v.is_a?(String)
@@ -179,18 +194,20 @@ module BarefootJS
179
194
  return v if v.is_a?(String)
180
195
  return number_to_string(v) if v.is_a?(Numeric)
181
196
  return v ? 'true' : 'false' if v.is_a?(TrueClass) || v.is_a?(FalseClass)
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)
197
+ return 'null' if BarefootJS.null?(v)
198
+ return 'undefined' if BarefootJS.undefined?(v)
199
+ # Array.prototype.toString is join(","): a nil element (`null` or
200
+ # `undefined`) prints as "", and a nested array flattens through its
201
+ # own join. A plain object prints as "[object Object]".
202
+ return v.map { |el| BarefootJS.nullish?(el) ? '' : to_string(el) }.join(',') if v.is_a?(Array)
187
203
  return '[object Object]' if v.is_a?(Hash)
188
204
 
189
205
  raise EvalUnsupported, "cannot coerce #{v.class} to string"
190
206
  end
191
207
 
192
208
  def truthy?(v)
193
- return false if v.nil? || v.is_a?(FalseClass)
209
+ # `UNDEF` is truthy under Ruby's own `if`: this is the JS test.
210
+ return false if BarefootJS.nullish?(v) || v.is_a?(FalseClass)
194
211
  return true if v.is_a?(TrueClass)
195
212
  if v.is_a?(Numeric)
196
213
  f = v.to_f
@@ -381,8 +398,10 @@ module BarefootJS
381
398
  if non_primitive?(l) || non_primitive?(r)
382
399
  raise EvalUnsupported, '=== on a non-primitive is not in the evaluator subset'
383
400
  end
384
- return true if l.nil? && r.nil?
385
- return false if l.nil? || r.nil?
401
+ # `null` is only itself and `undefined` only itself.
402
+ return BarefootJS.null?(r) if BarefootJS.null?(l)
403
+ return BarefootJS.undefined?(r) if BarefootJS.undefined?(l)
404
+ return false if BarefootJS.nullish?(r)
386
405
  return l == r if l.is_a?(Numeric) && r.is_a?(Numeric)
387
406
  return l == r if boolean?(l) && boolean?(r)
388
407
  return l == r if l.is_a?(String) && r.is_a?(String)
@@ -442,7 +461,7 @@ module BarefootJS
442
461
  def array_join(obj, sep)
443
462
  return '' unless obj.is_a?(Array)
444
463
 
445
- obj.map { |el| el.nil? ? '' : to_string(el) }.join(sep)
464
+ obj.map { |el| BarefootJS.nullish?(el) ? '' : to_string(el) }.join(sep)
446
465
  end
447
466
  private_class_method :array_join
448
467
 
@@ -573,6 +592,8 @@ module BarefootJS
573
592
  private_class_method :math_round
574
593
 
575
594
  def call_builtin(name, args)
595
+ # An omitted argument is JS `undefined`.
596
+ arg = ->(i) { i < args.length ? args[i] : UNDEF }
576
597
  case name
577
598
  when 'Math.max'
578
599
  return -Float::INFINITY if args.empty?
@@ -588,17 +609,19 @@ module BarefootJS
588
609
  return Float::NAN if nums.any?(&:nan?)
589
610
 
590
611
  nums.min
591
- when 'Math.abs' then to_number(args[0]).abs
612
+ when 'Math.abs' then to_number(arg.call(0)).abs
592
613
  when 'Math.floor'
593
- n = to_number(args[0]).to_f
614
+ n = to_number(arg.call(0)).to_f
594
615
  n.finite? ? n.floor : n
595
616
  when 'Math.ceil'
596
- n = to_number(args[0]).to_f
617
+ n = to_number(arg.call(0)).to_f
597
618
  n.finite? ? n.ceil : n
598
- when 'Math.round' then math_round(to_number(args[0]).to_f)
599
- when 'String' then to_string(args[0])
600
- when 'Number' then to_number(args[0])
601
- when 'Boolean' then truthy?(args[0])
619
+ when 'Math.round' then math_round(to_number(arg.call(0)).to_f)
620
+ # `String()` / `Number()` with no argument are "" / 0; `String(undefined)`
621
+ # is "undefined" and `Number(undefined)` NaN.
622
+ when 'String' then args.empty? ? '' : to_string(args[0])
623
+ when 'Number' then args.empty? ? 0 : to_number(args[0])
624
+ when 'Boolean' then truthy?(arg.call(0))
602
625
  else
603
626
  raise EvalUnsupported, "builtin '#{name}' is not in the evaluator subset"
604
627
  end
@@ -622,9 +645,9 @@ module BarefootJS
622
645
  end
623
646
  if obj.is_a?(Hash)
624
647
  sym = key.to_sym
625
- return obj.key?(sym) ? obj[sym] : nil
648
+ return obj.key?(sym) ? obj[sym] : UNDEF
626
649
  end
627
- raise EvalUnsupported, "cannot read property '#{key}' of #{obj.nil? ? 'null' : obj.class}"
650
+ raise EvalUnsupported, "cannot read property '#{key}' of #{js_type_name(obj)}"
628
651
  end
629
652
  private_class_method :read_property
630
653
 
@@ -633,13 +656,22 @@ module BarefootJS
633
656
  # is outside the subset here.
634
657
  def read_index(obj, index)
635
658
  unless obj.is_a?(Array) || obj.is_a?(Hash) || obj.is_a?(String)
636
- raise EvalUnsupported, "cannot index #{obj.nil? ? 'null' : obj.class}"
659
+ raise EvalUnsupported, "cannot index #{js_type_name(obj)}"
637
660
  end
638
661
 
639
662
  index_value(obj, index)
640
663
  end
641
664
  private_class_method :read_index
642
665
 
666
+ # The name a refusal message gives a receiver: JS's for the two nils.
667
+ def js_type_name(obj)
668
+ return 'null' if BarefootJS.null?(obj)
669
+ return 'undefined' if BarefootJS.undefined?(obj)
670
+
671
+ obj.class
672
+ end
673
+ private_class_method :js_type_name
674
+
643
675
  # index_value(obj, index) -> JS `obj[index]`, shared with the template
644
676
  # helper `bf.get` (which delegates here, so a template read and a
645
677
  # callback read cannot disagree on a key). The key goes through
@@ -649,27 +681,31 @@ module BarefootJS
649
681
  # unit), are read only through a canonical array index: "1" reads
650
682
  # element 1, while "01", "1e0", "-0", "1.1" and "-1" are ordinary
651
683
  # property names (spec/js-primitive-semantics.md, "ToPropertyKey and
652
- # index read"). Any other receiver reads nil.
684
+ # index read"). A key the receiver does not have, and any read of a
685
+ # receiver with no properties, is `undefined`.
653
686
  def index_value(obj, index)
654
687
  key = property_key(index)
655
- return nil if key.nil?
688
+ return UNDEF if key.nil?
656
689
 
657
690
  case obj
658
691
  when Hash
659
692
  sym = key.to_sym
660
693
  return obj[sym] if obj.key?(sym)
661
694
 
662
- obj.key?(key) ? obj[key] : nil
695
+ obj.key?(key) ? obj[key] : UNDEF
663
696
  when Array, String
664
- return nil unless key.match?(/\A(?:0|[1-9][0-9]*)\z/)
697
+ return UNDEF unless key.match?(/\A(?:0|[1-9][0-9]*)\z/)
665
698
 
666
699
  i = key.to_i
667
700
  return utf16_unit_at(obj, i) if obj.is_a?(String)
668
701
 
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
702
+ # An index past the end reads `undefined`. Checking before
703
+ # `Array#[]` also keeps an oversized key ("9223372036854775808",
704
+ # 1e20) from raising RangeError: a Bignum cannot be converted to a C
705
+ # long.
706
+ i < obj.length ? obj[i] : UNDEF
707
+ else
708
+ UNDEF
673
709
  end
674
710
  end
675
711
 
@@ -685,8 +721,8 @@ module BarefootJS
685
721
  end
686
722
  private_class_method :property_key
687
723
 
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
724
+ # The UTF-16 code unit of `str` at index `i` (JS `str[i]`), or
725
+ # `undefined` past the end. One half of a surrogate pair reads as U+FFFD: a lone
690
726
  # surrogate cannot be written out as UTF-8
691
727
  # (spec/js-primitive-semantics.md, "Out of scope").
692
728
  def utf16_unit_at(str, i)
@@ -697,7 +733,7 @@ module BarefootJS
697
733
 
698
734
  pos += width
699
735
  end
700
- nil
736
+ UNDEF
701
737
  end
702
738
  private_class_method :utf16_unit_at
703
739
 
@@ -742,7 +778,10 @@ module BarefootJS
742
778
  env = base_env ? base_env.dup : {}
743
779
  a_key = param_a.to_sym
744
780
  b_key = param_b.to_sym
745
- decorated = items.each_with_index.map { |item, i| [i, item] }
781
+ # JS `Array.prototype.sort` moves every `undefined` element to the end
782
+ # without handing it to the comparator.
783
+ defined, tail = items.partition { |item| !BarefootJS.undefined?(item) }
784
+ decorated = defined.each_with_index.map { |item, i| [i, item] }
746
785
  sorted = decorated.sort do |x, y|
747
786
  env[a_key] = x[1]
748
787
  env[b_key] = y[1]
@@ -750,7 +789,7 @@ module BarefootJS
750
789
  sign = c.nan? ? 0 : (c <=> 0)
751
790
  sign.zero? ? (x[0] <=> y[0]) : sign
752
791
  end
753
- sorted.map { |pair| pair[1] }
792
+ sorted.map { |pair| pair[1] } + tail
754
793
  end
755
794
 
756
795
  def sort_by_json(items, cmp_json, param_a, param_b, base_env = nil)
@@ -794,8 +833,8 @@ module BarefootJS
794
833
  end
795
834
  end
796
835
 
797
- # find -- first matching element, or nil. `forward` false searches from
798
- # the end (findLast).
836
+ # find -- first matching element, or `undefined`. `forward` false
837
+ # searches from the end (findLast).
799
838
  def find(items, pred, param, forward = true, base_env = nil)
800
839
  arr = items.is_a?(Array) ? items : []
801
840
  arr = arr.reverse unless forward
@@ -805,7 +844,7 @@ module BarefootJS
805
844
  env[key] = item
806
845
  return item if truthy?(evaluate(pred, env))
807
846
  end
808
- nil
847
+ UNDEF
809
848
  end
810
849
 
811
850
  # find_index -- index of the first matching element, or -1. `forward`
@@ -0,0 +1,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BarefootJS
4
+ # JS `undefined` (spec/js-undefined-value.md). Host `nil` is JS `null`; JS
5
+ # `undefined` is one frozen singleton, `BarefootJS::UNDEF`, created only
6
+ # where JS reads one: a missing key, an out-of-range index, `.at()` /
7
+ # `.find()` with no result, `?.` over a nullish receiver, the `undefined`
8
+ # identifier (`bf.undefined` in a template), an omitted declared prop. No
9
+ # decoded data is walked to convert anything.
10
+ #
11
+ # Ruby cannot make an object falsy, so `UNDEF` is truthy under Ruby's own
12
+ # `if` / `||` / `&&` / `unless`. Every JS truthiness test in a compiled
13
+ # template and in this runtime goes through `Evaluator.truthy?`
14
+ # (`bf.truthy?`), which reads it as falsy. `nil?` answers true, so a
15
+ # native `x.nil?` in a template is the JS nullish test (`x == null`); the
16
+ # runtime never relies on it and tests with `BarefootJS.undefined?` /
17
+ # `null?` / `nullish?` instead. `&.` does not consult `nil?`: it calls
18
+ # through on `UNDEF`, which is why a template spells `o?.k` as
19
+ # `bf.get_opt(o, :k)`.
20
+ #
21
+ # It prints as `''` (`to_s`), as JS renders `undefined` in a text or
22
+ # attribute position, and reading any key of it gives itself (`[]`), so a
23
+ # chained read past it stays `undefined` instead of raising. `to_json`
24
+ # gives `null` for a host encoder; the runtime's own JSON walk follows
25
+ # `JSON.stringify` instead (a member holding it is dropped).
26
+ class Undefined
27
+ def nil?
28
+ true
29
+ end
30
+
31
+ def to_s
32
+ ''
33
+ end
34
+
35
+ def inspect
36
+ 'undefined'
37
+ end
38
+
39
+ def [](*)
40
+ self
41
+ end
42
+
43
+ def to_json(*)
44
+ 'null'
45
+ end
46
+
47
+ # The singleton survives a copy (a host's `deep_dup`, `Marshal`-free
48
+ # cloning), so identity tests keep holding.
49
+ def dup
50
+ self
51
+ end
52
+
53
+ def clone(*)
54
+ self
55
+ end
56
+ end
57
+
58
+ UNDEF = Undefined.new.freeze
59
+ Undefined.private_class_method :new
60
+
61
+ module_function
62
+
63
+ # JS `v === undefined`.
64
+ def undefined?(value)
65
+ Undefined === value
66
+ end
67
+
68
+ # JS `v === null`: host `nil` (strictly: `UNDEF.nil?` is true too).
69
+ def null?(value)
70
+ NilClass === value
71
+ end
72
+
73
+ # JS `v == null`: `null` or `undefined`.
74
+ def nullish?(value)
75
+ NilClass === value || Undefined === value
76
+ end
77
+
78
+ # Whether a JSON-decoded value (symbol or string keys) is the
79
+ # `{"$undef": true}` sentinel, the manifest's (and the golden vectors')
80
+ # spelling of JS `undefined` (spec/js-undefined-value.md, "JSON encoding
81
+ # for vectors").
82
+ def undefined_sentinel?(value)
83
+ value.is_a?(Hash) && value.size == 1 && (value[:$undef] == true || value['$undef'] == true)
84
+ end
85
+
86
+ # `value` with every sentinel, at any depth, replaced by `UNDEF`; inside a
87
+ # hash it is a present key holding `undefined`. Every other hash key that
88
+ # begins with `$$` loses one leading `$`: the manifest encoder escapes a
89
+ # seed's own `$`-prefixed keys that way, so data shaped like the sentinel
90
+ # stays data.
91
+ def decode_undefined(value)
92
+ return UNDEF if undefined_sentinel?(value)
93
+ return value.map { |v| decode_undefined(v) } if value.is_a?(Array)
94
+ return value.to_h { |k, v| [unescape_key(k), decode_undefined(v)] } if value.is_a?(Hash)
95
+
96
+ value
97
+ end
98
+
99
+ # A `$$`-prefixed key (symbol or string) with one leading `$` removed.
100
+ def unescape_key(key)
101
+ name = key.to_s
102
+ return key unless name.start_with?('$$')
103
+
104
+ key.is_a?(Symbol) ? name[1..].to_sym : name[1..]
105
+ end
106
+ end