blib/lib/Text/Nunjucks/Lib.pm

filter: Statementstmt 90.8% 1316 / 1449 Branchbran 86.0% 780 / 906 Conditioncond 80.8% 240 / 297 MC/DCmcdc 76.4% 133 / 174 Subroutinesub 88.0% 147 / 167 Podpod 0.0% 0 / 71 totaltotal 85.3% 2616 / 3064 CC 998 SCAR 25.5
CC
998
Cov
88%
has_own_prop
70.0
has_own_prop
70.0
number_to_string
24.1
CRAP 12.8
« blib/lib/Text/Nunjucks/Transformer.pm ↑ Summary blib/lib/Text/Nunjucks/Compiler.pm »
1 package Text::Nunjucks::Lib;
2 # ABSTRACT: 1:1 port of Nunjucks src/lib.js -- foundation utilities and escaping
3  
4 23 our $VERSION = '0.001';
5  
6 23 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 23 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 23 ▶use builtin qw( is_bool created_as_number true false );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 23 ▶use feature qw( current_sub );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 23 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 23 ▶use Config ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 23 ▶use Cwd ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 23 ▶use Errno ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 23 ▶use Math::BigInt ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 23 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 23 ▶use Scalar::Util qw( blessed refaddr );
Subroutine BEGIN: called CC=1 SCAR=0.0
17 23 ▶use Text::Nunjucks::Lib::TemplateError;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 23 ▶use Text::Nunjucks::Lib::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 # Circular with Runtime's `use Text::Nunjucks::Lib`. Lib calls up into it for
20 # the JS semantics Runtime is the one home of -- the property reads and
21 # ToPropertyKey of hasOwnProp / getAttrGetter / groupBy / toArray / map's
22 # array-like branch, groupBy's result object (make_dict), ToNumber / ToString /
23 # the operators in groupBy, toArray, JSON.stringify and the sort comparator --
24 # from inside their subs, run time. Caveat: when Lib loads first,
25 # this line compiles and runs all of Runtime before the rest of Lib is even
26 # compiled -- the Lib subs below this line do not exist yet and its file-scope
27 # lexicals (%ESCAPE_MAP, $JS_WORD_CLASS, $NUM_POS_INF, ...) are still unset. So
28 # Runtime must never call a Lib function at file scope (a `my $X = Lib->...`,
29 # a BEGIN, a `use constant`); calls from inside its subs are fine.
30 23 ▶use Text::Nunjucks::Runtime;
Subroutine BEGIN: called CC=1 SCAR=0.0
31  
32 23 ▶no warnings 'experimental::builtin';
Subroutine BEGIN: called CC=1 SCAR=0.0
33  
34 # lib.js is a plain bag of exported functions accessed qualified as `lib.foo`.
35 # Ported as a class-method-only module (getty-perl-core "dispatch through the
36 # invocant"): every function is a method taking $self, callers use
37 # Text::Nunjucks::Lib->is_array($x), cross-calls go through $self. No instances.
38 # ADR 0001 designates this module the single home for value-kind checks.
39  
40 # The collaborator class, named once (getty-perl-core resolver), for map's
41 # array-like branch and groupBy's engine-built result.
42 943014 ▶sub _runtime { 'Text::Nunjucks::Runtime' }
Subroutine _runtime: called CC=1 SCAR=0.0
43  
44 #### module constants (var escapeMap / escapeRegex)
45  
46 23 my %ESCAPE_MAP = (
47 '&' => '&',
48 '"' => '"',
49 "'" => ''',
50 '<' => '&lt;',
51 '>' => '&gt;',
52 '\\' => '&#92;',
53 );
54  
55 23 my $ESCAPE_REGEX = qr/[&"'<>\\]/;
56  
57 #### hasOwnProp
58  
59 # ObjProto.hasOwnProperty.call(obj, k): ToPropertyKey(k) first (Runtime's, the
60 # key obj[k] reads), then ToObject(obj), which throws on undefined and null
61 # (oracle: [u]|groupby('a') and [{'a': null}]|groupby('a.b') -> "TypeError:
62 # Cannot convert undefined or null to object"). The own properties per value
63 # kind, oracle-measured through groupby(attr): an object -- caller hash or
64 # ordered dict -- its keys; an array its indices and length; a primitive
65 # string, a String object after ToObject, its code-unit indices and length
66 # (ADR 0012; '01' is no index); a SafeString this.val and this.length; a regex
67 # its lastIndex (source and flags are inherited accessors). A number and a
68 # boolean own nothing. A function owns length and name in JS (a macro: 0 and
69 # 'macro'), which a Perl coderef has no form of, so it owns nothing here; nor
70 # does any other blessed object (k47).
71 385205 ▶sub has_own_prop {
Subroutine has_own_prop: called CC=20 SCAR=42.5
Pod undocumented
72 0 ▶ my ( $self, $obj, $k ) = @_;
Subroutine has_own_prop: not called CC=20 SCAR=42.5
Pod undocumented
73 0 my $rt = $self->_runtime;
74 0 my $key = $rt->_member_key($k);
75 0 ▶ die Text::Nunjucks::Lib::Error->new( 'Cannot convert undefined or null to object', name => 'TypeError' )
Branch: 2 branches
BranchTrueFalseTotal
if not defined $obj or $rt->_is_none($obj) 10 385195 385205
if not defined $obj or $rt->_is_none($obj) 0 0 0
Condition50%3/6
not defined $obj or $rt->_is_none($obj)
l!l&&r!l&&!r
64385195
not defined $obj or $rt->_is_none($obj)
l!l&&r!l&&!r
000
MC/DC100%2/2
not defined $obj or $rt->_is_none($obj)
not defined $obj $rt->_is_none($obj)
MC/DC0%0/2
not defined $obj or $rt->_is_none($obj)
not defined $obj $rt->_is_none($obj)
Truth table100%3/3
not(A) or B
A= not defined $objB= $rt->_is_none($obj)
ABresult
1X1
011
000
Truth table0%0/3
not(A) or B
A= not defined $objB= $rt->_is_none($obj)
ABresult
1X1
011
000
76 if !defined($obj) || $rt->_is_none($obj);
77  
78 0 my $r = ref $obj;
79 0 ▶ return exists $obj->{$key} ? 1 : 0 if $r eq 'HASH';
Branch: 4 branches
BranchTrueFalseTotal
if $r eq "HASH" 384927 268 385195
exists $obj->{$key} ? : 384847 80 384927
if $r eq "HASH" 0 0 0
exists $obj->{$key} ? : 0 0 0
80 0 ▶ return $obj->exists($key) ? 1 : 0 if $rt->_is_ordered_hash($obj);
Branch: 4 branches
BranchTrueFalseTotal
if $rt->_is_ordered_hash($obj) 144 124 268
$obj->exists($key) ? : 133 11 144
if $rt->_is_ordered_hash($obj) 0 0 0
$obj->exists($key) ? : 0 0 0
81 0 ▶ if ( $r eq 'ARRAY' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($r eq "ARRAY") 52 72 124
if ($r eq "ARRAY") 0 0 0
82 0 ▶ return 1 if $key eq 'length';
Branch: 2 branches
BranchTrueFalseTotal
if $key eq "length" 2 50 52
if $key eq "length" 0 0 0
83 0 ▶ return ( $self->_is_array_index($key) && $key < scalar @$obj ) ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
$self->_is_array_index($key) && $key < scalar @$obj ? : 42 8 50
$self->_is_array_index($key) && $key < scalar @$obj ? : 0 0 0
Condition50%3/6
$self->_is_array_index($key) and $key < scalar @$obj
!ll&&!rl&&r
7142
$self->_is_array_index($key) and $key < scalar @$obj
!ll&&!rl&&r
000
MC/DC100%2/2
$self->_is_array_index($key) and $key < scalar @$obj
$self->_is_array_index($key) $key < scalar @$obj
MC/DC0%0/2
$self->_is_array_index($key) and $key < scalar @$obj
$self->_is_array_index($key) $key < scalar @$obj
Truth table100%3/3
A and B
A= $self->_is_array_index($key)B= $key < scalar @$obj
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $self->_is_array_index($key)B= $key < scalar @$obj
ABresult
0X0
100
111
84 }
85 0 ▶ if ( $self->is_string($obj) ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->is_string($obj)) 44 28 72
if ($self->is_string($obj)) 0 0 0
86 0 ▶ return 1 if $key eq 'length';
Branch: 2 branches
BranchTrueFalseTotal
if $key eq "length" 25 19 44
if $key eq "length" 0 0 0
87 0 ▶ return ( $self->_is_array_index($key) && $key < $self->js_string_length($obj) ) ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
$self->_is_array_index($key) && $key < $self->js_string_length($obj) ? : 13 6 19
$self->_is_array_index($key) && $key < $self->js_string_length($obj) ? : 0 0 0
Condition50%3/6
$self->_is_array_index($key) and $key < $self->js_string_length($obj)
!ll&&!rl&&r
5113
$self->_is_array_index($key) and $key < $self->js_string_length($obj)
!ll&&!rl&&r
000
MC/DC100%2/2
$self->_is_array_index($key) and $key < $self->js_string_length($obj)
$self->_is_array_index($key) $key < $self->js_string_length($obj)
MC/DC0%0/2
$self->_is_array_index($key) and $key < $self->js_string_length($obj)
$self->_is_array_index($key) $key < $self->js_string_length($obj)
Truth table100%3/3
A and B
A= $self->_is_array_index($key)B= $key < $self->js_string_length($obj)
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $self->_is_array_index($key)B= $key < $self->js_string_length($obj)
ABresult
0X0
100
111
88 }
89 0 ▶ return ( $key eq 'val' || $key eq 'length' ) ? 1 : 0 if $rt->_is_safe_string($obj);
Branch: 4 branches
BranchTrueFalseTotal
if $rt->_is_safe_string($obj) 10 18 28
$key eq 'val' || $key eq 'length' ? : 3 7 10
if $rt->_is_safe_string($obj) 0 0 0
$key eq 'val' || $key eq 'length' ? : 0 0 0
Condition50%3/6
$key eq "val" or $key eq "length"
l!l&&r!l&&!r
127
$key eq "val" or $key eq "length"
l!l&&r!l&&!r
000
MC/DC100%2/2
$key eq "val" or $key eq "length"
$key eq "val" $key eq "length"
MC/DC0%0/2
$key eq "val" or $key eq "length"
$key eq "val" $key eq "length"
Truth table100%3/3
A or B
A= $key eq "val"B= $key eq "length"
ABresult
1X1
011
000
Truth table0%0/3
A or B
A= $key eq "val"B= $key eq "length"
ABresult
1X1
011
000
90 0 ▶ return $key eq 'lastIndex' ? 1 : 0 if $rt->_is_regex($obj);
Branch: 4 branches
BranchTrueFalseTotal
if $rt->_is_regex($obj) 3 15 18
$key eq 'lastIndex' ? : 2 1 3
if $rt->_is_regex($obj) 0 0 0
$key eq 'lastIndex' ? : 0 0 0
91 0 return 0;
92 }
93  
94 #### lookupEscape
95  
96 1937 ▶sub lookup_escape {
Subroutine lookup_escape: called CC=1 SCAR=1.2
Pod undocumented
97 0 ▶ my ( $self, $ch ) = @_;
Subroutine lookup_escape: not called CC=1 SCAR=1.2
Pod undocumented
98 0 return $ESCAPE_MAP{$ch};
99 }
100  
101 #### _prettifyError
102  
103 712 ▶sub _prettify_error {
Subroutine _prettify_error: called CC=4 SCAR=17.9
104 0 ▶ my ( $self, $path, $with_internals, $err ) = @_;
Subroutine _prettify_error: not called CC=4 SCAR=17.9
105  
106 0 ▶ if ( !( blessed($err) && $err->can('update') ) ) {
Branch: 2 branches
BranchTrueFalseTotal
unless (builtin::blessed($err) and $err->can("update")) 256 456 712
unless (builtin::blessed($err) and $err->can("update")) 0 0 0
Condition50%3/6
builtin::blessed($err) and $err->can("update")
!ll&&!rl&&r
1255456
builtin::blessed($err) and $err->can("update")
!ll&&!rl&&r
000
MC/DC100%2/2
builtin::blessed($err) and $err->can("update")
builtin::blessed($err) $err->can("update")
MC/DC0%0/2
builtin::blessed($err) and $err->can("update")
builtin::blessed($err) $err->can("update")
Truth table100%3/3
A and B
A= builtin::blessed($err)B= $err->can("update")
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= builtin::blessed($err)B= $err->can("update")
ABresult
0X0
100
111
107 # not one of ours, cast it
108 0 $err = Text::Nunjucks::Lib::TemplateError->new($err);
109 }
110 0 $err->update($path);
111  
112 # Unless they marked the dev flag, show them a trace from here. In JS this
113 # rebuilds a plain Error to scrub internal stack frames; Perl has no such
114 # stack in the message, but reproducing "an object without update()" matters:
115 # a re-prettified error must be re-wrapped, not updated again.
116 0 ▶ if ( !$with_internals ) {
Branch: 2 branches
BranchTrueFalseTotal
unless ($with_internals) 711 1 712
unless ($with_internals) 0 0 0
117 0 my $old = $err;
118 0 $err = Text::Nunjucks::Lib::Error->new( $old->message, name => $old->name );
119 }
120  
121 0 return $err;
122 }
123  
124 #### TemplateError -- Text::Nunjucks::Lib::TemplateError (own file)
125  
126 #### escape
127  
128 127427 ▶sub escape {
Subroutine escape: called CC=1 SCAR=1.2
Pod undocumented
129 0 ▶ my ( $self, $val ) = @_;
Subroutine escape: not called CC=1 SCAR=1.2
Pod undocumented
130 0 return $val =~ s/($ESCAPE_REGEX)/$self->lookup_escape($1)/ger;
131 }
132  
133 #### isFunction
134  
135 136382 ▶sub is_function {
Subroutine is_function: called CC=2 SCAR=9.2
Pod undocumented
136 0 ▶ my ( $self, $obj ) = @_;
Subroutine is_function: not called CC=2 SCAR=9.2
Pod undocumented
137 # plain coderef only; blessed / overloaded callables are k8 (callables) territory
138 0 ▶ return ref($obj) eq 'CODE' ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
ref $obj eq 'CODE' ? : 52328 84054 136382
ref $obj eq 'CODE' ? : 0 0 0
139 }
140  
141 #### isArray
142  
143 156831 ▶sub is_array {
Subroutine is_array: called CC=2 SCAR=9.2
Pod undocumented
144 0 ▶ my ( $self, $obj ) = @_;
Subroutine is_array: not called CC=2 SCAR=9.2
Pod undocumented
145 0 ▶ return ref($obj) eq 'ARRAY' ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
ref $obj eq 'ARRAY' ? : 67279 89552 156831
ref $obj eq 'ARRAY' ? : 0 0 0
146 }
147  
148 #### isString
149  
150 535284 ▶sub is_string {
Subroutine is_string: called CC=5 SCAR=20.9
Pod undocumented
151 0 ▶ my ( $self, $obj ) = @_;
Subroutine is_string: not called CC=5 SCAR=20.9
Pod undocumented
152 # ADR 0001: a string is a defined non-ref scalar that is neither a boolean
153 # nor created-as-number. A numeric *string* ('5') is a string; 5 is not.
154 0 ▶ return ( defined($obj) && !ref($obj) && !is_bool($obj) && !created_as_number($obj) )
Branch: 2 branches
BranchTrueFalseTotal
defined $obj && !ref($obj) && !builtin::is_bool($obj) && !created_as_number($obj) ? : 159197 376087 535284
defined $obj && !ref($obj) && !builtin::is_bool($obj) && !created_as_number($obj) ? : 0 0 0
Condition50%9/18
defined $obj and not ref $obj and not builtin::is_bool($obj) and not created_as_number $obj
!ll&&!rl&&r
33244943638159197
defined $obj and not ref $obj and not builtin::is_bool($obj)
!ll&&!rl&&r
332245204202835
defined $obj and not ref $obj
!ll&&!rl&&r
76332169203039
defined $obj and not ref $obj and not builtin::is_bool($obj) and not created_as_number $obj
!ll&&!rl&&r
000
defined $obj and not ref $obj and not builtin::is_bool($obj)
!ll&&!rl&&r
000
defined $obj and not ref $obj
!ll&&!rl&&r
000
MC/DC100%4/4
defined $obj and not ref $obj and not builtin::is_bool($obj) and not created_as_number $obj
defined $obj not ref $obj not builtin::is_bool($obj) not created_as_number $obj
MC/DC0%0/4
defined $obj and not ref $obj and not builtin::is_bool($obj) and not created_as_number $obj
defined $obj not ref $obj not builtin::is_bool($obj) not created_as_number $obj
Truth table100%5/5
A and not(B) and not(C) and not(D)
A= defined $objB= not ref $objC= not builtin::is_bool($obj)D= not created_as_number $obj
ABCDresult
0XXX0
10XX0
110X0
11100
11111
Truth table0%0/5
A and not(B) and not(C) and not(D)
A= defined $objB= not ref $objC= not builtin::is_bool($obj)D= not created_as_number $obj
ABCDresult
0XXX0
10XX0
110X0
11100
11111
155 ? 1 : 0;
156 }
157  
158 #### isObject
159  
160 10299 ▶sub is_object {
Subroutine is_object: called CC=5 SCAR=20.9
Pod undocumented
161 0 ▶ my ( $self, $obj ) = @_;
Subroutine is_object: not called CC=5 SCAR=20.9
Pod undocumented
162 # Object.prototype.toString.call(obj) === '[object Object]': a plain hashref,
163 # an ordered dict (template literal / engine-built object, ADR 0011) and a
164 # SafeString -- a String subclass whose instances are ordinary objects
165 # (oracle: '{% macro m() %}ab{% endmacro %}' m()|list gives val=ab;length=2;).
166 # Other blessed objects are k6/Runtime member-access territory.
167 0 ▶ return 1 if ref($obj) eq 'HASH';
Branch: 2 branches
BranchTrueFalseTotal
if ref $obj eq "HASH" 62 10237 10299
if ref $obj eq "HASH" 0 0 0
168 0 ▶ return ( blessed($obj) && ( $obj->isa('Hash::Ordered') || $obj->isa('Text::Nunjucks::Runtime::SafeString') ) )
Branch: 2 branches
BranchTrueFalseTotal
builtin::blessed($obj) && ($obj->isa('Hash::Ordered') || $obj->isa('Text::Nunjucks::Runtime::SafeString')) ? : 199 10038 10237
builtin::blessed($obj) && ($obj->isa('Hash::Ordered') || $obj->isa('Text::Nunjucks::Runtime::SafeString')) ? : 0 0 0
Condition50%6/12
builtin::blessed($obj) and $obj->isa("Hash::Ordered") || $obj->isa("Text::Nunjucks::Runtime::SafeString")
!ll&&!rl&&r
100344199
$obj->isa("Hash::Ordered") or $obj->isa("Text::Nunjucks::Runtime::SafeString")
l!l&&r!l&&!r
741254
builtin::blessed($obj) and $obj->isa("Hash::Ordered") || $obj->isa("Text::Nunjucks::Runtime::SafeString")
!ll&&!rl&&r
000
$obj->isa("Hash::Ordered") or $obj->isa("Text::Nunjucks::Runtime::SafeString")
l!l&&r!l&&!r
000
MC/DC100%3/3
builtin::blessed($obj) and $obj->isa("Hash::Ordered") || $obj->isa("Text::Nunjucks::Runtime::SafeString")
builtin::blessed($obj) $obj->isa("Hash::Ordered") $obj->isa("Text::Nunjucks::Runtime::SafeString")
MC/DC0%0/3
builtin::blessed($obj) and $obj->isa("Hash::Ordered") || $obj->isa("Text::Nunjucks::Runtime::SafeString")
builtin::blessed($obj) $obj->isa("Hash::Ordered") $obj->isa("Text::Nunjucks::Runtime::SafeString")
Truth table100%4/4
A and B or C
A= builtin::blessed($obj)B= $obj->isa("Hash::Ordered")C= $obj->isa("Text::Nunjucks::Runtime::SafeString")
ABCresult
0XX0
1000
11X1
1011
Truth table0%0/4
A and B or C
A= builtin::blessed($obj)B= $obj->isa("Hash::Ordered")C= $obj->isa("Text::Nunjucks::Runtime::SafeString")
ABCresult
0XX0
1000
11X1
1011
169 ? 1 : 0;
170 }
171  
172 #### _prepareAttributeParts
173  
174 282 ▶sub _prepare_attribute_parts {
Subroutine _prepare_attribute_parts: called CC=3 SCAR=14.2
175 0 ▶ my ( $self, $attr ) = @_;
Subroutine _prepare_attribute_parts: not called CC=3 SCAR=14.2
176  
177 # JS: if (!attr) return []; -- JS falsiness, NOT Perl's: Runtime's, which
178 # knows null (oracle: groupby(null) groups by the item itself)
179 0 ▶ return [] if $self->_runtime->_falsy($attr);
Branch: 2 branches
BranchTrueFalseTotal
if $self->_runtime->_falsy($attr) 104 178 282
if $self->_runtime->_falsy($attr) 0 0 0
180  
181 # JS: if (typeof attr === 'string') return attr.split('.'); (-1 keeps trailing empties)
182 0 ▶ return [ split /\./, $attr, -1 ] if $self->is_string($attr);
Branch: 2 branches
BranchTrueFalseTotal
if $self->is_string($attr) 159 19 178
if $self->is_string($attr) 0 0 0
183  
184 0 return [$attr];
185 }
186  
187 #### getAttrGetter
188  
189 276 ▶sub get_attr_getter {
Subroutine get_attr_getter: called CC=1 SCAR=1.2
Pod undocumented
190 0 ▶ my ( $self, $attribute ) = @_;
Subroutine get_attr_getter: not called CC=1 SCAR=1.2
Pod undocumented
191 0 my $parts = $self->_prepare_attribute_parts($attribute);
192  
193 8938 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=14.2
194 0 ▶ my ($item) = @_;
Subroutine __ANON__: not called CC=3 SCAR=14.2
195 0 my $_item = $item;
196  
197 0 for my $part (@$parts) {
198 # If item is not an object, and we still got parts to handle, roll out to
199 # undefined.
200 0 ▶ if ( $self->has_own_prop( $_item, $part ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->has_own_prop($_item, $part)) { } 8911 78 8989
if ($self->has_own_prop($_item, $part)) { } 0 0 0
201 # _item[part]: the JS property read, Runtime's (ADR 0016) -- a
202 # SafeString's val reads undefined there (k72)
203 0 $_item = $self->_runtime->member_lookup( $_item, $part );
204 } else {
205 0 return undef;
206 }
207 }
208  
209 0 return $_item;
210 0 };
211 }
212  
213 #### groupBy
214  
215 122 ▶sub group_by {
Subroutine group_by: called CC=8 SCAR=28.2
Pod undocumented
216 0 ▶ my ( $self, $obj, $val, $throw_on_undefined ) = @_;
Subroutine group_by: not called CC=8 SCAR=28.2
Pod undocumented
217 0 my $rt = $self->_runtime;
218 # const result = {} -- an engine-built object, so an ordered dict from
219 # Runtime's make_dict (ADR 0011): groups iterate in JS key order
220 0 my $result = $rt->make_dict;
221 0 ▶ my $iterator = $self->is_function($val) ? $val : $self->get_attr_getter($val);
Branch: 2 branches
BranchTrueFalseTotal
$self->is_function($val) ? : 6 116 122
$self->is_function($val) ? : 0 0 0
222  
223 # i < obj.length and obj[i] are JS property reads and a JS comparison,
224 # Runtime's (oracle: undefined|groupby('a') -> "TypeError: Cannot read
225 # properties of undefined (reading 'length')", a number or an object without
226 # length groups nothing, a SafeString's obj[i] is undefined). A primitive
227 # string cannot change under the loop: its split('') units are the same
228 # length and obj[i] (ADR 0012), measured once.
229 0 my $array_like = $rt->_for_code_units($obj);
230 0 ▶ for ( my $i = 0; $rt->op_lt( $i, $rt->js_member_read( $array_like, 'length' ) ); $i++ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($rt->op_lt($i, $rt->js_member_read($array_like, "length"))) 675 102 777
if ($rt->op_lt($i, $rt->js_member_read($array_like, "length"))) 0 0 0
231 0 my $value = $rt->js_member_read( $array_like, $i );
232 0 my $key = $iterator->( $value, $i );
233  
234 # JS: if (key === undefined && throwOnUndefined === true)
235 0 ▶ if ( !defined($key)
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $key and defined $throw_on_undefined and builtin::is_bool($throw_on_undefined) and $throw_on_undefined) 11 659 670
if (not defined $key and defined $throw_on_undefined and builtin::is_bool($throw_on_undefined) and $throw_on_undefined) 0 0 0
Condition50%9/18
not defined $key and defined $throw_on_undefined and builtin::is_bool($throw_on_undefined) and $throw_on_undefined
!ll&&!rl&&r
6273211
not defined $key and defined $throw_on_undefined and builtin::is_bool($throw_on_undefined)
!ll&&!rl&&r
626143
not defined $key and defined $throw_on_undefined
!ll&&!rl&&r
624244
not defined $key and defined $throw_on_undefined and builtin::is_bool($throw_on_undefined) and $throw_on_undefined
!ll&&!rl&&r
000
not defined $key and defined $throw_on_undefined and builtin::is_bool($throw_on_undefined)
!ll&&!rl&&r
000
not defined $key and defined $throw_on_undefined
!ll&&!rl&&r
000
MC/DC100%4/4
not defined $key and defined $throw_on_undefined and builtin::is_bool($throw_on_undefined) and $throw_on_undefined
not defined $key defined $throw_on_undefined builtin::is_bool($throw_on_undefined) $throw_on_undefined
MC/DC0%0/4
not defined $key and defined $throw_on_undefined and builtin::is_bool($throw_on_undefined) and $throw_on_undefined
not defined $key defined $throw_on_undefined builtin::is_bool($throw_on_undefined) $throw_on_undefined
Truth table100%5/5
not(A) and B and C and D
A= not defined $keyB= defined $throw_on_undefinedC= builtin::is_bool($throw_on_undefined)D= $throw_on_undefined
ABCDresult
0XXX0
10XX0
110X0
11100
11111
Truth table0%0/5
not(A) and B and C and D
A= not defined $keyB= defined $throw_on_undefinedC= builtin::is_bool($throw_on_undefined)D= $throw_on_undefined
ABCDresult
0XXX0
10XX0
110X0
11100
11111
236 && defined($throw_on_undefined)
237 && is_bool($throw_on_undefined)
238 && $throw_on_undefined )
239 {
240 # `${val}` is val's JS ToString (oracle: groupby(['a', 'b']) names
241 # "a,b", groupby({'a': 1}) "[object Object]", groupby(0.1 + 0.2)
242 # "0.30000000000000004")
243 0 die Text::Nunjucks::Lib::Error->new(
244 'groupby: attribute "' . $rt->_js_to_string($val) . '" resolved to undefined',
245 name => 'TypeError'
246 );
247 }
248  
249 # result[key] reads the key's ToPropertyKey: undefined -> 'undefined', true
250 # -> 'true', null -> 'null', a number its JS ToString (ADR 0007: 0.3 and
251 # 0.30000000000000004 stay apart, -0 is '0'), an array its join, a
252 # SafeString its value (oracle). A key naming an Object.prototype member
253 # groups here where JS throws -- k81.
254 0 my $hkey = $rt->_member_key($key);
255 # (result[key] || (result[key] = [])).push(value)
256 0 ▶ push @{ $result->get($hkey) // $result->set( $hkey, [] ) }, $value;
Condition33%2/6
$result->get($hkey) // $result->set($hkey, [])
l!l&&r!l&&!r
3293300
$result->get($hkey) // $result->set($hkey, [])
l!l&&r!l&&!r
000
MC/DC0%0/2
$result->get($hkey) // $result->set($hkey, [])
$result->get($hkey) $result->set($hkey, [])
MC/DC0%0/2
$result->get($hkey) // $result->set($hkey, [])
$result->get($hkey) $result->set($hkey, [])
Truth table66%2/3
A // B
A= $result->get($hkey)B= $result->set($hkey, [])
ABresult
1X1
011
000
Truth table0%0/3
A // B
A= $result->get($hkey)B= $result->set($hkey, [])
ABresult
1X1
011
000
257 }
258  
259 0 return $result;
260 }
261  
262 #### toArray
263  
264 # Array.prototype.slice.call(obj): ToObject(obj), a TypeError on undefined and
265 # null; len = ToLength(obj.length); then every index below len obj has, in
266 # order -- Runtime's property reads (oracle, through select: {'length': '2',
267 # '0': 1, '1': 2} -> 1,2, {'length': 1.7, ...} -> 1, {'length': -1} ->
268 # nothing, a length above 2^32 - 1 -> "RangeError: Invalid array length"). An
269 # array is copied, a primitive string gives its UTF-16 code units, the same
270 # list as split('') (ADR 0012). A SafeString has a length but no indices; a
271 # number, boolean, function or regex has no length, ToLength(undefined) is 0.
272 # An index obj lacks is a hole in JS's result: the value model has none (ADR
273 # 0001), so it is left out -- which the one caller, select / reject's filter,
274 # cannot tell apart, as filter skips holes.
275 145 ▶sub to_array {
Subroutine to_array: called CC=9 SCAR=29.5
Pod undocumented
276 0 ▶ my ( $self, $obj ) = @_;
Subroutine to_array: not called CC=9 SCAR=29.5
Pod undocumented
277 0 my $rt = $self->_runtime;
278 0 ▶ die Text::Nunjucks::Lib::Error->new( 'Cannot convert undefined or null to object', name => 'TypeError' )
Branch: 2 branches
BranchTrueFalseTotal
if not defined $obj or $rt->_is_none($obj) 5 140 145
if not defined $obj or $rt->_is_none($obj) 0 0 0
Condition50%3/6
not defined $obj or $rt->_is_none($obj)
l!l&&r!l&&!r
32140
not defined $obj or $rt->_is_none($obj)
l!l&&r!l&&!r
000
MC/DC100%2/2
not defined $obj or $rt->_is_none($obj)
not defined $obj $rt->_is_none($obj)
MC/DC0%0/2
not defined $obj or $rt->_is_none($obj)
not defined $obj $rt->_is_none($obj)
Truth table100%3/3
not(A) or B
A= not defined $objB= $rt->_is_none($obj)
ABresult
1X1
011
000
Truth table0%0/3
not(A) or B
A= not defined $objB= $rt->_is_none($obj)
ABresult
1X1
011
000
279 if !defined($obj) || $rt->_is_none($obj);
280 0 ▶ return [ @$obj ] if ref($obj) eq 'ARRAY';
Branch: 2 branches
BranchTrueFalseTotal
if ref $obj eq "ARRAY" 81 59 140
if ref $obj eq "ARRAY" 0 0 0
281 0 ▶ return $self->js_split( $obj, '' ) if $self->is_string($obj);
Branch: 2 branches
BranchTrueFalseTotal
if $self->is_string($obj) 9 50 59
if $self->is_string($obj) 0 0 0
282  
283 0 my $len = $self->_js_to_integer_or_infinity( $rt->_to_number( $rt->member_lookup( $obj, 'length' ) ) );
284 0 ▶ $len = 0 if $len < 0;
Branch: 2 branches
BranchTrueFalseTotal
if $len < 0 3 47 50
if $len < 0 0 0 0
285 # ArraySpeciesCreate(O, count) -> ArrayCreate, which caps an array's length
286 0 ▶ die Text::Nunjucks::Lib::Error->new( 'Invalid array length', name => 'RangeError' ) if $len > 4294967295;
Branch: 2 branches
BranchTrueFalseTotal
if $len > 4294967295 8 42 50
if $len > 4294967295 0 0 0
287  
288 0 my $result = [];
289 0 for my $k ( 0 .. $len - 1 ) {
290 0 ▶ push @$result, $rt->member_lookup( $obj, $k ) if $self->has_own_prop( $obj, $k );
Branch: 2 branches
BranchTrueFalseTotal
if $self->has_own_prop($obj, $k) 28 10 38
if $self->has_own_prop($obj, $k) 0 0 0
291 }
292 0 return $result;
293 }
294  
295 #### without
296  
297 5 ▶sub without {
Subroutine without: called CC=4 SCAR=17.9
Pod undocumented
298 0 ▶ my ( $self, $array, @contains ) = @_;
Subroutine without: not called CC=4 SCAR=17.9
Pod undocumented
299 0 my $result = [];
300 0 ▶ return $result unless $array; # JS !array (array is arrayref|undef here)
Branch: 2 branches
BranchTrueFalseTotal
unless $array 1 4 5
unless $array 0 0 0
301  
302 0 my $length = scalar @$array;
303 0 my $index = -1;
304  
305 0 ▶ while ( ++$index < $length ) {
Branch: 2 branches
BranchTrueFalseTotal
if (++$index < $length) 12 4 16
if (++$index < $length) 0 0 0
306 0 ▶ if ( $self->index_of( \@contains, $array->[$index] ) == -1 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->index_of(\@contains, $array->[$index]) == -1) 6 6 12
if ($self->index_of(\@contains, $array->[$index]) == -1) 0 0 0
307 0 push @$result, $array->[$index];
308 }
309 }
310 0 return $result;
311 }
312  
313 #### repeat
314  
315 135 ▶sub repeat {
Subroutine repeat: called CC=2 SCAR=9.2
Pod undocumented
316 0 ▶ my ( $self, $char, $n ) = @_;
Subroutine repeat: not called CC=2 SCAR=9.2
Pod undocumented
317 0 my $str = '';
318 # JS: for (let i = 0; i < n; i++) -- runs (ceil of) fractional n times, unlike
319 # Perl's `1..$n` which truncates. center() feeds fractional counts (spaces/2).
320 0 ▶ for ( my $i = 0; $i < $n; $i++ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($i < $n) 1452 135 1587
if ($i < $n) 0 0 0
321 0 $self->js_string_append( $str, $char ); # str += char_ (ADR 0012)
322 }
323 0 return $str;
324 }
325  
326 #### each
327  
328 2 ▶sub each {
Subroutine each: called CC=4 SCAR=19.1
Pod undocumented
329 0 ▶ my ( $self, $obj, $func, $context ) = @_;
Subroutine each: not called CC=4 SCAR=19.1
Pod undocumented
330 0 ▶ return if !defined $obj; # JS obj == null
Branch: 2 branches
BranchTrueFalseTotal
unless defined $obj 1 1 2
unless defined $obj 0 0 0
331  
332 # array / array-like branch; context (`this`) is k8 and not modelled
333 0 ▶ if ( ref($obj) eq 'ARRAY' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $obj eq "ARRAY") 1 0 1
if (ref $obj eq "ARRAY") 0 0 0
334 0 for my $i ( 0 .. $#$obj ) {
335 0 $func->( $obj->[$i], $i, $obj );
336 }
337 }
338 }
339  
340 #### map
341  
342 404 ▶sub map {
Subroutine map: called CC=9 SCAR=29.5
Pod undocumented
343 0 ▶ my ( $self, $obj, $func ) = @_;
Subroutine map: not called CC=9 SCAR=29.5
Pod undocumented
344 0 my $results = [];
345 # if (obj == null) -- undefined here; null (Runtime's None) after the array
346 # branch, which so needs nothing from Runtime
347 0 ▶ return $results if !defined $obj;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $obj 7 397 404
unless defined $obj 0 0 0
348  
349 # if (ArrayProto.map && obj.map === ArrayProto.map) return obj.map(func);
350 # -- a real array; native Array.map passes (element, index, array)
351 0 ▶ if ( $self->is_array($obj) ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->is_array($obj)) 322 75 397
if ($self->is_array($obj)) 0 0 0
352 0 for my $i ( 0 .. $#$obj ) {
353 0 $results->[$i] = $func->( $obj->[$i], $i, $obj );
354 }
355 0 return $results;
356 }
357  
358 # Anything else is read as an array-like. obj.length and obj[i] are JS
359 # property reads and `i < obj.length` a JS comparison: Runtime's
360 # member_lookup and op_lt, the one home of both (ADR 0008 / 0007), so this
361 # branch calls up into Runtime (as groupBy does for make_dict). Oracle: a
362 # SafeString has a length but no index access ('abc' from a macro, |reverse
363 # -> ',,'), {length: '2', 0: 'x', 1: 'y'} maps x, y, a number or a plain
364 # object without length maps nothing. A primitive string cannot change under
365 # the loop, so it is read through its split('') units -- the same length and
366 # the same obj[i] (ADR 0012) without measuring the string once per index.
367 0 my $rt = $self->_runtime;
368 0 ▶ return $results if $rt->_is_none($obj);
Branch: 2 branches
BranchTrueFalseTotal
if $rt->_is_none($obj) 7 68 75
if $rt->_is_none($obj) 0 0 0
369 0 ▶ my $array_like = $self->is_string($obj) ? $self->js_split( $obj, '' ) : $obj;
Branch: 2 branches
BranchTrueFalseTotal
$self->is_string($obj) ? : 12 56 68
$self->is_string($obj) ? : 0 0 0
370  
371 0 ▶ for ( my $i = 0; $rt->op_lt( $i, $rt->member_lookup( $array_like, 'length' ) ); $i++ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($rt->op_lt($i, $rt->member_lookup($array_like, "length"))) 105 65 170
if ($rt->op_lt($i, $rt->member_lookup($array_like, "length"))) 0 0 0
372 0 $results->[ scalar @$results ] = $func->( $rt->member_lookup( $array_like, $i ), $i );
373 }
374  
375 # if (obj.length === +obj.length) results.length = obj.length; -- setting an
376 # array's length to anything but an integer in [0, 2^32 - 1] is a RangeError
377 # (oracle: {length: 2.5}|reverse, {length: -1}|reverse)
378 0 my $length = $rt->member_lookup( $array_like, 'length' );
379 0 ▶ if ( $self->_strict_eq( $length, $rt->op_pos($length) ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_strict_eq($length, $rt->op_pos($length))) 37 28 65
if ($self->_strict_eq($length, $rt->op_pos($length))) 0 0 0
380 0 ▶ die Text::Nunjucks::Lib::Error->new( 'Invalid array length', name => 'RangeError' )
Branch: 2 branches
BranchTrueFalseTotal
if $self->_js_to_uint32($length) != $length 4 33 37
if $self->_js_to_uint32($length) != $length 0 0 0
381 if $self->_js_to_uint32($length) != $length;
382 0 $#$results = $length - 1;
383 }
384  
385 0 return $results;
386 }
387  
388 #### asyncIter
389  
390 5091 ▶sub async_iter {
Subroutine async_iter: called CC=1 SCAR=0.8
Pod undocumented
391 0 ▶ my ( $self, $arr, $iter, $cb ) = @_;
Subroutine async_iter: not called CC=1 SCAR=0.8
Pod undocumented
392 0 my $i = -1;
393  
394 # Port-only (k107): JS's `function next()` names itself; here the closure
395 # hands itself on as __SUB__. Closing over the variable that holds it would
396 # be a reference cycle that keeps $iter, $cb and everything they reach (the
397 # render's Context, Frame and Template) alive for the life of the process.
398 8176 ▶ my $next = sub {
Subroutine __ANON__: called CC=2 SCAR=8.1
399 0 ▶ $i++;
Subroutine __ANON__: not called CC=2 SCAR=8.1
400 0 ▶ if ( $i < scalar @$arr ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($i < scalar @$arr) { } 7259 917 8176
if ($i < scalar @$arr) { } 0 0 0
401 # Port-only (k83): every item nests one call deeper, $iter being entered
402 # again before it has returned -- upstream's next() nests one JS call per
403 # item the same way (ADR 0003). Perl warns at the 100th nested call of a
404 # sub, here where the call is made; the depth is bounded by memory, not
405 # by Perl, so that warning is noise and is off for this call alone.
406 23 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
407 0 $iter->( $arr->[$i], $i, __SUB__, $cb );
408 } else {
409 0 $cb->();
410 }
411 0 };
412  
413 0 $next->();
414 }
415  
416 #### asyncFor
417  
418 518 ▶sub async_for {
Subroutine async_for: called CC=4 SCAR=15.6
Pod undocumented
419 0 ▶ my ( $self, $obj, $iter, $cb ) = @_;
Subroutine async_for: not called CC=4 SCAR=15.6
Pod undocumented
420 # JS: lib.keys(arr || {}) -- JS falsiness, not Perl's `// {}` which only
421 # guarded undef and let a 0 / '' / false through to crash keys() on the deref.
422 # None (JS null) is a Runtime sentinel that Lib does not know (ADR 0006); the
423 # only caller that can pass a null iterable, Runtime::async_each, guards it
424 # there before delegating, so _falsy (kind-based, no None) suffices here.
425 0 ▶ my $keys = $self->keys( $self->_falsy($obj) ? {} : $obj );
Branch: 2 branches
BranchTrueFalseTotal
$self->_falsy($obj) ? : 4 514 518
$self->_falsy($obj) ? : 0 0 0
426 0 my $len = scalar @$keys;
427 0 my $i = -1;
428  
429 # Value lookup mirrors the ordering policy of keys() above (ADR 0011): a
430 # Hash::Ordered (template dict literal / engine-built object) reads via ->get;
431 # a plain hashref reads via ->{}. asyncFor doesn't reach Runtime->member_lookup
432 # (Lib calls up into Runtime only in map and groupBy),
433 # so this is the single seam -- the Runtime side mirrors it for its own
434 # async_all loop.
435 my $lookup = ( blessed($obj) && $obj->isa('Hash::Ordered') )
436 512 ▶ ? sub { my $k = shift; $obj->exists($k) ? $obj->get($k) : undef }
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$obj->exists($k) ? : 512 0 512
437 0 ▶ : sub { my $k = shift; $obj->{$k} };
Subroutine __ANON__: called CC=1 SCAR=1.2
Branch: 2 branches
BranchTrueFalseTotal
builtin::blessed($obj) && $obj->isa('Hash::Ordered') ? : 496 22 518
builtin::blessed($obj) && $obj->isa('Hash::Ordered') ? : 0 0 0
Condition33%2/6
builtin::blessed($obj) and $obj->isa("Hash::Ordered")
!ll&&!rl&&r
220496
builtin::blessed($obj) and $obj->isa("Hash::Ordered")
!ll&&!rl&&r
000
MC/DC50%1/2
builtin::blessed($obj) and $obj->isa("Hash::Ordered")
builtin::blessed($obj) $obj->isa("Hash::Ordered")
MC/DC0%0/2
builtin::blessed($obj) and $obj->isa("Hash::Ordered")
builtin::blessed($obj) $obj->isa("Hash::Ordered")
Truth table66%2/3
A and B
A= builtin::blessed($obj)B= $obj->isa("Hash::Ordered")
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= builtin::blessed($obj)B= $obj->isa("Hash::Ordered")
ABresult
0X0
100
111
438  
439 # __SUB__, not a captured $next: see async_iter (k107).
440 1525 ▶ my $next = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
441 1525 $i++;
442 1525 my $k = $keys->[$i];
443 1525 ▶ if ( $i < $len ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) { } 1007 518 1525
444 # one call deeper per key, as in async_iter (k83)
445 23 ▶ no warnings 'recursion';
Subroutine BEGIN: called CC=1 SCAR=0.0
446 1007 $iter->( $k, $lookup->($k), $i, $len, __SUB__ );
447 } else {
448 518 $cb->();
449 }
450 0 };
451  
452 0 $next->();
453 }
454  
455 #### indexOf
456  
457 120466 ▶sub index_of {
Subroutine index_of: called CC=7 SCAR=20.8
Pod undocumented
458 120466 my ( $self, $arr, $search, $from_index ) = @_;
459 # Array.prototype.indexOf.call(arr || [], searchElement, fromIndex) -- uses
460 # strict equality (===). See _strict_eq below.
461 120466 ▶ $arr = [] unless defined $arr;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $arr 0 120466 120466
462 120466 my $len = scalar @$arr;
463  
464 120466 ▶ my $start = defined($from_index) ? int($from_index) : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $from_index ? : 1 120465 120466
465 120466 ▶ if ( $start < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($start < 0) 0 120466 120466
466 0 $start += $len;
467 0 ▶ $start = 0 if $start < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $start < 0 0 0 0
468 }
469  
470 120466 ▶ for ( my $i = $start; $i < $len; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 805986 110946 916932
471 805986 ▶ return $i if $self->_strict_eq( $arr->[$i], $search );
Branch: 1 branch
BranchTrueFalseTotal
if $self->_strict_eq($arr->[$i], $search) 9520 796466 805986
472 }
473 110946 return -1;
474 }
475  
476 #### keys (keys_)
477  
478 44546 ▶sub keys {
Subroutine keys: called CC=13 SCAR=25.7
Pod undocumented
479 44546 my ( $self, $obj ) = @_;
480 # own enumerable keys. ADR 0011 (amended on k51) sets the ordering policy in
481 # one place:
482 #
483 # * Hash::Ordered (template dict literal / engine-built object): own keys
484 # in JS order -- _ordinary_own_property_keys over its insertion order,
485 # byte-identical to JS Object.keys.
486 # * Plain caller hash: the array-index keys first, ascending, then the
487 # rest key-sorted -- the documented divergence is only in that rest
488 # (Perl hashes carry no insertion order to preserve; sorted gives a
489 # deterministic cross-PERL_HASH_SEED iteration where JS would have shown
490 # insertion order).
491 #
492 # _entries / _values / extend / async_for / member_lookup / the dump /
493 # dictsort / list / items filters (k17) all reach the iterator here, so this
494 # is the only seam the policy needs.
495 #
496 # Non-hash refs are an open latency: JS keys([10,20]) -> ['0','1'], but a
497 # non-HASH ref dies here on the deref. The value model routes arrays through
498 # async_iter / to_array, so this is believed unreachable; keys(undef) already
499 # yields [] cleanly. Revisit if a k14/k17 call site reaches it.
500 #
501 # for-in over undefined, null, a number, a boolean or a function enumerates
502 # nothing (oracle: 5|urlencode, none|urlencode and a macro|urlencode render
503 # '' -- lib._entries(obj) is []). A primitive string's indices are k59.
504 44546 ▶ return [] if !defined($obj) || ( !ref($obj) && !$self->is_string($obj) );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $obj and ref $obj || $self->is_string($obj) 12 44534 44546
Condition83%5/6
defined $obj and ref $obj || $self->is_string($obj)
!ll&&!rl&&r
3944534
ref $obj or $self->is_string($obj)
l!l&&r!l&&!r
4453409
MC/DC66%2/3
defined $obj and ref $obj || $self->is_string($obj)
defined $obj ref $obj $self->is_string($obj)
Truth table75%3/4
A and B or C
A= defined $objB= ref $objC= $self->is_string($obj)
ABCresult
0XX0
1000
11X1
1011
505 44534 ▶ return [] if $self->_runtime->_is_none($obj) || $self->is_function($obj);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_runtime->_is_none($obj) or $self->is_function($obj) 4 44530 44534
Condition100%3/3
$self->_runtime->_is_none($obj) or $self->is_function($obj)
l!l&&r!l&&!r
2244530
MC/DC100%2/2
$self->_runtime->_is_none($obj) or $self->is_function($obj)
$self->_runtime->_is_none($obj) $self->is_function($obj)
Truth table100%3/3
A or B
A= $self->_runtime->_is_none($obj)B= $self->is_function($obj)
ABresult
1X1
011
000
506 44530 ▶ return $self->_ordinary_own_property_keys( [ $obj->keys ] ) if blessed($obj) && $obj->isa('Hash::Ordered');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($obj) and $obj->isa("Hash::Ordered") 882 43648 44530
Condition100%3/3
builtin::blessed($obj) and $obj->isa("Hash::Ordered")
!ll&&!rl&&r
4361533882
MC/DC100%2/2
builtin::blessed($obj) and $obj->isa("Hash::Ordered")
builtin::blessed($obj) $obj->isa("Hash::Ordered")
Truth table100%3/3
A and B
A= builtin::blessed($obj)B= $obj->isa("Hash::Ordered")
ABresult
0X0
100
111
507  
508 # A SafeString (engine-built): its own properties in the order its
509 # constructor creates them, this.val then this.length.
510 43648 ▶ return [ 'val', 'length' ] if blessed($obj) && $obj->isa('Text::Nunjucks::Runtime::SafeString');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($obj) and $obj->isa("Text::Nunjucks::Runtime::SafeString") 24 43624 43648
Condition100%3/3
builtin::blessed($obj) and $obj->isa("Text::Nunjucks::Runtime::SafeString")
!ll&&!rl&&r
43615924
MC/DC100%2/2
builtin::blessed($obj) and $obj->isa("Text::Nunjucks::Runtime::SafeString")
builtin::blessed($obj) $obj->isa("Text::Nunjucks::Runtime::SafeString")
Truth table100%3/3
A and B
A= builtin::blessed($obj)B= $obj->isa("Text::Nunjucks::Runtime::SafeString")
ABresult
0X0
100
111
511  
512 # Any other blessed object -- a regex, keyword arguments (k79), a caller's
513 # object (k47) -- enumerates nothing: its hash fields are no JS properties
514 # (a regex's own lastIndex is not enumerable).
515 43624 ▶ return [] if blessed($obj);
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($obj) 9 43615 43624
516  
517 # Plain hash: sort CORE::keys (per-process-random Perl order) deterministically.
518 43615 my $arr = [];
519 43615 for my $k ( sort CORE::keys %$obj ) {
520 376039 ▶ push @$arr, $k if $self->has_own_prop( $obj, $k );
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_own_prop($obj, $k) 376039 0 376039
521 }
522 43615 return $self->_ordinary_own_property_keys($arr);
523 }
524  
525 # Port addition (ADR 0011, k51): the order JS's for-in gives an ordinary
526 # object's own string keys, ECMAScript OrdinaryOwnPropertyKeys -- every array
527 # index first, in ascending numeric order, then the other keys in the order
528 # given (insertion order for an ordered dict, key-sorted for a plain hash).
529 # oracle: {"a":1,"10":2,"9":3,"01":4,"-1":5,"4294967295":6,"4294967294":7,"1.5":8}
530 # iterates 9;10;4294967294;a;01;-1;4294967295;1.5;
531 44497 ▶sub _ordinary_own_property_keys {
Subroutine _ordinary_own_property_keys: called CC=3 SCAR=11.0
532 44497 my ( $self, $keys ) = @_;
533 44497 my ( @index, @rest );
534 44497 for my $k (@$keys) {
535 377483 ▶ if ( $self->_is_array_index($k) ) { push @index, $k }
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_array_index($k)) { } 452 377031 377483
536 377031 else { push @rest, $k }
537 }
538 44497 return [ ( sort { $a <=> $b } @index ), @rest ];
539 }
540  
541 # An array index is a String P with ToString(ToUint32(P)) === P and
542 # ToUint32(P) !== 2^32 - 1: the canonical ASCII decimal form of an integer
543 # 0 .. 4294967294. oracle: '0' and '4294967294' are indices; '4294967295',
544 # '00', '01', '-0', '-1', '+1', '1.5', '1e3', ' 1', '0x1', '' and non-ASCII
545 # digits are not. At most ten digits pass the pattern; a ten-digit one is
546 # compared with 4294967294 as a string.
547 377552 ▶sub _is_array_index {
Subroutine _is_array_index: called CC=4 SCAR=13.9
548 377552 my ( $self, $k ) = @_;
549 377552 ▶ return 0 unless $k =~ /\A(?:0|[1-9][0-9]{0,9})\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $k =~ /\A(?:0|[1-9][0-9]{0,9})\z/ 377033 519 377552
550 519 ▶ return ( length($k) < 10 || $k le '4294967294' ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
length $k < 10 || $k le '4294967294' ? : 509 10 519
Condition100%3/3
length $k < 10 or $k le "4294967294"
l!l&&r!l&&!r
4971210
MC/DC100%2/2
length $k < 10 or $k le "4294967294"
length $k < 10 $k le "4294967294"
Truth table100%3/3
A or B
A= length $k < 10B= $k le "4294967294"
ABresult
1X1
011
000
551 }
552  
553 #### js_for_in_keys -- the keys `for (k in obj)` visits
554  
555 # Port addition: lib.js's for-in loops filter by hasOwnProp, so keys above is
556 # their whole iteration; a raw for-in (the dictsort filter's, which upstream
557 # notes deliberately includes properties from the object's prototype) visits
558 # the enumerable properties up the prototype chain after the own ones, each
559 # name once. The own ones are keys', the one ordering seam (ADR 0011). Of the
560 # prototypes the value model reaches, only SafeString.prototype has
561 # enumerable properties: valueOf and toString, assigned after the
562 # Object.create that made its length non-enumerable, and never shadowed by a
563 # SafeString's own val and length -- Object.prototype, Array.prototype and
564 # String.prototype have none (oracle: 'ab'|safe|dictsort gives length,
565 # toString, val, valueOf).
566 67 ▶sub js_for_in_keys {
Subroutine js_for_in_keys: called CC=3 SCAR=11.0
Pod undocumented
567 67 my ( $self, $obj ) = @_;
568 67 my $keys = $self->keys($obj);
569 67 ▶ push @$keys, qw( valueOf toString ) if blessed($obj) && $obj->isa('Text::Nunjucks::Runtime::SafeString');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($obj) and $obj->isa("Text::Nunjucks::Runtime::SafeString") 3 64 67
Condition100%3/3
builtin::blessed($obj) and $obj->isa("Text::Nunjucks::Runtime::SafeString")
!ll&&!rl&&r
24403
MC/DC100%2/2
builtin::blessed($obj) and $obj->isa("Text::Nunjucks::Runtime::SafeString")
builtin::blessed($obj) $obj->isa("Text::Nunjucks::Runtime::SafeString")
Truth table100%3/3
A and B
A= builtin::blessed($obj)B= $obj->isa("Text::Nunjucks::Runtime::SafeString")
ABresult
0X0
100
111
570 67 return $keys;
571 }
572  
573 #### _entries
574  
575 10312 ▶sub _entries {
Subroutine _entries: called CC=1 SCAR=0.0
576 10312 my ( $self, $obj ) = @_;
577 10312 return [ CORE::map { [ $_, $self->_own_value( $obj, $_ ) ] } @{ $self->keys($obj) } ];
578 }
579  
580 #### _values
581  
582 5 ▶sub _values {
Subroutine _values: called CC=1 SCAR=0.0
583 5 my ( $self, $obj ) = @_;
584 5 return [ CORE::map { $self->_own_value( $obj, $_ ) } @{ $self->keys($obj) } ];
585 }
586  
587 # obj[k] for a key keys() returned: an ordered dict (a blessed array, ADR 0011)
588 # reads through ->get, a hash -- a SafeString's included -- by its key.
589 363964 ▶sub _own_value {
Subroutine _own_value: called CC=3 SCAR=11.0
590 363964 my ( $self, $obj, $k ) = @_;
591 363964 ▶ return ( blessed($obj) && $obj->isa('Hash::Ordered') ) ? $obj->get($k) : $obj->{$k};
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($obj) && $obj->isa('Hash::Ordered') ? : 328 363636 363964
Condition100%3/3
builtin::blessed($obj) and $obj->isa("Hash::Ordered")
!ll&&!rl&&r
36359244328
MC/DC100%2/2
builtin::blessed($obj) and $obj->isa("Hash::Ordered")
builtin::blessed($obj) $obj->isa("Hash::Ordered")
Truth table100%3/3
A and B
A= builtin::blessed($obj)B= $obj->isa("Hash::Ordered")
ABresult
0X0
100
111
592 }
593  
594 #### extend / _assign
595  
596 11980 ▶sub extend {
Subroutine extend: called CC=3 SCAR=11.0
Pod undocumented
597 11980 my ( $self, $obj1, $obj2 ) = @_;
598 11980 ▶ $obj1 = {} unless $obj1; # JS obj1 || {} (obj1 is hashref|undef; refs are truthy)
Branch: 1 branch
BranchTrueFalseTotal
unless $obj1 1 11979 11980
599 11980 for my $k ( @{ $self->keys($obj2) } ) {
600 10141 $obj1->{$k} = $self->_own_value( $obj2, $k );
601 }
602 11980 return $obj1;
603 }
604  
605 # exports._assign = exports.extend
606 23 *_assign = \&extend;
607  
608 #### inOperator
609  
610 211 ▶sub in_operator {
Subroutine in_operator: called CC=11 SCAR=24.0
Pod undocumented
611 211 my ( $self, $key, $val ) = @_;
612  
613 # JS: if (isArray(val) || isString(val)) return val.indexOf(key) !== -1;
614 # Array.indexOf and String.indexOf differ in Perl, so the one JS branch
615 # splits in two.
616 211 ▶ if ( $self->is_array($val) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_array($val)) 134 77 211
617 134 ▶ return $self->index_of( $val, $key ) != -1 ? true : false;
Branch: 1 branch
BranchTrueFalseTotal
$self->index_of($val, $key) != -1 ? : 129 5 134
618 }
619 77 ▶ if ( $self->is_string($val) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_string($val)) 56 21 77
620 # JS String.prototype.indexOf coerces the search value via ToString:
621 # undefined -> "undefined", true -> "true", numbers -> their decimal form.
622 # Perl's index() stringifies too, but undef -> "" (which matches at 0)
623 # instead of "undefined". Coerce undef here to match JS. The full ToString
624 # for other non-string values (booleans especially: true -> "true", not
625 # Perl's "1") rides on k6 (native coercion) and is left to that decision.
626 56 ▶ my $needle = defined($key) ? $key : 'undefined';
Branch: 1 branch
BranchTrueFalseTotal
defined $key ? : 55 1 56
627 56 ▶ return $self->js_string_index_of( $val, $needle ) != -1 ? true : false; # code units (ADR 0012)
Branch: 1 branch
BranchTrueFalseTotal
$self->js_string_index_of($val, $needle) != -1 ? : 53 3 56
628 }
629 # Ordered hash (template dict literal / engine-built object, ADR 0011).
630 21 ▶ if ( blessed($val) && $val->isa('Hash::Ordered') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($val) and $val->isa("Hash::Ordered")) 1 20 21
Condition100%3/3
builtin::blessed($val) and $val->isa("Hash::Ordered")
!ll&&!rl&&r
1371
MC/DC100%2/2
builtin::blessed($val) and $val->isa("Hash::Ordered")
builtin::blessed($val) $val->isa("Hash::Ordered")
Truth table100%3/3
A and B
A= builtin::blessed($val)B= $val->isa("Hash::Ordered")
ABresult
0X0
100
111
631 1 ▶ return $val->exists($key) ? true : false;
Branch: 1 branch
BranchTrueFalseTotal
$val->exists($key) ? : 1 0 1
632 }
633  
634 20 ▶ if ( $self->is_object($val) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_object($val)) 16 4 20
635 16 ▶ return exists( $val->{$key} ) ? true : false; # key in val
Branch: 1 branch
BranchTrueFalseTotal
exists $val->{$key} ? : 9 7 16
636 }
637  
638 4 die Text::Nunjucks::Lib::Error->new(
639 'Cannot use "in" operator to search for "' . $key . '" in unexpected types.'
640 );
641 }
642  
643 #### JS regex character classes -- explicit ECMAScript sets (ADR 0005)
644  
645 # JavaScript's \s is a FIXED ECMAScript set (WhiteSpace + LineTerminator), not
646 # Perl's \s. It includes U+00A0 (NBSP, a member of the lexer's whitespace_chars)
647 # and U+FEFF, and excludes U+0085; Perl's default /d \s additionally matches (or
648 # not) U+00A0 depending on whether the target SV carries the UTF-8 flag, so the
649 # same template would lex differently by how it reached the engine. The engine's
650 # own regexes therefore map JS \s to this explicit class, matched flag-
651 # independently under /u. Membership is oracle-verified via the lstripBlocks
652 # /^\s+$/ path (see t/10-lexer.t / the k10 report), never recalled:
653 # WhiteSpace U+0009 U+000B U+000C U+0020 U+00A0 U+FEFF
654 # + Unicode Zs: U+1680, U+2000-U+200A, U+202F, U+205F, U+3000
655 # LineTerminator U+000A U+000D U+2028 U+2029
656 # \w is js_word_class and \d js_digit_class below (ADR 0005: added on demand,
657 # one seam per class, like _strict_eq / _falsy below).
658 23 my $JS_WHITESPACE_CLASS =
659 qr/[\x09\x0A\x0B\x0C\x0D\x20\x{A0}\x{1680}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}\x{FEFF}]/u;
660  
661 123024 ▶sub js_whitespace_class {
Subroutine js_whitespace_class: called CC=1 SCAR=0.0
Pod undocumented
662 123024 my ($self) = @_;
663 123024 return $JS_WHITESPACE_CLASS;
664 }
665  
666 # JavaScript's \w is [A-Za-z0-9_] -- ASCII only, without the u flag and with it
667 # (only u together with i widens it). Perl's \w is Unicode word characters. The
668 # filters' own regexes (wordcount's /\w+/g, striptags' \b) use this set; oracle:
669 # 'héllo wörld'|wordcount is 4, '١٢٣ abc'|wordcount is 1, and striptags keeps
670 # '<ab_c>' (no \b between b and _) but strips '<aſb>' (ſ is not a word char).
671 23 my $JS_WORD_CLASS = qr/[A-Za-z0-9_]/;
672  
673 144 ▶sub js_word_class {
Subroutine js_word_class: called CC=1 SCAR=0.0
Pod undocumented
674 144 my ($self) = @_;
675 144 return $JS_WORD_CLASS;
676 }
677  
678 # JavaScript's \d is [0-9] -- ASCII only, with or without the u and i flags.
679 # Perl's \d is every Unicode decimal digit. urlize's emailRe uses it; oracle:
680 # 'a@x\u0663.com'|urlize does not take the mailto: branch (ARABIC-INDIC DIGIT
681 # THREE is not \d), 'a@x3.com' does.
682 23 my $JS_DIGIT_CLASS = qr/[0-9]/;
683  
684 16 ▶sub js_digit_class {
Subroutine js_digit_class: called CC=1 SCAR=0.0
Pod undocumented
685 16 my ($self) = @_;
686 16 return $JS_DIGIT_CLASS;
687 }
688  
689 #### JS !x (falsiness) for async_for, and Runtime _falsy's kind-based half
690  
691 # Provisional JS falsiness keyed to ADR 0001 kinds. JS falsy values are
692 # undefined/null, false, 0, NaN and '' -- but the string '0' is TRUTHY in JS
693 # (Perl disagrees), so this cannot be a bare Perl boolean test. Truthiness's
694 # mechanism is slated for Runtime (k14); this is the single Lib seam it will
695 # merge with, mirroring _strict_eq below.
696 605758 ▶sub _falsy {
Subroutine _falsy: called CC=9 SCAR=22.0
697 605758 my ( $self, $x ) = @_;
698 605758 ▶ return 1 if !defined($x);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $x 304132 301626 605758
699 301626 ▶ return ( $x ? 0 : 1 ) if is_bool($x); # false is falsy
Branch: 2 branches
BranchTrueFalseTotal
if builtin::is_bool($x) 67872 233754 301626
$x ? : 18888 48984 67872
700 233754 ▶ return ( ( $x == 0 || $x != $x ) ? 1 : 0 ) if created_as_number($x); # 0 or NaN
Branch: 2 branches
BranchTrueFalseTotal
if created_as_number $x 5258 228496 233754
$x == 0 || $x != $x ? : 322 4936 5258
Condition100%3/3
$x == 0 or $x != $x
l!l&&r!l&&!r
300224936
MC/DC100%2/2
$x == 0 or $x != $x
$x == 0 $x != $x
Truth table100%3/3
A or B
A= $x == 0B= $x != $x
ABresult
1X1
011
000
701 228496 ▶ return ( $x eq '' ? 1 : 0 ) if $self->is_string($x); # '' falsy, '0' truthy
Branch: 2 branches
BranchTrueFalseTotal
if $self->is_string($x) 13248 215248 228496
$x eq '' ? : 243 13005 13248
702 215248 return 0; # refs are truthy
703 }
704  
705 #### JS === for index_of / in_operator membership
706  
707 # Provisional strict-equality keyed to ADR 0001 kinds. This mirrors the === that
708 # lib.js's indexOf relies on via Array.prototype.indexOf, so it lives here 1:1;
709 # Runtime will grow its own === for the template operator (k14). Whether the two
710 # should share one mechanism is an open placement question -- see the k9 report.
711 815243 ▶sub _strict_eq {
Subroutine _strict_eq: called CC=19 SCAR=29.4
712 815243 my ( $self, $a, $b ) = @_;
713  
714 815243 ▶ return 1 if !defined($a) && !defined($b);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $a or defined $b 442 814801 815243
Condition100%3/3
defined $a or defined $b
l!l&&r!l&&!r
8133501451442
MC/DC100%2/2
defined $a or defined $b
defined $a defined $b
Truth table100%3/3
A or B
A= defined $aB= defined $b
ABresult
1X1
011
000
715 814801 ▶ return 0 if !defined($a) || !defined($b);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $a and defined $b 1457 813344 814801
Condition100%3/3
defined $a and defined $b
!ll&&!rl&&r
14516813344
MC/DC100%2/2
defined $a and defined $b
defined $a defined $b
Truth table100%3/3
A and B
A= defined $aB= defined $b
ABresult
0X0
100
111
716  
717 813344 my ( $ra, $rb ) = ( ref($a), ref($b) );
718 813344 ▶ return ( ( $ra && $rb && refaddr($a) == refaddr($b) ) ? 1 : 0 ) if $ra || $rb;
Branch: 2 branches
BranchTrueFalseTotal
if $ra or $rb 678 812666 813344
$ra && $rb && builtin::refaddr($a) == builtin::refaddr($b) ? : 540 138 678
Condition100%9/9
$ra or $rb
l!l&&r!l&&!r
65622812666
$ra and $rb and builtin::refaddr($a) == builtin::refaddr($b)
!ll&&!rl&&r
12117540
$ra and $rb
!ll&&!rl&&r
2299557
MC/DC100%2/2
$ra or $rb
$ra $rb
MC/DC100%3/3
$ra and $rb and builtin::refaddr($a) == builtin::refaddr($b)
$ra $rb builtin::refaddr($a) == builtin::refaddr($b)
Truth table100%3/3
A or B
A= $raB= $rb
ABresult
1X1
011
000
Truth table100%4/4
A and B and C
A= $raB= $rbC= builtin::refaddr($a) == builtin::refaddr($b)
ABCresult
0XX0
10X0
1100
1111
719  
720 812666 my ( $ba, $bb ) = ( is_bool($a), is_bool($b) );
721 812666 ▶ return 0 if !$ba != !$bb; # one boolean, one not
Branch: 1 branch
BranchTrueFalseTotal
if !$ba != !$bb 39 812627 812666
722 812627 ▶ return ( ( $a == $b ) ? 1 : 0 ) if $ba; # both booleans
Branch: 2 branches
BranchTrueFalseTotal
if $ba 1117 811510 812627
$a == $b ? : 753 364 1117
723  
724 811510 my ( $na, $nb ) = ( created_as_number($a), created_as_number($b) );
725 811510 ▶ return 0 if !$na != !$nb; # number vs string
Branch: 1 branch
BranchTrueFalseTotal
if !$na != !$nb 72 811438 811510
726 811438 ▶ if ($na) {
Branch: 1 branch
BranchTrueFalseTotal
if ($na) 4480 806958 811438
727 4480 ▶ return 0 if $a != $a || $b != $b; # NaN !== NaN
Branch: 1 branch
BranchTrueFalseTotal
if $a != $a or $b != $b 1015 3465 4480
Condition100%3/3
$a != $a or $b != $b
l!l&&r!l&&!r
101143465
MC/DC100%2/2
$a != $a or $b != $b
$a != $a $b != $b
Truth table100%3/3
A or B
A= $a != $aB= $b != $b
ABresult
1X1
011
000
728 3465 ▶ return $a == $b ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$a == $b ? : 2588 877 3465
729 }
730 806958 ▶ return $a eq $b ? 1 : 0; # both strings
Branch: 1 branch
BranchTrueFalseTotal
$a eq $b ? : 9362 797596 806958
731 }
732  
733 #### number_to_string -- ECMAScript Number::toString, shortest round-trip (ADR 0007)
734  
735 # Not a src/lib.js function: ADR 0007 designates Lib the single home for the
736 # JS Number->String routine, and the JS *operators* that home in Runtime feed
737 # their numeric results back through it. It reproduces ECMAScript
738 # Number::toString: the shortest decimal that round-trips to the same IEEE
739 # double, then JS's exponent thresholds and the spellings Infinity / -Infinity
740 # / NaN. Every number reaching template output goes through it
741 # (Runtime::_js_to_string / suppress_value); nothing uses bare "$n".
742 #
743 # JS numbers are all IEEE doubles; a Perl scalar can hold an exact 64-bit
744 # integer no double can represent -- a literal like 1234567890123456789, or an
745 # IV product Perl computed exactly (123456789 * 987654321 stays exact in Perl,
746 # but JS rounds it). pack/unpack('d') forces the value through a C double first
747 # so the rounding matches Node's. Runtime's operators round their operands the
748 # same way before computing, so intermediates are doubles too.
749 23 my $NUM_POS_INF = 9**9**9;
750 23 my $NUM_NEG_INF = -$NUM_POS_INF;
751 23 my $NUM_NAN = $NUM_POS_INF - $NUM_POS_INF;
752 23 my $NUM_NEG_ZERO = -0.0;
753  
754 276494 ▶sub number_to_string {
Subroutine number_to_string: called CC=24 SCAR=31.8
Pod undocumented
755 276494 my ( $self, $n ) = @_;
756  
757 276494 $n = unpack( 'd', pack( 'd', $n ) ); # normalise to a real IEEE double
758  
759 276494 ▶ return 'NaN' if $n != $n; # NaN is the only value != itself
Branch: 1 branch
BranchTrueFalseTotal
if $n != $n 687 275807 276494
760 275807 ▶ return 'Infinity' if $n == $NUM_POS_INF;
Branch: 1 branch
BranchTrueFalseTotal
if $n == $NUM_POS_INF 639 275168 275807
761 275168 ▶ return '-Infinity' if $n == $NUM_NEG_INF;
Branch: 1 branch
BranchTrueFalseTotal
if $n == $NUM_NEG_INF 568 274600 275168
762 274600 ▶ return '0' if $n == 0; # +0 and -0 both render "0"
Branch: 1 branch
BranchTrueFalseTotal
if $n == 0 19593 255007 274600
763  
764 255007 ▶ my $neg = $n < 0 ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$n < 0 ? : 58987 196020 255007
765 255007 ▶ my $abs = $neg ? -$n : $n;
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 58987 196020 255007
766  
767 # Shortest significant-digit count p (1..17) whose p-digit rounding of $abs
768 # parses back to exactly $abs. 17 sig digits always round-trip a double, so
769 # the loop terminates; sprintf %e gives the correctly-rounded p-digit form.
770 # On a perl whose NV is wider than a double (ADR 0019) the comparison is made
771 # on the double's bytes: 0 + $sci would be a long double, which a 17-digit
772 # string never equals.
773 255007 my $wide = $Config::Config{nvsize} != 8;
774 255007 ▶ my $abs_bytes = $wide ? pack( 'd', $abs ) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$wide ? : 0 255007 255007
775 255007 my ( $digits, $e10 );
776 255007 for my $p ( 1 .. 17 ) {
777 482188 my $sci = sprintf( '%.*e', $p - 1, $abs );
778 482188 ▶ if ( $wide ? pack( 'd', 0 + $sci ) eq $abs_bytes : 0 + $sci == $abs ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($wide ? pack("d", 0 + $sci) eq $abs_bytes : 0 + $sci == $abs) 255007 227181 482188
$wide ? : 0 482188 482188
779 255007 ▶ $sci =~ /\A(\d)(?:\.(\d+))?e([+-]\d+)\z/
Branch: 1 branch
BranchTrueFalseTotal
$sci =~ /\A(\d)(?:\.(\d+))?e([+-]\d+)\z/ or croak('Text::Nunjucks::Lib->number_to_string cannot parse ' . $sci) 255007 0 255007
780 or croak __PACKAGE__ . '->number_to_string cannot parse ' . $sci;
781 255007 ▶ $digits = $1 . ( defined $2 ? $2 : '' );
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 137704 117303 255007
782 255007 $e10 = 0 + $3;
783 255007 last;
784 }
785 }
786  
787 # Strip trailing zeros for the spec's significant digits s (length k); the
788 # decimal point position is n = e10 + 1 (value = s x 10^(n-k)).
789 255007 $digits =~ s/0+\z//;
790 255007 ▶ $digits = '0' if $digits eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $digits eq "" 0 255007 255007
791 255007 my $k = length $digits;
792 255007 my $point = $e10 + 1;
793  
794 255007 my $out;
795 255007 ▶ if ( $k <= $point && $point <= 21 ) {
Branch: 4 branches
BranchTrueFalseTotal
if ($k <= $point and $point <= 21) { } 251415 3592 255007
elsif (0 < $point and $point <= 21) { } 1330 2262 3592
elsif (-6 < $point and $point <= 0) { } 965 1297 2262
elsif ($k == 1) { } 1255 42 1297
Condition100%3/3
$k <= $point and $point <= 21
!ll&&!rl&&r
2903689251415
MC/DC100%2/2
$k <= $point and $point <= 21
$k <= $point $point <= 21
Truth table100%3/3
A and B
A= $k <= $pointB= $point <= 21
ABresult
0X0
100
111
796 251415 $out = $digits . ( '0' x ( $point - $k ) );
797 ▶ } elsif ( 0 < $point && $point <= 21 ) {
Condition100%3/3
0 < $point and $point <= 21
!ll&&!rl&&r
15736891330
MC/DC100%2/2
0 < $point and $point <= 21
0 < $point $point <= 21
Truth table100%3/3
A and B
A= 0 < $pointB= $point <= 21
ABresult
0X0
100
111
798 1330 $out = substr( $digits, 0, $point ) . '.' . substr( $digits, $point );
799 ▶ } elsif ( -6 < $point && $point <= 0 ) {
Condition100%3/3
-6 < $point and $point <= 0
!ll&&!rl&&r
608689965
MC/DC100%2/2
-6 < $point and $point <= 0
-6 < $point $point <= 0
Truth table100%3/3
A and B
A= -6 < $pointB= $point <= 0
ABresult
0X0
100
111
800 965 $out = '0.' . ( '0' x ( -$point ) ) . $digits;
801 } elsif ( $k == 1 ) {
802 1255 my $e = $point - 1;
803 1255 ▶ $out = $digits . 'e' . ( $e >= 0 ? '+' : '-' ) . abs($e);
Branch: 1 branch
BranchTrueFalseTotal
$e >= 0 ? : 658 597 1255
804 } else {
805 42 my $e = $point - 1;
806 42 ▶ $out = substr( $digits, 0, 1 ) . '.' . substr( $digits, 1 )
Branch: 1 branch
BranchTrueFalseTotal
$e >= 0 ? : 31 11 42
807 . 'e' . ( $e >= 0 ? '+' : '-' ) . abs($e);
808 }
809  
810 255007 ▶ return $neg ? '-' . $out : $out;
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 58987 196020 255007
811 }
812  
813 #### js_math_floor -- Math.floor(x)
814  
815 # Not a src/lib.js function: the filters' Math.floor (random, slice), over an
816 # already-ToNumber'd value as the other number seams here take it. C's floor is
817 # IEEE's: NaN and +-Infinity pass through, -0 stays -0.
818 617 ▶sub js_math_floor {
Subroutine js_math_floor: called CC=1 SCAR=0.0
Pod undocumented
819 617 my ( $self, $n ) = @_;
820 617 return POSIX::floor($n);
821 }
822  
823 #### js_math_ceil -- Math.ceil(x)
824  
825 # The round filter's 'ceil' method, over an already-ToNumber'd value like
826 # js_math_floor: C's ceil is IEEE's, -0.5 gives -0.
827 109 ▶sub js_math_ceil {
Subroutine js_math_ceil: called CC=1 SCAR=0.0
Pod undocumented
828 109 my ( $self, $n ) = @_;
829 109 return POSIX::ceil($n);
830 }
831  
832 #### js_math_round -- Math.round(x)
833  
834 # The round filter's default method, over an already-ToNumber'd value. The
835 # integral Number closest to x, a tie going towards +Infinity: 2.5 -> 3, -2.5 ->
836 # -2, and -0 for x in [-0.5, -0] (oracle: -0.5|round(0) is -0 -- 1/x is
837 # -Infinity). V8's Float64Round, step for step: ceil(x), one less unless ceil(x)
838 # - 0.5 <= x. It never computes x + 0.5, which rounds 0.49999999999999994 up to
839 # 1 and an odd integer above 2^52 to the next even one; NaN and +-Infinity pass
840 # through.
841 485 ▶sub js_math_round {
Subroutine js_math_round: called CC=2 SCAR=6.9
Pod undocumented
842 485 my ( $self, $n ) = @_;
843 485 my $c = POSIX::ceil($n);
844 485 ▶ return ( $c - 0.5 <= $n ) ? $c : $c - 1;
Branch: 1 branch
BranchTrueFalseTotal
$c - 0.5 <= $n ? : 306 179 485
845 }
846  
847 #### js_math_abs -- Math.abs(x)
848  
849 # The abs filter (exports.abs = Math.abs), over an already-ToNumber'd value: C's
850 # fabs, so -0 is +0 and NaN stays NaN.
851 128 ▶sub js_math_abs {
Subroutine js_math_abs: called CC=1 SCAR=0.0
Pod undocumented
852 128 my ( $self, $n ) = @_;
853 128 return POSIX::fabs($n);
854 }
855  
856 #### js_math_pow -- Math.pow(base, exponent)
857  
858 # The round filter's Math.pow(10, precision) and the template ** operator
859 # (compiler.js emits Math.pow), over already-ToNumber'd values. Number::
860 # exponentiate is IEEE pow with two exceptions C's pow does not share: a NaN
861 # exponent gives NaN even for base 1, and base +-1 with an infinite exponent
862 # gives NaN, not 1 (oracle: 1 ** (1/0) -> NaN).
863 746 ▶sub js_math_pow {
Subroutine js_math_pow: called CC=6 SCAR=17.9
Pod undocumented
864 746 my ( $self, $base, $exponent ) = @_;
865 746 ▶ return $NUM_NAN if $exponent != $exponent;
Branch: 1 branch
BranchTrueFalseTotal
if $exponent != $exponent 23 723 746
866 723 ▶ return $NUM_NAN
Branch: 1 branch
BranchTrueFalseTotal
if $exponent == $NUM_POS_INF || $exponent == $NUM_NEG_INF and $base == 1 || $base == -1 7 716 723
Condition100%9/9
$exponent == $NUM_POS_INF || $exponent == $NUM_NEG_INF and $base == 1 || $base == -1
!ll&&!rl&&r
701157
$exponent == $NUM_POS_INF or $exponent == $NUM_NEG_INF
l!l&&r!l&&!r
139701
$base == 1 or $base == -1
l!l&&r!l&&!r
4315
MC/DC100%4/4
$exponent == $NUM_POS_INF || $exponent == $NUM_NEG_INF and $base == 1 || $base == -1
$exponent == $NUM_POS_INF $exponent == $NUM_NEG_INF $base == 1 $base == -1
Truth table100%7/7
A or B and C or D
A= $exponent == $NUM_POS_INFB= $exponent == $NUM_NEG_INFC= $base == 1D= $base == -1
ABCDresult
00XX0
1X000
01000
1X1X1
1X011
011X1
01011
867 if ( $exponent == $NUM_POS_INF || $exponent == $NUM_NEG_INF ) && ( $base == 1 || $base == -1 );
868 716 return POSIX::pow( $base, $exponent );
869 }
870  
871 #### js_parse_int -- parseInt(string, radix)
872  
873 # Not a src/lib.js function: the global parseInt the int filter calls, over an
874 # already-ToString'd string and an already-ToNumber'd radix (undef for JS
875 # undefined), as the other number seams here take their arguments. ECMAScript
876 # parseInt step by step: leading StrWhiteSpaceChar trimmed (js_whitespace_class),
877 # one sign, the radix through ToInt32 -- 0 means 10, or 16 after a 0x / 0X
878 # prefix, which radix 16 strips too; outside 2..36 is NaN -- then the longest
879 # prefix of radix digits, NaN when there is none, and a zero keeps its sign
880 # (oracle: '-0'|int is -0). The digits' value is computed as V8 computes it,
881 # which the spec leaves to the implementation beyond 2^53 (oracle-fuzzed):
882 #
883 # * radix 10: correctly rounded, as V8's Strtod -- Perl's numification of the
884 # digit string is (an exact integer below 2^64, else C's strtod);
885 # * radix 2, 4, 8, 16, 32: correctly rounded, round-half-even on the bits, the
886 # integer arithmetic of V8's InternalStringToIntDouble;
887 # * any other radix: V8's HandleGenericCase -- 32-bit chunks folded in by a
888 # double multiply and a double add, two roundings per chunk.
889 1986 ▶sub js_parse_int {
Subroutine js_parse_int: called CC=14 SCAR=26.4
Pod undocumented
890 1986 my ( $self, $input_string, $radix ) = @_;
891 1986 my $ws = $self->js_whitespace_class;
892 1986 ( my $s = $input_string ) =~ s/\A(?:$ws)+//; # TrimString(inputString, start)
893 1986 my $sign = 1;
894 1986 ▶ $sign = -1 if substr( $s, 0, 1 ) eq '-';
Branch: 1 branch
BranchTrueFalseTotal
if substr($s, 0, 1) eq "-" 220 1766 1986
895 1986 ▶ $s = substr( $s, 1 ) if $s =~ /\A[+-]/;
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /\A[+-]/ 259 1727 1986
896 1986 my $r = $self->_js_to_int32($radix);
897 1986 my $strip_prefix = 1;
898 1986 ▶ if ( $r != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r != 0) { } 1629 357 1986
899 1629 ▶ return $NUM_NAN if $r < 2 || $r > 36;
Branch: 1 branch
BranchTrueFalseTotal
if $r < 2 or $r > 36 218 1411 1629
Condition100%3/3
$r < 2 or $r > 36
l!l&&r!l&&!r
186321411
MC/DC100%2/2
$r < 2 or $r > 36
$r < 2 $r > 36
Truth table100%3/3
A or B
A= $r < 2B= $r > 36
ABresult
1X1
011
000
900 1411 ▶ $strip_prefix = 0 if $r != 16;
Branch: 1 branch
BranchTrueFalseTotal
if $r != 16 774 637 1411
901 } else {
902 357 $r = 10;
903 }
904 1768 ▶ if ( $strip_prefix && $s =~ /\A0[xX]/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($strip_prefix and $s =~ /\A0[xX]/) 141 1627 1768
Condition100%3/3
$strip_prefix and $s =~ /\A0[xX]/
!ll&&!rl&&r
774853141
MC/DC100%2/2
$strip_prefix and $s =~ /\A0[xX]/
$strip_prefix $s =~ /\A0[xX]/
Truth table100%3/3
A and B
A= $strip_prefixB= $s =~ /\A0[xX]/
ABresult
0X0
100
111
905 141 $s = substr( $s, 2 );
906 141 $r = 16;
907 }
908 # the radix-R digits: 0-9 then a-z / A-Z, ASCII only
909 1768 ▶ my $class = $r <= 10
Branch: 1 branch
BranchTrueFalseTotal
$r <= 10 ? : 1027 741 1768
910 ? '0-' . ( $r - 1 )
911 : '0-9a-' . chr( ord('a') + $r - 11 ) . 'A-' . chr( ord('A') + $r - 11 );
912 1768 my ($z) = $s =~ /\A([$class]*)/;
913 1768 ▶ return $NUM_NAN if $z eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $z eq "" 590 1178 1768
914 1178 my $math_int = $self->_js_parse_int_value( $z, $r );
915 1178 ▶ return $sign < 0 ? $NUM_NEG_ZERO : 0 if $math_int == 0;
Branch: 2 branches
BranchTrueFalseTotal
if $math_int == 0 155 1023 1178
$sign < 0 ? : 44 111 155
916 1023 ▶ return $sign < 0 ? -$math_int : $math_int;
Branch: 1 branch
BranchTrueFalseTotal
$sign < 0 ? : 96 927 1023
917 }
918  
919 # The value of a non-empty string of radix-$r digits, as V8 computes it.
920 1178 ▶sub _js_parse_int_value {
Subroutine _js_parse_int_value: called CC=5 SCAR=16.1
921 1178 my ( $self, $z, $r ) = @_;
922 1178 $z =~ s/\A0+//; # V8 skips leading zeros before it counts digits
923 1178 ▶ return 0 if $z eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $z eq "" 155 1023 1178
924 1023 ▶ if ( $r == 10 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r == 10) 449 574 1023
925 # V8 keeps the first 310 significant digits; more than 309 is past the
926 # largest double either way
927 449 return unpack( 'd', pack( 'd', 0 + substr( $z, 0, 310 ) ) );
928 }
929 574 ▶ my @digits = CORE::map { /[0-9]/ ? ord($_) - ord('0') : ( ord( lc $_ ) - ord('a') + 10 ) } split //, $z;
Branch: 1 branch
BranchTrueFalseTotal
/[0-9]/ ? : 1756 397 2153
930 574 ▶ return $self->_js_parse_int_power_of_two( \@digits, $r ) if ( $r & ( $r - 1 ) ) == 0;
Branch: 1 branch
BranchTrueFalseTotal
if ($r & $r - 1) == 0 533 41 574
931 41 return $self->_js_parse_int_generic( \@digits, $r );
932 }
933  
934 # V8's InternalStringToIntDouble<radix_log_2>: accumulate the digits in an
935 # integer until it passes 53 bits, then round half to even on the bits dropped,
936 # a non-zero tail breaking a tie upwards, and scale by the bits left over.
937 533 ▶sub _js_parse_int_power_of_two {
Subroutine _js_parse_int_power_of_two: called CC=16 SCAR=27.7
938 533 my ( $self, $digits, $radix ) = @_;
939 533 my $radix_log_2 = 0;
940 533 ▶ $radix_log_2++ while ( 1 << $radix_log_2 ) < $radix;
Branch: 1 branch
BranchTrueFalseTotal
1 << $radix_log_2 < $radix and do { ++$radix_log_2 } 1950 533 2483
941 # an exact integer, below 2^58. Perl IVs of 64 bits hold it; a perl with a
942 # 4-byte IV (ADR 0019) computes it in Math::BigInt, the bit operations alike.
943 533 my $big = $Config::Config{ivsize} < 8;
944 533 ▶ my $one = $big ? Math::BigInt->new(1) : 1;
Branch: 1 branch
BranchTrueFalseTotal
$big ? : 0 533 533
945 533 ▶ my $number = $big ? Math::BigInt->new(0) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$big ? : 0 533 533
946 533 my $exponent = 0;
947 533 ▶ for ( my $i = 0; $i < @$digits; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$digits) 1780 497 2277
948 1780 $number = $number * $radix + $digits->[$i];
949 1780 my $overflow = $number >> 53;
950 1780 ▶ if ( $overflow != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($overflow != 0) 36 1744 1780
951 # Overflow occurred. Need to determine which direction to round the result.
952 36 my $overflow_bits_count = 1;
953 36 ▶ while ( $overflow > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($overflow > 1) 59 36 95
954 59 $overflow_bits_count++;
955 59 $overflow >>= 1;
956 }
957  
958 36 my $dropped_bits_mask = ( $one << $overflow_bits_count ) - 1;
959 36 my $dropped_bits = $number & $dropped_bits_mask;
960 36 $number >>= $overflow_bits_count;
961 36 $exponent = $overflow_bits_count;
962  
963 36 my $zero_tail = 1;
964 36 ▶ for ( $i++; $i < @$digits; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$digits) 176 36 212
965 176 ▶ $zero_tail = 0 if $digits->[$i] != 0;
Branch: 1 branch
BranchTrueFalseTotal
if $digits->[$i] != 0 139 37 176
966 176 $exponent += $radix_log_2;
967 }
968  
969 36 my $middle_value = $one << ( $overflow_bits_count - 1 );
970 36 ▶ if ( $dropped_bits > $middle_value ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($dropped_bits > $middle_value) { } 3 33 36
elsif ($dropped_bits == $middle_value) { } 11 22 33
971 3 $number++; # Rounding up.
972 } elsif ( $dropped_bits == $middle_value ) {
973 # Rounding to even to consistency with decimals: half-way case rounds
974 # up if significant part is odd and down otherwise.
975 11 ▶ $number++ if ( $number & 1 ) != 0 || !$zero_tail;
Branch: 1 branch
BranchTrueFalseTotal
if ($number & 1) != 0 or not $zero_tail 8 3 11
Condition100%3/3
($number & 1) != 0 or not $zero_tail
l!l&&r!l&&!r
533
MC/DC100%2/2
($number & 1) != 0 or not $zero_tail
($number & 1) != 0 not $zero_tail
Truth table100%3/3
A or not(B)
A= ($number & 1) != 0B= not $zero_tail
ABresult
1X1
011
000
976 }
977  
978 # Rounding up may cause overflow.
979 36 ▶ if ( ( $number & ( $one << 53 ) ) != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (($number & $one << 53) != 0) 7 29 36
980 7 $exponent++;
981 7 $number >>= 1;
982 }
983 36 last;
984 }
985 }
986 533 ▶ $number = $number->numify if $big;
Branch: 1 branch
BranchTrueFalseTotal
if $big 0 533 533
987 533 ▶ return unpack( 'd', pack( 'd', $number ) ) if $exponent == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $exponent == 0 497 36 533
988 36 return POSIX::ldexp( $number, $exponent );
989 }
990  
991 # V8's HandleGenericCase: the digits in chunks whose multiplier stays below
992 # 0xFFFFFFFF / 36, each folded in as result * multiplier + part in double
993 # arithmetic -- every step through pack('d'), since Perl would otherwise keep an
994 # exact integer product where the double rounds.
995 41 ▶sub _js_parse_int_generic {
Subroutine _js_parse_int_generic: called CC=4 SCAR=13.9
996 41 my ( $self, $digits, $radix ) = @_;
997 41 my $maximum_multiplier = int( 0xFFFFFFFF / 36 );
998 41 my $result = 0;
999 41 my $i = 0;
1000 41 my $done = 0;
1001 41 ▶ while ( !$done ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($done) 57 41 98
1002 57 my ( $part, $multiplier ) = ( 0, 1 );
1003 57 while (1) {
1004 254 ▶ if ( $i >= @$digits ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i >= @$digits) 41 213 254
1005 41 $done = 1;
1006 41 last;
1007 }
1008 213 my $m = $multiplier * $radix;
1009 213 ▶ last if $m > $maximum_multiplier;
Branch: 1 branch
BranchTrueFalseTotal
if $m > $maximum_multiplier 16 197 213
1010 197 $part = $part * $radix + $digits->[$i];
1011 197 $multiplier = $m;
1012 197 $i++;
1013 }
1014 57 $result = unpack( 'd', pack( 'd', $result * $multiplier ) );
1015 57 $result = unpack( 'd', pack( 'd', $result + $part ) );
1016 }
1017 41 return $result;
1018 }
1019  
1020 #### js_parse_float -- parseFloat(string)
1021  
1022 # Not a src/lib.js function: the global parseFloat the float filter calls, over
1023 # an already-ToString'd string. Leading StrWhiteSpaceChar trimmed, then the
1024 # longest prefix that is a StrDecimalLiteral -- an optional sign, then Infinity
1025 # or digits with an optional fraction and exponent, no 0x, no numeric separator
1026 # -- else NaN (oracle: '3.7abc' -> 3.7, '.5' -> 0.5, '1e' -> 1, 'Infinityx' ->
1027 # Infinity, 'infinity' -> NaN, '-0' -> -0). The value is the correctly rounded
1028 # double, as V8's StringToDouble gives it; Perl numifies a decimal string through
1029 # C's strtod, which rounds correctly too.
1030 393 ▶sub js_parse_float {
Subroutine js_parse_float: called CC=5 SCAR=16.1
Pod undocumented
1031 393 my ( $self, $input_string ) = @_;
1032 393 my $ws = $self->js_whitespace_class;
1033 393 ( my $s = $input_string ) =~ s/\A(?:$ws)+//; # TrimString(inputString, start)
1034 393 ▶ my ( $sign, $unsigned ) =
Branch: 1 branch
BranchTrueFalseTotal
() = $s =~ /\A([+-]?)(Infinity|(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)/ or return $NUM_NAN 277 116 393
1035 $s =~ /\A([+-]?)(Infinity|(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)/
1036 or return $NUM_NAN;
1037 277 ▶ my $n = $unsigned eq 'Infinity' ? $NUM_POS_INF : unpack( 'd', pack( 'd', 0 + $unsigned ) );
Branch: 1 branch
BranchTrueFalseTotal
$unsigned eq 'Infinity' ? : 24 253 277
1038 277 ▶ return $n if $sign ne '-';
Branch: 1 branch
BranchTrueFalseTotal
if $sign ne "-" 237 40 277
1039 40 ▶ return $n == 0 ? $NUM_NEG_ZERO : -$n;
Branch: 1 branch
BranchTrueFalseTotal
$n == 0 ? : 9 31 40
1040 }
1041  
1042 #### JS strings reckon in UTF-16 code units (ADR 0012)
1043  
1044 # Not src/lib.js functions: ADR 0012 designates Lib the single home for the
1045 # string operations JS defines over UTF-16 code units. Strings stay ordinary
1046 # Perl character strings; the code-unit view is computed per call:
1047 #
1048 # * the "unit form" of a string spells every astral character (U+10000 ..
1049 # U+10FFFF) as its two surrogate characters, so each Perl character of the
1050 # unit form IS one UTF-16 code unit, and Perl's own length / substr / index /
1051 # rindex / cmp run in code units on it;
1052 # * a result goes back through _js_from_units, which re-pairs every valid
1053 # high + low surrogate pair into its astral character. A surrogate left
1054 # without its partner -- a slice, split or index through a pair -- stays a
1055 # lone surrogate character, 1:1 with JS (ADR 0012 accepts them).
1056 #
1057 # The invariant: no string the engine builds holds a valid pair (a high
1058 # surrogate U+D800..DBFF directly followed by a low one U+DC00..DFFF) as two
1059 # surrogate characters -- a pair is always the one astral character. Seam
1060 # results keep it through _js_from_units; joins keep it through
1061 # js_string_append, the one way two strings are glued together (template `~`
1062 # and string `+`, String concat / replace, Array join and toString, the output
1063 # buffer, asyncAll's output, repeat). Because every string satisfies it, the
1064 # two code-unit sequences JS compares are equal exactly when the Perl strings
1065 # are, so Perl's eq and hash keys stand in for JS ==, ===, object keys and `in`
1066 # over an array or object with no further mapping. A caller string that spells
1067 # a pair as two surrogate characters is outside the invariant: the seams below
1068 # give both spellings the same unit form, but eq and hash keys tell them apart.
1069 #
1070 # Index and length arguments follow one contract, because ToNumber lives in
1071 # Runtime (ADR 0007) and these seams do not call into Runtime: an argument is a JS
1072 # number (already through ToNumber) or undef for JS `undefined`, and undef means
1073 # whatever `undefined` means for that parameter of that method. Search strings
1074 # and separators arrive already through ToString.
1075  
1076 23 my $JS_ASTRAL = qr/[\x{10000}-\x{10FFFF}]/;
1077  
1078 # The last astral string converted and its unit form. Spelling the pairs out
1079 # costs a Perl-level substitution per astral character, the eq that finds the
1080 # string again a C-level compare, so a template that indexes one string in a
1081 # loop ({{ s[i] }}) converts it once instead of once per index.
1082 23 my ( $JS_UNITS_OF, $JS_UNITS );
1083  
1084 80575 ▶sub _js_to_units {
Subroutine _js_to_units: called CC=4 SCAR=13.9
1085 80575 my ( $self, $s ) = @_;
1086 80575 ▶ return $s unless $s =~ $JS_ASTRAL;
Branch: 1 branch
BranchTrueFalseTotal
unless $s =~ /$JS_ASTRAL/ 76807 3768 80575
1087 3768 ▶ return $JS_UNITS if defined($JS_UNITS_OF) && $JS_UNITS_OF eq $s;
Branch: 1 branch
BranchTrueFalseTotal
if defined $JS_UNITS_OF and $JS_UNITS_OF eq $s 1686 2082 3768
Condition100%3/3
defined $JS_UNITS_OF and $JS_UNITS_OF eq $s
!ll&&!rl&&r
320791686
MC/DC100%2/2
defined $JS_UNITS_OF and $JS_UNITS_OF eq $s
defined $JS_UNITS_OF $JS_UNITS_OF eq $s
Truth table100%3/3
A and B
A= defined $JS_UNITS_OFB= $JS_UNITS_OF eq $s
ABresult
0X0
100
111
1088 2082 $JS_UNITS_OF = "$s";
1089 2082 return $JS_UNITS = $s =~ s/($JS_ASTRAL)/$self->_js_surrogate_pair( ord $1 )/ger;
1090 }
1091  
1092 2133 ▶sub _js_surrogate_pair {
Subroutine _js_surrogate_pair: called CC=1 SCAR=0.0
1093 2133 my ( $self, $cp ) = @_;
1094 2133 $cp -= 0x10000;
1095 2133 return chr( 0xD800 + ( $cp >> 10 ) ) . chr( 0xDC00 + ( $cp & 0x3FF ) );
1096 }
1097  
1098 7181 ▶sub _js_from_units {
Subroutine _js_from_units: called CC=2 SCAR=6.9
1099 7181 my ( $self, $u ) = @_;
1100 7181 ▶ return $u unless $u =~ /[\x{D800}-\x{DBFF}]/;
Branch: 1 branch
BranchTrueFalseTotal
unless $u =~ /[\x{D800}-\x{DBFF}]/ 7002 179 7181
1101 179 return $u =~ s/([\x{D800}-\x{DBFF}])([\x{DC00}-\x{DFFF}])/
1102 132 chr( 0x10000 + ( ( ord($1) - 0xD800 ) << 10 ) + ( ord($2) - 0xDC00 ) )/ger;
1103 }
1104  
1105 # ECMAScript ToIntegerOrInfinity over an already-ToNumber'd value: NaN (and
1106 # undef, JS undefined -> NaN) is 0, +-Infinity stays, the rest truncates to zero.
1107 8918 ▶sub _js_to_integer_or_infinity {
Subroutine _js_to_integer_or_infinity: called CC=5 SCAR=16.1
1108 8918 my ( $self, $n ) = @_;
1109 8918 ▶ return 0 if !defined($n) || $n != $n;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $n or $n != $n 277 8641 8918
Condition100%3/3
not defined $n or $n != $n
l!l&&r!l&&!r
1731048641
MC/DC100%2/2
not defined $n or $n != $n
not defined $n $n != $n
Truth table100%3/3
not(A) or B
A= not defined $nB= $n != $n
ABresult
1X1
011
000
1110 8641 ▶ return $n if $n == $NUM_POS_INF || $n == $NUM_NEG_INF;
Branch: 1 branch
BranchTrueFalseTotal
if $n == $NUM_POS_INF or $n == $NUM_NEG_INF 75 8566 8641
Condition100%3/3
$n == $NUM_POS_INF or $n == $NUM_NEG_INF
l!l&&r!l&&!r
53228566
MC/DC100%2/2
$n == $NUM_POS_INF or $n == $NUM_NEG_INF
$n == $NUM_POS_INF $n == $NUM_NEG_INF
Truth table100%3/3
A or B
A= $n == $NUM_POS_INFB= $n == $NUM_NEG_INF
ABresult
1X1
011
000
1111 8566 return int($n);
1112 }
1113  
1114 # ECMAScript ToUint32 over an already-ToNumber'd value (String.prototype.split's
1115 # limit): NaN and +-Infinity are 0, else truncate and wrap modulo 2^32.
1116 2021 ▶sub _js_to_uint32 {
Subroutine _js_to_uint32: called CC=5 SCAR=16.1
1117 2021 my ( $self, $n ) = @_;
1118 2021 ▶ return 0 if $n != $n || $n == $NUM_POS_INF || $n == $NUM_NEG_INF;
Branch: 1 branch
BranchTrueFalseTotal
if $n != $n or $n == $NUM_POS_INF or $n == $NUM_NEG_INF 132 1889 2021
Condition100%6/6
$n != $n or $n == $NUM_POS_INF or $n == $NUM_NEG_INF
l!l&&r!l&&!r
108241889
$n != $n or $n == $NUM_POS_INF
l!l&&r!l&&!r
82261913
MC/DC100%3/3
$n != $n or $n == $NUM_POS_INF or $n == $NUM_NEG_INF
$n != $n $n == $NUM_POS_INF $n == $NUM_NEG_INF
Truth table100%4/4
A or B or C
A= $n != $nB= $n == $NUM_POS_INFC= $n == $NUM_NEG_INF
ABCresult
1XX1
01X1
0011
0000
1119 1889 my $m = POSIX::fmod( int($n), 4294967296 );
1120 1889 ▶ return $m < 0 ? $m + 4294967296 : $m;
Branch: 1 branch
BranchTrueFalseTotal
$m < 0 ? : 87 1802 1889
1121 }
1122  
1123 # ECMAScript ToInt32 over an already-ToNumber'd value (parseInt's radix), undef
1124 # being JS undefined: ToUint32, then the upper half of the range wraps negative.
1125 1993 ▶sub _js_to_int32 {
Subroutine _js_to_int32: called CC=3 SCAR=11.0
1126 1993 my ( $self, $n ) = @_;
1127 1993 ▶ return 0 unless defined $n;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n 20 1973 1993
1128 1973 my $m = $self->_js_to_uint32($n);
1129 1973 ▶ return $m >= 2147483648 ? $m - 4294967296 : $m;
Branch: 1 branch
BranchTrueFalseTotal
$m >= 2147483648 ? : 108 1865 1973
1130 }
1131  
1132 # Clamp an integer-or-infinity to [0, $len].
1133 8347 ▶sub _js_clamp {
Subroutine _js_clamp: called CC=3 SCAR=11.0
1134 8347 my ( $self, $n, $len ) = @_;
1135 8347 ▶ return $n < 0 ? 0 : $n > $len ? $len : $n;
Branch: 2 branches
BranchTrueFalseTotal
$n < 0 ? : 85 8262 8347
$n > $len ? : 1448 6814 8262
1136 }
1137  
1138 # The code units [$from, $to) of a unit form, back as a Perl string.
1139 4654 ▶sub _js_unit_range {
Subroutine _js_unit_range: called CC=2 SCAR=6.9
1140 4654 my ( $self, $u, $from, $to ) = @_;
1141 4654 ▶ return '' if $from >= $to;
Branch: 1 branch
BranchTrueFalseTotal
if $from >= $to 425 4229 4654
1142 4229 return $self->_js_from_units( substr( $u, $from, $to - $from ) );
1143 }
1144  
1145 #### js_string_append -- JS string concatenation, in place
1146  
1147 # Appends $str to the caller's string variable -- $_[1] is aliased, so the
1148 # buffer is extended in place and never copied -- and returns nothing. JS joins
1149 # code units, so a lone high surrogate at the end of the buffer and a lone low
1150 # one at the start of $str form a valid pair in JS's result; here they become
1151 # the one astral character, which keeps the invariant above. Only that boundary
1152 # is looked at: each side already holds the invariant, so no other pair can
1153 # form, and the check is O(1) whatever the buffer's length -- a test of $str's
1154 # first character, then a chop of the buffer's last one (put back unless it is
1155 # a high surrogate). Not a /[\x{D800}-\x{DBFF}]\z/ match: a successful match
1156 # shares the buffer copy-on-write, so the chop after it would copy the whole
1157 # buffer, and an output of many re-paired halves would turn O(n^2).
1158 286906 ▶sub js_string_append {
Subroutine js_string_append: called CC=5 SCAR=16.1
Pod undocumented
1159 286906 my ( $self, undef, $str ) = @_;
1160 286906 my $lo = ord $str; # ord '' is 0
1161 286906 ▶ if ( $lo >= 0xDC00 && $lo <= 0xDFFF ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lo >= 56320 and $lo <= 57343) 96 286810 286906
Condition100%3/3
$lo >= 56320 and $lo <= 57343
!ll&&!rl&&r
28630051096
MC/DC100%2/2
$lo >= 56320 and $lo <= 57343
$lo >= 56320 $lo <= 57343
Truth table100%3/3
A and B
A= $lo >= 56320B= $lo <= 57343
ABresult
0X0
100
111
1162 96 my $last = chop $_[1]; # '' on an empty buffer
1163 96 my $hi = ord $last;
1164 96 ▶ if ( $hi >= 0xD800 && $hi <= 0xDBFF ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hi >= 55296 and $hi <= 56319) 60 36 96
Condition100%3/3
$hi >= 55296 and $hi <= 56319
!ll&&!rl&&r
35160
MC/DC100%2/2
$hi >= 55296 and $hi <= 56319
$hi >= 55296 $hi <= 56319
Truth table100%3/3
A and B
A= $hi >= 55296B= $hi <= 56319
ABresult
0X0
100
111
1165 60 $_[1] .= chr( 0x10000 + ( ( $hi - 0xD800 ) << 10 ) + ( $lo - 0xDC00 ) ) . substr( $str, 1 );
1166 60 return;
1167 }
1168 36 $_[1] .= $last;
1169 }
1170 286846 $_[1] .= $str;
1171 286846 return;
1172 }
1173  
1174 #### js_string_length -- String length
1175  
1176 112877 ▶sub js_string_length {
Subroutine js_string_length: called CC=2 SCAR=6.9
Pod undocumented
1177 112877 my ( $self, $s ) = @_;
1178 # one code unit per character, plus the second unit of each astral one; the
1179 # match first, because tr over a wide range costs ~20 ns per character even
1180 # on a string with no astral character in it
1181 112877 ▶ return CORE::length($s) unless $s =~ $JS_ASTRAL;
Branch: 1 branch
BranchTrueFalseTotal
unless $s =~ /$JS_ASTRAL/ 112586 291 112877
1182 291 return CORE::length($s) + ( $s =~ tr/\x{10000}-\x{10FFFF}// );
1183 }
1184  
1185 #### js_char_at -- String.prototype.charAt(pos)
1186  
1187 377 ▶sub js_char_at {
Subroutine js_char_at: called CC=3 SCAR=11.0
Pod undocumented
1188 377 my ( $self, $s, $pos ) = @_;
1189 377 my $u = $self->_js_to_units($s);
1190 377 my $p = $self->_js_to_integer_or_infinity($pos);
1191 377 ▶ return '' if $p < 0 || $p >= CORE::length($u);
Branch: 1 branch
BranchTrueFalseTotal
if $p < 0 or $p >= length $u 34 343 377
Condition100%3/3
$p < 0 or $p >= length $u
l!l&&r!l&&!r
133343
MC/DC100%2/2
$p < 0 or $p >= length $u
$p < 0 $p >= length $u
Truth table100%3/3
A or B
A= $p < 0B= $p >= length $u
ABresult
1X1
011
000
1192 343 return substr( $u, $p, 1 ); # one unit: an ordinary character or a lone surrogate
1193 }
1194  
1195 #### js_string_slice -- String.prototype.slice(start, end)
1196  
1197 237 ▶sub js_string_slice {
Subroutine js_string_slice: called CC=4 SCAR=13.9
Pod undocumented
1198 237 my ( $self, $s, $start, $end ) = @_;
1199 237 my $u = $self->_js_to_units($s);
1200 237 my $len = CORE::length($u);
1201 237 my $from = $self->_js_to_integer_or_infinity($start);
1202 237 ▶ my $to = defined($end) ? $self->_js_to_integer_or_infinity($end) : $len;
Branch: 1 branch
BranchTrueFalseTotal
defined $end ? : 105 132 237
1203 237 ▶ $from = $from < 0 ? $len + $from : $from; # negative counts from the end
Branch: 1 branch
BranchTrueFalseTotal
$from < 0 ? : 7 230 237
1204 237 ▶ $to = $to < 0 ? $len + $to : $to;
Branch: 1 branch
BranchTrueFalseTotal
$to < 0 ? : 3 234 237
1205 237 return $self->_js_unit_range( $u, $self->_js_clamp( $from, $len ), $self->_js_clamp( $to, $len ) );
1206 }
1207  
1208 #### js_substring -- String.prototype.substring(start, end)
1209  
1210 338 ▶sub js_substring {
Subroutine js_substring: called CC=3 SCAR=11.0
Pod undocumented
1211 338 my ( $self, $s, $start, $end ) = @_;
1212 338 my $u = $self->_js_to_units($s);
1213 338 my $len = CORE::length($u);
1214 338 my $from = $self->_js_clamp( $self->_js_to_integer_or_infinity($start), $len );
1215 338 ▶ my $to = defined($end) ? $self->_js_clamp( $self->_js_to_integer_or_infinity($end), $len ) : $len;
Branch: 1 branch
BranchTrueFalseTotal
defined $end ? : 252 86 338
1216 338 ▶ ( $from, $to ) = ( $to, $from ) if $from > $to; # substring swaps, slice does not
Branch: 1 branch
BranchTrueFalseTotal
if $from > $to 2 336 338
1217 338 return $self->_js_unit_range( $u, $from, $to );
1218 }
1219  
1220 #### js_substr -- String.prototype.substr(start, length) (ECMAScript Annex B)
1221  
1222 3893 ▶sub js_substr {
Subroutine js_substr: called CC=4 SCAR=13.9
Pod undocumented
1223 3893 my ( $self, $s, $start, $length ) = @_;
1224 3893 my $u = $self->_js_to_units($s);
1225 3893 my $size = CORE::length($u);
1226 3893 my $from = $self->_js_to_integer_or_infinity($start);
1227 3893 ▶ $from = $from < 0 ? $size + $from : $from;
Branch: 1 branch
BranchTrueFalseTotal
$from < 0 ? : 4 3889 3893
1228 3893 $from = $self->_js_clamp( $from, $size );
1229 # length undefined -> to the end; a negative or NaN length takes nothing
1230 # (JS 'abc'.substr(0, -1) is '', where Perl's substr would drop the last char)
1231 3893 ▶ my $n = defined($length) ? $self->_js_clamp( $self->_js_to_integer_or_infinity($length), $size ) : $size;
Branch: 1 branch
BranchTrueFalseTotal
defined $length ? : 3046 847 3893
1232 3893 ▶ my $to = $from + $n > $size ? $size : $from + $n;
Branch: 1 branch
BranchTrueFalseTotal
$from + $n > $size ? : 5 3888 3893
1233 3893 return $self->_js_unit_range( $u, $from, $to );
1234 }
1235  
1236 #### js_string_index_of -- String.prototype.indexOf(searchString, position)
1237  
1238 290 ▶sub js_string_index_of {
Subroutine js_string_index_of: called CC=1 SCAR=0.0
Pod undocumented
1239 290 my ( $self, $s, $search, $position ) = @_;
1240 290 my $u = $self->_js_to_units($s);
1241 290 my $p = $self->_js_clamp( $self->_js_to_integer_or_infinity($position), CORE::length($u) );
1242 290 return index( $u, $self->_js_to_units($search), $p );
1243 }
1244  
1245 #### js_string_last_index_of -- String.prototype.lastIndexOf(searchString, position)
1246  
1247 54 ▶sub js_string_last_index_of {
Subroutine js_string_last_index_of: called CC=3 SCAR=11.0
Pod undocumented
1248 54 my ( $self, $s, $search, $position ) = @_;
1249 54 my $u = $self->_js_to_units($s);
1250 # NaN -- and so undefined -- searches from the end, unlike indexOf's 0
1251 54 ▶ my $p = ( !defined($position) || $position != $position )
Branch: 1 branch
BranchTrueFalseTotal
!defined($position) || $position != $position ? : 8 46 54
Condition100%3/3
not defined $position or $position != $position
l!l&&r!l&&!r
5346
MC/DC100%2/2
not defined $position or $position != $position
not defined $position $position != $position
Truth table100%3/3
not(A) or B
A= not defined $positionB= $position != $position
ABresult
1X1
011
000
1252 ? $NUM_POS_INF
1253 : $self->_js_to_integer_or_infinity($position);
1254 54 return rindex( $u, $self->_js_to_units($search), $self->_js_clamp( $p, CORE::length($u) ) );
1255 }
1256  
1257 #### js_split -- String.prototype.split(separator, limit), string separator
1258  
1259 233 ▶sub js_split {
Subroutine js_split: called CC=9 SCAR=22.0
Pod undocumented
1260 233 my ( $self, $s, $separator, $limit ) = @_;
1261 233 ▶ my $lim = defined($limit) ? $self->_js_to_uint32($limit) : 4294967295;
Branch: 1 branch
BranchTrueFalseTotal
defined $limit ? : 11 222 233
1262 233 ▶ return [] if $lim == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $lim == 0 5 228 233
1263 228 ▶ return [$s] unless defined $separator; # split(undefined) -> [S]
Branch: 1 branch
BranchTrueFalseTotal
unless defined $separator 2 226 228
1264  
1265 226 my $u = $self->_js_to_units($s);
1266 # split('') -> the code units themselves, an astral character as two lone
1267 # surrogates; ''.split('') is [] while ''.split(',') is [''] (oracle)
1268 226 ▶ if ( $separator eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($separator eq "") 129 97 226
1269 129 ▶ my $head = $lim < CORE::length($u) ? substr( $u, 0, $lim ) : $u;
Branch: 1 branch
BranchTrueFalseTotal
$lim < length $u ? : 1 128 129
1270 129 return [ split //, $head ];
1271 }
1272 97 ▶ return [$s] if $u eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $u eq "" 11 86 97
1273  
1274 86 my $r = $self->_js_to_units($separator);
1275 86 my $r_len = CORE::length($r);
1276 86 my @parts;
1277 86 my $i = 0;
1278 86 my $j = index( $u, $r, 0 );
1279 86 ▶ while ( $j != -1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j != -1) 104 82 186
1280 104 push @parts, $self->_js_unit_range( $u, $i, $j );
1281 104 ▶ return \@parts if @parts == $lim;
Branch: 1 branch
BranchTrueFalseTotal
if @parts == $lim 4 100 104
1282 100 $i = $j + $r_len;
1283 100 $j = index( $u, $r, $i );
1284 }
1285 82 push @parts, $self->_js_unit_range( $u, $i, CORE::length($u) );
1286 82 return \@parts;
1287 }
1288  
1289 #### js_string_compare -- the code-unit order of the JS relational operators
1290  
1291 # IsLessThan on two strings compares UTF-16 code units, so U+FF01 sorts after
1292 # U+1F600 (high surrogate U+D83D) where code points would put it before. cmp
1293 # over the unit forms is exactly that order. Returns -1, 0 or 1.
1294 37365 ▶sub js_string_compare {
Subroutine js_string_compare: called CC=1 SCAR=0.0
Pod undocumented
1295 37365 my ( $self, $x, $y ) = @_;
1296 37365 return $self->_js_to_units($x) cmp $self->_js_to_units($y);
1297 }
1298  
1299 #### js_to_lower_case / js_to_upper_case -- String.prototype.toLowerCase / toUpperCase
1300  
1301 # Not src/lib.js functions: the one home of JS case mapping, for the lower /
1302 # upper / capitalize / title filters and the String methods a template calls.
1303 # JS maps by code point with the full Unicode default case conversion -- the
1304 # unconditional SpecialCasing mappings included (oracle: 'ß' upper is 'SS', 'İ'
1305 # lower is 'i' + U+0307, two code units) -- which Perl's lc / uc also do, with
1306 # two differences handled here:
1307 #
1308 # * Final_Sigma, the one language-independent conditional mapping: a capital
1309 # sigma lowercases to final 'ς' where it ends a word, else to 'σ'. Perl's lc
1310 # always gives 'σ'. Oracle: 'ΑΣ' -> 'ας', 'ΑΣΑ' -> 'ασα', 'ΑΣ.' -> 'ας.',
1311 # 'Α.Σ' -> 'α.ς', 'ΑΣ1' -> 'ας1', '1Σ' -> '1σ', 'ΑΣ\x{AD}' -> 'ας\x{AD}'.
1312 # The context test is ICU's, which V8 calls: skip case-ignorable characters
1313 # outward from the sigma, and the first other character must be cased
1314 # before it and must not be cased after it. A character that is both cased
1315 # and case-ignorable counts as ignorable (oracle: 'ʰΣ' -> 'ʰσ', U+02B0 is
1316 # both, where the Unicode wording alone would give 'ʰς').
1317 # * Perl maps Latin-1 characters by Unicode rules only under the
1318 # unicode_strings feature (else uc("\xDF") stays "\xDF" on a string without
1319 # the UTF-8 flag); both seams enable it.
1320 #
1321 # A lone surrogate maps to itself, as in JS (Perl would warn). A caller string
1322 # that spells a pair as two surrogate characters is re-paired first, so both
1323 # spellings map alike.
1324 23 my $JS_FINAL_SIGMA = qr/
1325 ( (?!\p{Case_Ignorable})\p{Cased} \p{Case_Ignorable}* ) # the cased letter before
1326 \x{3A3}
1327 (?! \p{Case_Ignorable}* (?!\p{Case_Ignorable})\p{Cased} ) # no cased letter after
1328 /x;
1329  
1330 574 ▶sub js_to_lower_case {
Subroutine js_to_lower_case: called CC=2 SCAR=6.9
Pod undocumented
1331 574 my ( $self, $s ) = @_;
1332 23 ▶ use feature 'unicode_strings';
Subroutine BEGIN: called CC=1 SCAR=0.0
1333 23 ▶ no warnings 'surrogate';
Subroutine BEGIN: called CC=1 SCAR=0.0
1334 574 $s = $self->_js_from_units($s);
1335 574 ▶ $s =~ s/$JS_FINAL_SIGMA/$1\x{3C2}/g if index( $s, "\x{3A3}" ) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($s, "\x{3a3}") != -1 49 525 574
1336 574 return lc $s;
1337 }
1338  
1339 1285 ▶sub js_to_upper_case {
Subroutine js_to_upper_case: called CC=1 SCAR=0.0
Pod undocumented
1340 1285 my ( $self, $s ) = @_;
1341 23 ▶ use feature 'unicode_strings';
Subroutine BEGIN: called CC=1 SCAR=0.0
1342 23 ▶ no warnings 'surrogate';
Subroutine BEGIN: called CC=1 SCAR=0.0
1343 1285 return uc $self->_js_from_units($s);
1344 }
1345  
1346 #### js_get_substitution -- GetSubstitution, the replacement patterns of replace
1347  
1348 # Not a src/lib.js function: ECMAScript GetSubstitution(matched, str, position,
1349 # captures, namedCaptures, replacement), which String.prototype.replace and
1350 # RegExp.prototype[Symbol.replace] apply to a string replacement:
1351 #
1352 # $$ -> '$' $& -> matched $` -> str before the match $' -> str after it
1353 # $n / $nn -> capture n (1..99), '' for a group that did not take part; a
1354 # two-digit index past the last group is read as one digit and a
1355 # literal digit ($10 with one group -> capture 1 then '0'), and an
1356 # index of 0 or past the groups stays literal ($0, $00, $1 with none)
1357 # $<name> -> the named group ('' if absent); literal '$<' when the regex has
1358 # no named groups ($named undef) or no '>' follows; $named is
1359 # the match's groups object, an engine-built Hash::Ordered
1360 #
1361 # Oracle: 'abc'.replace(/(b)/, '[$1$2$0$01$10]') -> 'a[b$2$0bb0]c'; with eleven
1362 # groups '[$11|$10|$1|$12|$011|$00|$100]' -> '[k|j|a|a2|a1|$00|j0]'. $position
1363 # counts code units (ADR 0012); $captures is an arrayref (undef for a group that
1364 # did not participate); every piece is joined through js_string_append.
1365 158 ▶sub js_get_substitution {
Subroutine js_get_substitution: called CC=18 SCAR=28.9
Pod undocumented
1366 158 my ( $self, $matched, $str, $position, $captures, $named, $replacement ) = @_;
1367 158 ▶ return $replacement if index( $replacement, '$' ) < 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($replacement, "\$") == -1 112 46 158
1368  
1369 46 my $m = scalar @$captures;
1370 46 my $result = '';
1371 46 pos($replacement) = 0;
1372 46 ▶ while ( pos($replacement) < CORE::length($replacement) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (pos $replacement < length $replacement) 208 46 254
1373 208 my $ref_replacement;
1374 208 ▶ if ( $replacement =~ /\G([^\$]+)/gc ) {
Branch: 7 branches
BranchTrueFalseTotal
if ($replacement =~ /\G([^\$]+)/cg) { } 109 99 208
elsif ($replacement =~ /\G\$\$/cg) { } 5 94 99
elsif ($replacement =~ /\G\$`/cg) { } 13 81 94
elsif ($replacement =~ /\G\$&/cg) { } 8 73 81
elsif ($replacement =~ /\G\$'/cg) { } 7 66 73
elsif ($replacement =~ /\G\$([0-9])([0-9]?)/cg) { } 42 24 66
elsif ($replacement =~ /\G\$</cg) { } 16 8 24
1375 109 $ref_replacement = $1;
1376 } elsif ( $replacement =~ /\G\$\$/gc ) {
1377 5 $ref_replacement = '$';
1378 } elsif ( $replacement =~ /\G\$`/gc ) {
1379 13 $ref_replacement = $self->js_substring( $str, 0, $position );
1380 } elsif ( $replacement =~ /\G\$&/gc ) {
1381 8 $ref_replacement = $matched;
1382 } elsif ( $replacement =~ /\G\$'/gc ) {
1383 7 my $tail_pos = $position + $self->js_string_length($matched);
1384 7 $ref_replacement = $self->js_substring( $str, $tail_pos ); # substring clamps to the length
1385 } elsif ( $replacement =~ /\G\$([0-9])([0-9]?)/gc ) {
1386 42 my ( $d1, $d2 ) = ( $1, $2 );
1387 42 my $index = $d1 . $d2;
1388 42 ▶ if ( $d2 ne '' && $index > $m ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($d2 ne "" and $index > $m) 6 36 42
Condition100%3/3
$d2 ne "" and $index > $m
!ll&&!rl&&r
22146
MC/DC100%2/2
$d2 ne "" and $index > $m
$d2 ne "" $index > $m
Truth table100%3/3
A and B
A= $d2 ne ""B= $index > $m
ABresult
0X0
100
111
1389 # a two-digit index past the groups: one digit, the second is literal
1390 6 ( $index, $d2 ) = ( $d1, '' );
1391 6 pos($replacement) = pos($replacement) - 1;
1392 }
1393 42 ▶ $ref_replacement = ( $index >= 1 && $index <= $m )
Branch: 2 branches
BranchTrueFalseTotal
$index >= 1 && $index <= $m ? : 32 10 42
defined $$captures[$index - 1] ? : 30 2 32
Condition100%3/3
$index >= 1 and $index <= $m
!ll&&!rl&&r
5532
MC/DC100%2/2
$index >= 1 and $index <= $m
$index >= 1 $index <= $m
Truth table100%3/3
A and B
A= $index >= 1B= $index <= $m
ABresult
0X0
100
111
1394 ? ( defined( $captures->[ $index - 1 ] ) ? $captures->[ $index - 1 ] : '' )
1395 : '$' . $d1 . $d2;
1396 } elsif ( $replacement =~ /\G\$</gc ) {
1397 16 my $gt_pos = index( $replacement, '>', pos($replacement) );
1398 16 ▶ if ( $gt_pos < 0 || !defined($named) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($gt_pos < 0 or not defined $named) { } 4 12 16
Condition100%3/3
$gt_pos < 0 or not defined $named
l!l&&r!l&&!r
1312
MC/DC100%2/2
$gt_pos < 0 or not defined $named
$gt_pos < 0 not defined $named
Truth table100%3/3
A or not(B)
A= $gt_pos < 0B= not defined $named
ABresult
1X1
011
000
1399 4 $ref_replacement = '$<';
1400 } else {
1401 12 my $group_name = substr( $replacement, pos($replacement), $gt_pos - pos($replacement) );
1402 12 pos($replacement) = $gt_pos + 1;
1403 12 my $capture = $named->get($group_name);
1404 12 ▶ $ref_replacement = defined($capture) ? $capture : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $capture ? : 6 6 12
1405 }
1406 } else {
1407 8 $replacement =~ /\G\$/gc;
1408 8 $ref_replacement = '$';
1409 }
1410 208 $self->js_string_append( $result, $ref_replacement );
1411 }
1412 46 return $result;
1413 }
1414  
1415 #### js_encode_uri_component -- encodeURIComponent(uriComponent)
1416  
1417 # Not a src/lib.js function: the global encodeURIComponent the urlencode filter
1418 # calls, over an already-ToString'd string. ECMAScript Encode(string,
1419 # extraUnescaped): A-Z a-z 0-9 and - _ . ! ~ * ' ( ) stay, every other code
1420 # point goes out as the %XX bytes of its UTF-8 form in uppercase hex (oracle:
1421 # 'a b&c' -> a%20b%26c, 'é' -> %C3%A9, '\u{1F600}' -> %F0%9F%98%80). It walks code
1422 # units: a surrogate pair is the one code point, a lone surrogate has no UTF-8
1423 # form and throws URIError: URI malformed (oracle: '\u{1F600}'|first|urlencode). A
1424 # caller string spelling a pair as two surrogate characters is re-paired first,
1425 # so both spellings encode alike (ADR 0012).
1426 318 ▶sub js_encode_uri_component {
Subroutine js_encode_uri_component: called CC=2 SCAR=6.9
Pod undocumented
1427 318 my ( $self, $s ) = @_;
1428 318 my $str = $self->_js_from_units($s);
1429 318 ▶ die Text::Nunjucks::Lib::Error->new( 'URI malformed', name => 'URIError' )
Branch: 1 branch
BranchTrueFalseTotal
if $str =~ /[\x{D800}-\x{DFFF}]/ 12 306 318
1430 if $str =~ /[\x{D800}-\x{DFFF}]/;
1431 306 return $str =~ s{([^A-Za-z0-9\-_.!~*'()])}{$self->_js_utf8_percent_encode($1)}ger;
1432 }
1433  
1434 239 ▶sub _js_utf8_percent_encode {
Subroutine _js_utf8_percent_encode: called CC=1 SCAR=0.0
1435 239 my ( $self, $char ) = @_;
1436 239 utf8::encode($char);
1437 239 return CORE::join( '', CORE::map { sprintf( '%%%02X', ord $_ ) } split //, $char );
1438 }
1439  
1440 #### js_array_sort -- Array.prototype.sort(comparefn), V8's TimSort
1441  
1442 # Not a src/lib.js function: the one home of JS Array.prototype.sort -- the
1443 # Array `sort` member of the ADR 0008 surface and the sort / dictsort filters'
1444 # array.sort(...). Maintainer decision B (k17): a port of V8's implementation,
1445 # pinned to the V8 of the oracle's Node (v24.19.0, V8 13.6.233.17), so that a
1446 # comparator that is no consistent order -- or one that watches its calls --
1447 # gets exactly the calls V8 makes and leaves the array as V8 leaves it. Source:
1448 # third_party/v8/builtins/array-sort.tq at V8 tag 13.6.233.17
1449 # (https://raw.githubusercontent.com/v8/v8/13.6.233.17/third_party/v8/builtins/array-sort.tq),
1450 # CPython's TimSort: natural runs, binary insertion sort up to the minimum run
1451 # length, merge_lo / merge_hi with galloping and the min_gallop adaptation. The
1452 # macros and builtins below are the .tq's, in its order, named in snake_case
1453 # with a _js_sort_ prefix; the comparator call sequence follows from their
1454 # control flow, which is therefore kept as is. The sort state is a hash, the
1455 # .tq's SortState fields in snake_case.
1456 #
1457 # Around the TimSort, the spec steps V8 implements: a comparefn that is neither
1458 # undefined nor callable throws before anything else, even on an empty array
1459 # (oracle: [].sort(5) -> "TypeError: The comparison function must be either a
1460 # function or undefined: 5"); fewer than two elements return untouched; the
1461 # undefined elements are counted out of the work array, never passed to the
1462 # comparator, and written back after the sorted values (oracle: [u, 'z',
1463 # 'a'].sort() -> a,z,undefined). Without a comparefn two elements compare as
1464 # their ToStrings in UTF-16 code-unit order (Runtime's JS ToString, ADR 0012's
1465 # js_string_compare); a comparefn is called with (x, y) and no this (ADR 0009),
1466 # its result goes through JS ToNumber and NaN counts as +0 (oracle: a macro's
1467 # SafeString output ' 2 ' is 2, 'x' is 0); only the sign is used, and -0 is not
1468 # below 0. Whatever the comparefn throws propagates as is. It sorts a copy of
1469 # the elements, and the receiver is written once, at the end: the comparefn
1470 # sees the unsorted array, and an exception leaves it unchanged.
1471 #
1472 # What the .tq does that has no counterpart here, and why:
1473 # * the elements-kind accessors (Load / Store / Delete for Smi, double, object
1474 # and generic elements, CheckAccessor, ResetToGenericAccessor): Perl has one
1475 # array kind, and every accessor writes the same values back -- index by
1476 # index, so a comparefn that grew the array keeps its tail, as in V8;
1477 # * array holes: the Perl value model has none (ADR 0001), so the compaction
1478 # skips nothing and the copy back deletes nothing;
1479 # * SortCompareDefault's Smi fast path (SmiLexicographicCompare): it returns
1480 # what comparing the two decimal strings returns;
1481 # * the Smi clamps of the lengths (kSmiMaxValue), the offset overflow guards
1482 # in the gallops (Smi wrap-around) and the temp array's size policy: Perl
1483 # integers do not wrap at array sizes, and a Perl array grows on demand.
1484  
1485 # When we get into galloping mode, we stay there until both runs win less often
1486 # than kMinGallopWins consecutive times.
1487 23 my $JS_SORT_MIN_GALLOP_WINS = 7;
1488  
1489 # SortState.Compare
1490 500920 ▶sub _js_sort_compare {
Subroutine _js_sort_compare: called CC=2 SCAR=6.9
1491 500920 my ( $self, $sort_state, $x, $y ) = @_;
1492 return defined( $sort_state->{user_cmp_fn} )
1493 500920 ▶ ? $self->_js_sort_compare_user_fn( $sort_state->{user_cmp_fn}, $x, $y )
Branch: 1 branch
BranchTrueFalseTotal
defined $sort_state->{'user_cmp_fn'} ? : 464600 36320 500920
1494 : $self->_js_sort_compare_default( $x, $y );
1495 }
1496  
1497 1432 ▶sub _js_sort_new_sort_state {
Subroutine _js_sort_new_sort_state: called CC=1 SCAR=0.0
1498 1432 my ( $self, $receiver, $comparefn, $initial_receiver_length ) = @_;
1499 return {
1500 1432 receiver => $receiver,
1501 initial_receiver_length => $initial_receiver_length,
1502 user_cmp_fn => $comparefn,
1503 min_gallop => $JS_SORT_MIN_GALLOP_WINS,
1504 pending_runs_size => 0,
1505 pending_runs => [],
1506 work_array => [],
1507 temp_array => [],
1508 sort_length => 0,
1509 number_of_undefined => 0,
1510 };
1511 }
1512  
1513 36320 ▶sub _js_sort_compare_default {
Subroutine _js_sort_compare_default: called CC=1 SCAR=0.0
1514 36320 my ( $self, $x, $y ) = @_;
1515 36320 my $rt = $self->_runtime;
1516  
1517 # 5. Let xString be ? ToString(x).
1518 # 6. Let yString be ? ToString(y).
1519 # 7.-11. xString < yString -> -1, yString < xString -> 1, else +0
1520 36320 return $self->js_string_compare( $rt->_js_to_string($x), $rt->_js_to_string($y) );
1521 }
1522  
1523 464600 ▶sub _js_sort_compare_user_fn {
Subroutine _js_sort_compare_user_fn: called CC=2 SCAR=6.9
1524 464600 my ( $self, $comparefn, $x, $y ) = @_;
1525  
1526 # a. Let v be ? ToNumber(? Call(comparefn, undefined, x, y)).
1527 464600 my $v = $self->_runtime->_to_number( $comparefn->( $x, $y ) );
1528  
1529 # b. If v is NaN, return +0.
1530 464588 ▶ return 0 if $v != $v;
Branch: 1 branch
BranchTrueFalseTotal
if $v != $v 3307 461281 464588
1531  
1532 # c. return v.
1533 461281 return $v;
1534 }
1535  
1536 # The pending runs, run #i at [2 * i] (base) and [2 * i + 1] (length).
1537 11910 ▶sub _js_sort_get_pending_runs_size { my ( $self, $sort_state ) = @_; $sort_state->{pending_runs_size} }
Subroutine _js_sort_get_pending_runs_size: called CC=1 SCAR=0.0
1538 2691 ▶sub _js_sort_get_pending_run_base { my ( $self, $pending_runs, $run ) = @_; $pending_runs->[ $run << 1 ] }
Subroutine _js_sort_get_pending_run_base: called CC=1 SCAR=0.0
1539 2758 ▶sub _js_sort_set_pending_run_base { my ( $self, $pending_runs, $run, $value ) = @_; $pending_runs->[ $run << 1 ] = $value; return }
Subroutine _js_sort_set_pending_run_base: called CC=1 SCAR=0.0
1540 10952 ▶sub _js_sort_get_pending_run_length { my ( $self, $pending_runs, $run ) = @_; $pending_runs->[ ( $run << 1 ) + 1 ] }
Subroutine _js_sort_get_pending_run_length: called CC=1 SCAR=0.0
1541 4100 ▶sub _js_sort_set_pending_run_length { my ( $self, $pending_runs, $run, $value ) = @_; $pending_runs->[ ( $run << 1 ) + 1 ] = $value; return }
Subroutine _js_sort_set_pending_run_length: called CC=1 SCAR=0.0
1542  
1543 2751 ▶sub _js_sort_push_run {
Subroutine _js_sort_push_run: called CC=1 SCAR=0.0
1544 2751 my ( $self, $sort_state, $base, $length ) = @_;
1545 2751 my $stack_size = $self->_js_sort_get_pending_runs_size($sort_state);
1546 2751 my $pending_runs = $sort_state->{pending_runs};
1547  
1548 2751 $self->_js_sort_set_pending_run_base( $pending_runs, $stack_size, $base );
1549 2751 $self->_js_sort_set_pending_run_length( $pending_runs, $stack_size, $length );
1550  
1551 2751 $sort_state->{pending_runs_size} = $stack_size + 1;
1552 2751 return;
1553 }
1554  
1555 # Returns the temporary array. V8 makes sure it has at least
1556 # max(kSortStateTempSize, requestedSize) slots; a Perl array grows on demand.
1557 1289 ▶sub _js_sort_get_temp_array {
Subroutine _js_sort_get_temp_array: called CC=1 SCAR=0.0
1558 1289 my ( $self, $sort_state, $requested_size ) = @_;
1559 1289 return $sort_state->{temp_array};
1560 }
1561  
1562 # source and target might be the same array, with overlapping ranges; V8 copies
1563 # from the back when srcPos < dstPos. A slice assignment reads the whole source
1564 # range before it writes, which gives the same result.
1565 6051 ▶sub _js_sort_copy {
Subroutine _js_sort_copy: called CC=1 SCAR=0.0
1566 6051 my ( $self, $source, $src_pos, $target, $dst_pos, $length ) = @_;
1567 6051 @{$target}[ $dst_pos .. $dst_pos + $length - 1 ] = @{$source}[ $src_pos .. $src_pos + $length - 1 ];
1568 6051 return;
1569 }
1570  
1571 # BinaryInsertionSort is the best method for sorting small arrays: it does few
1572 # compares, but can do data movement quadratic in the number of elements.
1573 # [low, high) is a contiguous range of an array, and is sorted via binary
1574 # insertion. This sort is stable. On entry, must have low <= start <= high, and
1575 # that [low, start) is already sorted. Pass start == low if you do not know!
1576 1950 ▶sub _js_sort_binary_insertion_sort {
Subroutine _js_sort_binary_insertion_sort: called CC=5 SCAR=16.1
1577 1950 my ( $self, $sort_state, $low, $start_arg, $high ) = @_;
1578 1950 my $work_array = $sort_state->{work_array};
1579  
1580 1950 ▶ my $start = $low == $start_arg ? $start_arg + 1 : $start_arg;
Branch: 1 branch
BranchTrueFalseTotal
$low == $start_arg ? : 0 1950 1950
1581  
1582 1950 ▶ for ( ; $start < $high; ++$start ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($start < $high) 61614 1950 63564
1583 # Set left to where a[start] belongs.
1584 61614 my $left = $low;
1585 61614 my $right = $start;
1586  
1587 61614 my $pivot = $work_array->[$right];
1588  
1589 # Invariants:
1590 # pivot >= all in [low, left).
1591 # pivot < all in [right, start).
1592 # Find pivot insertion point.
1593 61614 ▶ while ( $left < $right ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($left < $right) 266588 61614 328202
1594 266588 my $mid = $left + ( ( $right - $left ) >> 1 );
1595 266588 my $order = $self->_js_sort_compare( $sort_state, $pivot, $work_array->[$mid] );
1596  
1597 266588 ▶ if ( $order < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($order < 0) { } 128239 138349 266588
1598 128239 $right = $mid;
1599 } else {
1600 138349 $left = $mid + 1;
1601 }
1602 }
1603  
1604 # The invariants still hold, so pivot belongs at left. Note that if there
1605 # are elements equal to pivot, left points to the first slot after them --
1606 # that's why this sort is stable. Slide over to make room.
1607 61614 @{$work_array}[ $left + 1 .. $start ] = @{$work_array}[ $left .. $start - 1 ];
1608 61614 $work_array->[$left] = $pivot;
1609 }
1610 1950 return;
1611 }
1612  
1613 # Return the length of the run beginning at low, in the range [low, high), low
1614 # < high is required on entry. "A run" is the longest ascending sequence, with
1615 # a[low] <= a[low + 1] <= a[low + 2] <= ...
1616 # or the longest descending sequence, with
1617 # a[low] > a[low + 1] > a[low + 2] > ...
1618 # The strict ">" ensures there are no equal elements to get out of order when
1619 # a descending run is reversed, so the returned length is always an ascending
1620 # sequence.
1621 2763 ▶sub _js_sort_count_and_make_run {
Subroutine _js_sort_count_and_make_run: called CC=8 SCAR=20.8
1622 2763 my ( $self, $sort_state, $low_arg, $high ) = @_;
1623 2763 my $work_array = $sort_state->{work_array};
1624  
1625 2763 my $low = $low_arg + 1;
1626 2763 ▶ return 1 if $low == $high;
Branch: 1 branch
BranchTrueFalseTotal
if $low == $high 6 2757 2763
1627  
1628 2757 my $run_length = 2;
1629  
1630 2757 my $element_low = $work_array->[$low];
1631 2757 my $element_low_pred = $work_array->[ $low - 1 ];
1632 2757 my $order = $self->_js_sort_compare( $sort_state, $element_low, $element_low_pred );
1633  
1634 2747 ▶ my $is_descending = $order < 0 ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$order < 0 ? : 1118 1629 2747
1635  
1636 2747 my $previous_element = $element_low;
1637 2747 ▶ for ( my $idx = $low + 1; $idx < $high; ++$idx ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idx < $high) 63115 678 63793
1638 63115 my $current_element = $work_array->[$idx];
1639 63115 $order = $self->_js_sort_compare( $sort_state, $current_element, $previous_element );
1640  
1641 63113 ▶ if ($is_descending) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_descending) { } 20760 42353 63113
1642 20760 ▶ last if $order >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $order >= 0 880 19880 20760
1643 } else {
1644 42353 ▶ last if $order < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $order < 0 1187 41166 42353
1645 }
1646  
1647 61046 $previous_element = $current_element;
1648 61046 ++$run_length;
1649 }
1650  
1651 2745 ▶ $self->_js_sort_reverse_range( $work_array, $low_arg, $low_arg + $run_length ) if $is_descending;
Branch: 1 branch
BranchTrueFalseTotal
if $is_descending 1116 1629 2745
1652  
1653 2745 return $run_length;
1654 }
1655  
1656 1116 ▶sub _js_sort_reverse_range {
Subroutine _js_sort_reverse_range: called CC=1 SCAR=0.0
1657 1116 my ( $self, $array, $from, $to ) = @_;
1658 1116 @{$array}[ $from .. $to - 1 ] = reverse @{$array}[ $from .. $to - 1 ];
1659 1116 return;
1660 }
1661  
1662 # Merges the two runs at stack indices i and i + 1. We are only allowed to
1663 # either merge the two top-most runs, or leave the top most run alone and merge
1664 # the two next runs.
1665 1342 ▶sub _js_sort_merge_at {
Subroutine _js_sort_merge_at: called CC=5 SCAR=16.1
1666 1342 my ( $self, $sort_state, $i ) = @_;
1667 1342 my $stack_size = $self->_js_sort_get_pending_runs_size($sort_state);
1668 1342 my $work_array = $sort_state->{work_array};
1669  
1670 1342 my $pending_runs = $sort_state->{pending_runs};
1671 1342 my $base_a = $self->_js_sort_get_pending_run_base( $pending_runs, $i );
1672 1342 my $length_a = $self->_js_sort_get_pending_run_length( $pending_runs, $i );
1673 1342 my $base_b = $self->_js_sort_get_pending_run_base( $pending_runs, $i + 1 );
1674 1342 my $length_b = $self->_js_sort_get_pending_run_length( $pending_runs, $i + 1 );
1675  
1676 # Record the length of the combined runs; if i is the 3rd-last run now, also
1677 # slide over the last run (which isn't involved in this merge). The current
1678 # run i + 1 goes away in any case.
1679 1342 $self->_js_sort_set_pending_run_length( $pending_runs, $i, $length_a + $length_b );
1680 1342 ▶ if ( $i == $stack_size - 3 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i == $stack_size - 3) 7 1335 1342
1681 7 my $base = $self->_js_sort_get_pending_run_base( $pending_runs, $i + 2 );
1682 7 my $length = $self->_js_sort_get_pending_run_length( $pending_runs, $i + 2 );
1683 7 $self->_js_sort_set_pending_run_base( $pending_runs, $i + 1, $base );
1684 7 $self->_js_sort_set_pending_run_length( $pending_runs, $i + 1, $length );
1685 }
1686 1342 $sort_state->{pending_runs_size} = $stack_size - 1;
1687  
1688 # Where does b start in a? Elements in a before that can be ignored, because
1689 # they are already in place.
1690 1342 my $key_right = $work_array->[$base_b];
1691 1342 my $k = $self->_js_sort_gallop_right( $sort_state, $work_array, $key_right, $base_a, $length_a, 0 );
1692  
1693 1342 $base_a = $base_a + $k;
1694 1342 $length_a = $length_a - $k;
1695 1342 ▶ return if $length_a == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $length_a == 0 36 1306 1342
1696  
1697 # Where does a end in b? Elements in b after that can be ignored, because
1698 # they are already in place.
1699 1306 my $key_left = $work_array->[ $base_a + $length_a - 1 ];
1700 1306 $length_b = $self->_js_sort_gallop_left( $sort_state, $work_array, $key_left, $base_b, $length_b, $length_b - 1 );
1701 1306 ▶ return if $length_b == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $length_b == 0 17 1289 1306
1702  
1703 # Merge what remains of the runs, using a temp array with min(lengthA,
1704 # lengthB) elements.
1705 1289 ▶ if ( $length_a <= $length_b ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($length_a <= $length_b) { } 722 567 1289
1706 722 $self->_js_sort_merge_low( $sort_state, $base_a, $length_a, $base_b, $length_b );
1707 } else {
1708 567 $self->_js_sort_merge_high( $sort_state, $base_a, $length_a, $base_b, $length_b );
1709 }
1710 1289 return;
1711 }
1712  
1713 # Locates the proper position of key in a sorted array; if the array contains
1714 # an element equal to key, return the position immediately to the left of the
1715 # leftmost equal element. (GallopRight does the same except returns the
1716 # position to the right of the rightmost equal element (if any)).
1717 #
1718 # The array is sorted with "length" elements, starting at "base". "length" must
1719 # be > 0. "hint" is an index at which to begin the search, 0 <= hint < n. The
1720 # closer hint is to the final result, the faster this runs.
1721 #
1722 # The return value is the int offset in 0..length such that
1723 # array[base + offset] < key <= array[base + offset + 1]
1724 # pretending that array[base - 1] is minus infinity and array[base + len] is
1725 # plus infinity. In other words, key belongs at index base + k.
1726 3569 ▶sub _js_sort_gallop_left {
Subroutine _js_sort_gallop_left: called CC=10 SCAR=23.0
1727 3569 my ( $self, $sort_state, $array, $key, $base, $length, $hint ) = @_;
1728  
1729 3569 my $last_ofs = 0;
1730 3569 my $offset = 1;
1731  
1732 3569 my $base_hint_element = $array->[ $base + $hint ];
1733 3569 my $order = $self->_js_sort_compare( $sort_state, $base_hint_element, $key );
1734  
1735 3569 ▶ if ( $order < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($order < 0) { } 1863 1706 3569
1736 # a[base + hint] < key: gallop right, until
1737 # a[base + hint + lastOfs] < key <= a[base + hint + offset].
1738  
1739 # a[base + length - 1] is highest.
1740 1863 my $max_ofs = $length - $hint;
1741 1863 ▶ while ( $offset < $max_ofs ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset < $max_ofs) 3928 1095 5023
1742 3928 my $offset_element = $array->[ $base + $hint + $offset ];
1743 3928 $order = $self->_js_sort_compare( $sort_state, $offset_element, $key );
1744  
1745 # a[base + hint + offset] >= key? Break.
1746 3928 ▶ last if $order >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $order >= 0 768 3160 3928
1747  
1748 3160 $last_ofs = $offset;
1749 3160 $offset = ( $offset << 1 ) + 1;
1750 }
1751  
1752 1863 ▶ $offset = $max_ofs if $offset > $max_ofs;
Branch: 1 branch
BranchTrueFalseTotal
if $offset > $max_ofs 258 1605 1863
1753  
1754 # Translate back to positive offsets relative to base.
1755 1863 $last_ofs = $last_ofs + $hint;
1756 1863 $offset = $offset + $hint;
1757 } else {
1758 # key <= a[base + hint]: gallop left, until
1759 # a[base + hint - offset] < key <= a[base + hint - lastOfs].
1760  
1761 # a[base + hint] is lowest.
1762 1706 my $max_ofs = $hint + 1;
1763 1706 ▶ while ( $offset < $max_ofs ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset < $max_ofs) 4972 289 5261
1764 4972 my $offset_element = $array->[ $base + $hint - $offset ];
1765 4972 $order = $self->_js_sort_compare( $sort_state, $offset_element, $key );
1766  
1767 4972 ▶ last if $order < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $order < 0 1417 3555 4972
1768  
1769 3555 $last_ofs = $offset;
1770 3555 $offset = ( $offset << 1 ) + 1;
1771 }
1772  
1773 1706 ▶ $offset = $max_ofs if $offset > $max_ofs;
Branch: 1 branch
BranchTrueFalseTotal
if $offset > $max_ofs 113 1593 1706
1774  
1775 # Translate back to positive offsets relative to base.
1776 1706 my $tmp = $last_ofs;
1777 1706 $last_ofs = $hint - $offset;
1778 1706 $offset = $hint - $tmp;
1779 }
1780  
1781 # Now a[base+lastOfs] < key <= a[base+offset], so key belongs somewhere to the
1782 # right of lastOfs but no farther right than offset. Do a binary search, with
1783 # invariant: a[base + lastOfs - 1] < key <= a[base + offset].
1784 3569 $last_ofs++;
1785 3569 ▶ while ( $last_ofs < $offset ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($last_ofs < $offset) 6268 3569 9837
1786 6268 my $m = $last_ofs + ( ( $offset - $last_ofs ) >> 1 );
1787  
1788 6268 $order = $self->_js_sort_compare( $sort_state, $array->[ $base + $m ], $key );
1789  
1790 6268 ▶ if ( $order < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($order < 0) { } 3155 3113 6268
1791 3155 $last_ofs = $m + 1; # a[base + m] < key.
1792 } else {
1793 3113 $offset = $m; # key <= a[base + m].
1794 }
1795 }
1796 # so a[base + offset - 1] < key <= a[base + offset].
1797 3569 return $offset;
1798 }
1799  
1800 # Exactly like GallopLeft, except that if key already exists in [base, base +
1801 # length), finds the position immediately to the right of the rightmost equal
1802 # value. The return value is the int offset in 0..length such that
1803 # array[base + offset - 1] <= key < array[base + offset]
1804 3884 ▶sub _js_sort_gallop_right {
Subroutine _js_sort_gallop_right: called CC=10 SCAR=23.0
1805 3884 my ( $self, $sort_state, $array, $key, $base, $length, $hint ) = @_;
1806  
1807 3884 my $last_ofs = 0;
1808 3884 my $offset = 1;
1809  
1810 3884 my $base_hint_element = $array->[ $base + $hint ];
1811 3884 my $order = $self->_js_sort_compare( $sort_state, $key, $base_hint_element );
1812  
1813 3884 ▶ if ( $order < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($order < 0) { } 1888 1996 3884
1814 # key < a[base + hint]: gallop left, until
1815 # a[base + hint - offset] <= key < a[base + hint - lastOfs].
1816  
1817 # a[base + hint] is lowest.
1818 1888 my $max_ofs = $hint + 1;
1819 1888 ▶ while ( $offset < $max_ofs ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset < $max_ofs) 3187 1187 4374
1820 3187 my $offset_element = $array->[ $base + $hint - $offset ];
1821 3187 $order = $self->_js_sort_compare( $sort_state, $key, $offset_element );
1822  
1823 3187 ▶ last if $order >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $order >= 0 701 2486 3187
1824  
1825 2486 $last_ofs = $offset;
1826 2486 $offset = ( $offset << 1 ) + 1;
1827 }
1828  
1829 1888 ▶ $offset = $max_ofs if $offset > $max_ofs;
Branch: 1 branch
BranchTrueFalseTotal
if $offset > $max_ofs 165 1723 1888
1830  
1831 # Translate back to positive offsets relative to base.
1832 1888 my $tmp = $last_ofs;
1833 1888 $last_ofs = $hint - $offset;
1834 1888 $offset = $hint - $tmp;
1835 } else {
1836 # a[base + hint] <= key: gallop right, until
1837 # a[base + hint + lastOfs] <= key < a[base + hint + offset].
1838  
1839 # a[base + length - 1] is highest.
1840 1996 my $max_ofs = $length - $hint;
1841 1996 ▶ while ( $offset < $max_ofs ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset < $max_ofs) 5569 490 6059
1842 5569 my $offset_element = $array->[ $base + $hint + $offset ];
1843 5569 $order = $self->_js_sort_compare( $sort_state, $key, $offset_element );
1844  
1845 # a[base + hint + ofs] <= key.
1846 5569 ▶ last if $order < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $order < 0 1506 4063 5569
1847  
1848 4063 $last_ofs = $offset;
1849 4063 $offset = ( $offset << 1 ) + 1;
1850 }
1851  
1852 1996 ▶ $offset = $max_ofs if $offset > $max_ofs;
Branch: 1 branch
BranchTrueFalseTotal
if $offset > $max_ofs 146 1850 1996
1853  
1854 # Translate back to positive offests relative to base.
1855 1996 $last_ofs = $last_ofs + $hint;
1856 1996 $offset = $offset + $hint;
1857 }
1858  
1859 # Now a[base + lastOfs] <= key < a[base + ofs], so key belongs somewhere to
1860 # the right of lastOfs but no farther right than ofs. Do a binary search, with
1861 # invariant a[base + lastOfs - 1] < key <= a[base + ofs].
1862 3884 $last_ofs++;
1863 3884 ▶ while ( $last_ofs < $offset ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($last_ofs < $offset) 6186 3884 10070
1864 6186 my $m = $last_ofs + ( ( $offset - $last_ofs ) >> 1 );
1865  
1866 6186 $order = $self->_js_sort_compare( $sort_state, $key, $array->[ $base + $m ] );
1867  
1868 6186 ▶ if ( $order < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($order < 0) { } 3629 2557 6186
1869 3629 $offset = $m; # key < a[base + m].
1870 } else {
1871 2557 $last_ofs = $m + 1; # a[base + m] <= key.
1872 }
1873 }
1874 # so a[base + offset - 1] <= key < a[base + offset].
1875 3884 return $offset;
1876 }
1877  
1878 # Merge the lengthA elements starting at baseA with the lengthB elements
1879 # starting at baseB in a stable way, in-place. lengthA and lengthB must be > 0,
1880 # and baseA + lengthA == baseB. Must also have that array[baseB] <
1881 # array[baseA], that array[baseA + lengthA - 1] belongs at the end of the
1882 # merge, and should have lengthA <= lengthB.
1883 #
1884 # The .tq's try / label blocks: `goto Succeed` and `goto CopyB` leave the MERGE
1885 # block with `last MERGE`, the label's name in $goto.
1886 722 ▶sub _js_sort_merge_low {
Subroutine _js_sort_merge_low: called CC=21 SCAR=30.4
1887 722 my ( $self, $sort_state, $base_a, $length_a_arg, $base_b, $length_b_arg ) = @_;
1888  
1889 722 my $length_a = $length_a_arg;
1890 722 my $length_b = $length_b_arg;
1891  
1892 722 my $work_array = $sort_state->{work_array};
1893 722 my $temp_array = $self->_js_sort_get_temp_array( $sort_state, $length_a );
1894 722 $self->_js_sort_copy( $work_array, $base_a, $temp_array, 0, $length_a );
1895  
1896 722 my $dest = $base_a;
1897 722 my $cursor_temp = 0;
1898 722 my $cursor_b = $base_b;
1899  
1900 722 $work_array->[ $dest++ ] = $work_array->[ $cursor_b++ ];
1901  
1902 722 my $goto = 'Succeed';
1903 MERGE: {
1904 722 ▶ last MERGE if --$length_b == 0;
Branch: 1 branch
BranchTrueFalseTotal
if --$length_b == 0 2 720 722
1905 720 ▶ if ( $length_a == 1 ) { $goto = 'CopyB'; last MERGE }
Branch: 1 branch
BranchTrueFalseTotal
if ($length_a == 1) 6 714 720
1906  
1907 714 my $min_gallop = $sort_state->{min_gallop};
1908 714 while (1) {
1909 1005 my $nof_wins_a = 0; # # of times A won in a row.
1910 1005 my $nof_wins_b = 0; # # of times B won in a row.
1911  
1912 # Do the straightforward thing until (if ever) one run appears to win
1913 # consistently.
1914 1005 while (1) {
1915 63603 my $order = $self->_js_sort_compare( $sort_state, $work_array->[$cursor_b], $temp_array->[$cursor_temp] );
1916  
1917 63603 ▶ if ( $order < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($order < 0) { } 31306 32297 63603
1918 31306 $work_array->[ $dest++ ] = $work_array->[ $cursor_b++ ];
1919  
1920 31306 ++$nof_wins_b;
1921 31306 --$length_b;
1922 31306 $nof_wins_a = 0;
1923  
1924 31306 ▶ last MERGE if $length_b == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $length_b == 0 170 31136 31306
1925 31136 ▶ last if $nof_wins_b >= $min_gallop;
Branch: 1 branch
BranchTrueFalseTotal
if $nof_wins_b >= $min_gallop 338 30798 31136
1926 } else {
1927 32297 $work_array->[ $dest++ ] = $temp_array->[ $cursor_temp++ ];
1928  
1929 32297 ++$nof_wins_a;
1930 32297 --$length_a;
1931 32297 $nof_wins_b = 0;
1932  
1933 32297 ▶ if ( $length_a == 1 ) { $goto = 'CopyB'; last MERGE }
Branch: 1 branch
BranchTrueFalseTotal
if ($length_a == 1) 251 32046 32297
1934 32046 ▶ last if $nof_wins_a >= $min_gallop;
Branch: 1 branch
BranchTrueFalseTotal
if $nof_wins_a >= $min_gallop 246 31800 32046
1935 }
1936 }
1937  
1938 # One run is winning so consistently that galloping may be a huge win. So
1939 # try that, and continue galloping until (if ever) neither run appears to
1940 # be winning consistently anymore.
1941 584 ++$min_gallop;
1942 584 my $first_iteration = 1;
1943 584 ▶ while ( $nof_wins_a >= $JS_SORT_MIN_GALLOP_WINS || $nof_wins_b >= $JS_SORT_MIN_GALLOP_WINS || $first_iteration ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nof_wins_a >= $JS_SORT_MIN_GALLOP_WINS or $nof_wins_b >= $JS_SORT_MIN_GALLOP_WINS or $first_iteration) 1329 291 1620
Condition100%6/6
$nof_wins_a >= $JS_SORT_MIN_GALLOP_WINS or $nof_wins_b >= $JS_SORT_MIN_GALLOP_WINS or $first_iteration
l!l&&r!l&&!r
1063266291
$nof_wins_a >= $JS_SORT_MIN_GALLOP_WINS or $nof_wins_b >= $JS_SORT_MIN_GALLOP_WINS
l!l&&r!l&&!r
633430557
MC/DC100%3/3
$nof_wins_a >= $JS_SORT_MIN_GALLOP_WINS or $nof_wins_b >= $JS_SORT_MIN_GALLOP_WINS or $first_iteration
$nof_wins_a >= $JS_SORT_MIN_GALLOP_WINS $nof_wins_b >= $JS_SORT_MIN_GALLOP_WINS $first_iteration
Truth table100%4/4
A or B or C
A= $nof_wins_a >= $JS_SORT_MIN_GALLOP_WINSB= $nof_wins_b >= $JS_SORT_MIN_GALLOP_WINSC= $first_iteration
ABCresult
1XX1
01X1
0011
0000
1944 1329 $first_iteration = 0;
1945  
1946 1329 ▶ $min_gallop = $min_gallop - 1 > 1 ? $min_gallop - 1 : 1; # SmiMax(1, minGallop - 1)
Branch: 1 branch
BranchTrueFalseTotal
$min_gallop - 1 > 1 ? : 777 552 1329
1947 1329 $sort_state->{min_gallop} = $min_gallop;
1948  
1949 1329 $nof_wins_a = $self->_js_sort_gallop_right( $sort_state, $temp_array, $work_array->[$cursor_b], $cursor_temp, $length_a, 0 );
1950  
1951 1329 ▶ if ( $nof_wins_a > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nof_wins_a > 0) 805 524 1329
1952 805 $self->_js_sort_copy( $temp_array, $cursor_temp, $work_array, $dest, $nof_wins_a );
1953 805 $dest = $dest + $nof_wins_a;
1954 805 $cursor_temp = $cursor_temp + $nof_wins_a;
1955 805 $length_a = $length_a - $nof_wins_a;
1956  
1957 805 ▶ if ( $length_a == 1 ) { $goto = 'CopyB'; last MERGE }
Branch: 1 branch
BranchTrueFalseTotal
if ($length_a == 1) 26 779 805
1958  
1959 # lengthA == 0 is impossible now if the comparison function is
1960 # consistent, but we can't assume that it is.
1961 779 ▶ last MERGE if $length_a == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $length_a == 0 13 766 779
1962 }
1963 1290 $work_array->[ $dest++ ] = $work_array->[ $cursor_b++ ];
1964 1290 ▶ last MERGE if --$length_b == 0;
Branch: 1 branch
BranchTrueFalseTotal
if --$length_b == 0 84 1206 1290
1965  
1966 1206 $nof_wins_b = $self->_js_sort_gallop_left( $sort_state, $work_array, $temp_array->[$cursor_temp], $cursor_b, $length_b, 0 );
1967 1206 ▶ if ( $nof_wins_b > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nof_wins_b > 0) 1052 154 1206
1968 1052 $self->_js_sort_copy( $work_array, $cursor_b, $work_array, $dest, $nof_wins_b );
1969  
1970 1052 $dest = $dest + $nof_wins_b;
1971 1052 $cursor_b = $cursor_b + $nof_wins_b;
1972 1052 $length_b = $length_b - $nof_wins_b;
1973  
1974 1052 ▶ last MERGE if $length_b == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $length_b == 0 158 894 1052
1975 }
1976 1048 $work_array->[ $dest++ ] = $temp_array->[ $cursor_temp++ ];
1977 1048 ▶ if ( --$length_a == 1 ) { $goto = 'CopyB'; last MERGE }
Branch: 1 branch
BranchTrueFalseTotal
if (--$length_a == 1) 12 1036 1048
1978 }
1979 291 ++$min_gallop; # Penalize it for leaving galloping mode
1980 291 $sort_state->{min_gallop} = $min_gallop;
1981 }
1982 }
1983  
1984 722 ▶ if ( $goto eq 'Succeed' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($goto eq 'Succeed') { } 427 295 722
1985 427 ▶ $self->_js_sort_copy( $temp_array, $cursor_temp, $work_array, $dest, $length_a ) if $length_a > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $length_a > 0 414 13 427
1986 } else { # CopyB
1987 # The last element of run A belongs at the end of the merge.
1988 295 $self->_js_sort_copy( $work_array, $cursor_b, $work_array, $dest, $length_b );
1989 295 $work_array->[ $dest + $length_b ] = $temp_array->[$cursor_temp];
1990 }
1991 722 return;
1992 }
1993  
1994 # Merge the lengthA elements starting at baseA with the lengthB elements
1995 # starting at baseB in a stable way, in-place. lengthA and lengthB must be > 0.
1996 # Must also have that array[baseA + lengthA - 1] belongs at the end of the
1997 # merge and should have lengthA >= lengthB. Labels as in _js_sort_merge_low,
1998 # here Succeed and CopyA.
1999 567 ▶sub _js_sort_merge_high {
Subroutine _js_sort_merge_high: called CC=21 SCAR=30.4
2000 567 my ( $self, $sort_state, $base_a, $length_a_arg, $base_b, $length_b_arg ) = @_;
2001  
2002 567 my $length_a = $length_a_arg;
2003 567 my $length_b = $length_b_arg;
2004  
2005 567 my $work_array = $sort_state->{work_array};
2006 567 my $temp_array = $self->_js_sort_get_temp_array( $sort_state, $length_b );
2007 567 $self->_js_sort_copy( $work_array, $base_b, $temp_array, 0, $length_b );
2008  
2009 # MergeHigh merges the two runs backwards.
2010 567 my $dest = $base_b + $length_b - 1;
2011 567 my $cursor_temp = $length_b - 1;
2012 567 my $cursor_a = $base_a + $length_a - 1;
2013  
2014 567 $work_array->[ $dest-- ] = $work_array->[ $cursor_a-- ];
2015  
2016 567 my $goto = 'Succeed';
2017 MERGE: {
2018 567 ▶ last MERGE if --$length_a == 0;
Branch: 1 branch
BranchTrueFalseTotal
if --$length_a == 0 0 567 567
2019 567 ▶ if ( $length_b == 1 ) { $goto = 'CopyA'; last MERGE }
Branch: 1 branch
BranchTrueFalseTotal
if ($length_b == 1) 9 558 567
2020  
2021 558 my $min_gallop = $sort_state->{min_gallop};
2022 558 while (1) {
2023 910 my $nof_wins_a = 0; # # of times A won in a row.
2024 910 my $nof_wins_b = 0; # # of times B won in a row.
2025  
2026 # Do the straightforward thing until (if ever) one run appears to win
2027 # consistently.
2028 910 while (1) {
2029 67294 my $order = $self->_js_sort_compare( $sort_state, $temp_array->[$cursor_temp], $work_array->[$cursor_a] );
2030  
2031 67294 ▶ if ( $order < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($order < 0) { } 33686 33608 67294
2032 33686 $work_array->[ $dest-- ] = $work_array->[ $cursor_a-- ];
2033  
2034 33686 ++$nof_wins_a;
2035 33686 --$length_a;
2036 33686 $nof_wins_b = 0;
2037  
2038 33686 ▶ last MERGE if $length_a == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $length_a == 0 130 33556 33686
2039 33556 ▶ last if $nof_wins_a >= $min_gallop;
Branch: 1 branch
BranchTrueFalseTotal
if $nof_wins_a >= $min_gallop 340 33216 33556
2040 } else {
2041 33608 $work_array->[ $dest-- ] = $temp_array->[ $cursor_temp-- ];
2042  
2043 33608 ++$nof_wins_b;
2044 33608 --$length_b;
2045 33608 $nof_wins_a = 0;
2046  
2047 33608 ▶ if ( $length_b == 1 ) { $goto = 'CopyA'; last MERGE }
Branch: 1 branch
BranchTrueFalseTotal
if ($length_b == 1) 222 33386 33608
2048 33386 ▶ last if $nof_wins_b >= $min_gallop;
Branch: 1 branch
BranchTrueFalseTotal
if $nof_wins_b >= $min_gallop 218 33168 33386
2049 }
2050 }
2051  
2052 # One run is winning so consistently that galloping may be a huge win. So
2053 # try that, and continue galloping until (if ever) neither run appears to
2054 # be winning consistently anymore.
2055 558 ++$min_gallop;
2056 558 my $first_iteration = 1;
2057 558 ▶ while ( $nof_wins_a >= $JS_SORT_MIN_GALLOP_WINS || $nof_wins_b >= $JS_SORT_MIN_GALLOP_WINS || $first_iteration ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nof_wins_a >= $JS_SORT_MIN_GALLOP_WINS or $nof_wins_b >= $JS_SORT_MIN_GALLOP_WINS or $first_iteration) 1213 352 1565
Condition100%6/6
$nof_wins_a >= $JS_SORT_MIN_GALLOP_WINS or $nof_wins_b >= $JS_SORT_MIN_GALLOP_WINS or $first_iteration
l!l&&r!l&&!r
924289352
$nof_wins_a >= $JS_SORT_MIN_GALLOP_WINS or $nof_wins_b >= $JS_SORT_MIN_GALLOP_WINS
l!l&&r!l&&!r
610314641
MC/DC100%3/3
$nof_wins_a >= $JS_SORT_MIN_GALLOP_WINS or $nof_wins_b >= $JS_SORT_MIN_GALLOP_WINS or $first_iteration
$nof_wins_a >= $JS_SORT_MIN_GALLOP_WINS $nof_wins_b >= $JS_SORT_MIN_GALLOP_WINS $first_iteration
Truth table100%4/4
A or B or C
A= $nof_wins_a >= $JS_SORT_MIN_GALLOP_WINSB= $nof_wins_b >= $JS_SORT_MIN_GALLOP_WINSC= $first_iteration
ABCresult
1XX1
01X1
0011
0000
2058 1213 $first_iteration = 0;
2059  
2060 1213 ▶ $min_gallop = $min_gallop - 1 > 1 ? $min_gallop - 1 : 1; # SmiMax(1, minGallop - 1)
Branch: 1 branch
BranchTrueFalseTotal
$min_gallop - 1 > 1 ? : 774 439 1213
2061 1213 $sort_state->{min_gallop} = $min_gallop;
2062  
2063 1213 my $k = $self->_js_sort_gallop_right( $sort_state, $work_array, $temp_array->[$cursor_temp], $base_a, $length_a, $length_a - 1 );
2064 1213 $nof_wins_a = $length_a - $k;
2065  
2066 1213 ▶ if ( $nof_wins_a > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nof_wins_a > 0) 889 324 1213
2067 889 $dest = $dest - $nof_wins_a;
2068 889 $cursor_a = $cursor_a - $nof_wins_a;
2069 889 $self->_js_sort_copy( $work_array, $cursor_a + 1, $work_array, $dest + 1, $nof_wins_a );
2070  
2071 889 $length_a = $length_a - $nof_wins_a;
2072 889 ▶ last MERGE if $length_a == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $length_a == 0 134 755 889
2073 }
2074 1079 $work_array->[ $dest-- ] = $temp_array->[ $cursor_temp-- ];
2075 1079 ▶ if ( --$length_b == 1 ) { $goto = 'CopyA'; last MERGE }
Branch: 1 branch
BranchTrueFalseTotal
if (--$length_b == 1) 22 1057 1079
2076  
2077 1057 $k = $self->_js_sort_gallop_left( $sort_state, $temp_array, $work_array->[$cursor_a], 0, $length_b, $length_b - 1 );
2078 1057 $nof_wins_b = $length_b - $k;
2079  
2080 1057 ▶ if ( $nof_wins_b > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nof_wins_b > 0) 772 285 1057
2081 772 $dest = $dest - $nof_wins_b;
2082 772 $cursor_temp = $cursor_temp - $nof_wins_b;
2083 772 $self->_js_sort_copy( $temp_array, $cursor_temp + 1, $work_array, $dest + 1, $nof_wins_b );
2084  
2085 772 $length_b = $length_b - $nof_wins_b;
2086 772 ▶ if ( $length_b == 1 ) { $goto = 'CopyA'; last MERGE }
Branch: 1 branch
BranchTrueFalseTotal
if ($length_b == 1) 5 767 772
2087  
2088 # lengthB == 0 is impossible now if the comparison function is
2089 # consistent, but we can't assume that it is.
2090 767 ▶ last MERGE if $length_b == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $length_b == 0 32 735 767
2091 }
2092 1020 $work_array->[ $dest-- ] = $work_array->[ $cursor_a-- ];
2093 1020 ▶ last MERGE if --$length_a == 0;
Branch: 1 branch
BranchTrueFalseTotal
if --$length_a == 0 13 1007 1020
2094 }
2095 352 ++$min_gallop;
2096 352 $sort_state->{min_gallop} = $min_gallop;
2097 }
2098 }
2099  
2100 567 ▶ if ( $goto eq 'Succeed' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($goto eq 'Succeed') { } 309 258 567
2101 309 ▶ $self->_js_sort_copy( $temp_array, 0, $work_array, $dest - ( $length_b - 1 ), $length_b ) if $length_b > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $length_b > 0 277 32 309
2102 } else { # CopyA
2103 # The first element of run B belongs at the front of the merge.
2104 258 $dest = $dest - $length_a;
2105 258 $cursor_a = $cursor_a - $length_a;
2106 258 $self->_js_sort_copy( $work_array, $cursor_a + 1, $work_array, $dest + 1, $length_a );
2107 258 $work_array->[$dest] = $temp_array->[$cursor_temp];
2108 }
2109 567 return;
2110 }
2111  
2112 # Compute a good value for the minimum run length; natural runs shorter than
2113 # this are boosted artificially via binary insertion sort. If n < 64, return n
2114 # (it's too small to bother with fancy stuff). Else if n is an exact power of 2,
2115 # return 32. Else return an int k, 32 <= k <= 64, such that n/k is close to,
2116 # but strictly less than, an exact power of 2.
2117 1421 ▶sub _js_sort_compute_min_run_length {
Subroutine _js_sort_compute_min_run_length: called CC=2 SCAR=6.9
2118 1421 my ( $self, $n_arg ) = @_;
2119 1421 my $n = $n_arg;
2120 1421 my $r = 0; # Becomes 1 if any 1 bits are shifted off.
2121  
2122 1421 ▶ while ( $n >= 64 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n >= 64) 873 1421 2294
2123 873 $r = $r | ( $n & 1 );
2124 873 $n = $n >> 1;
2125 }
2126  
2127 1421 return $n + $r;
2128 }
2129  
2130 # Returns true iff run_length(n - 2) > run_length(n - 1) + run_length(n).
2131 3519 ▶sub _js_sort_run_invariant_established {
Subroutine _js_sort_run_invariant_established: called CC=3 SCAR=11.0
2132 3519 my ( $self, $pending_runs, $n ) = @_;
2133 3519 ▶ return 1 if $n < 2;
Branch: 1 branch
BranchTrueFalseTotal
if $n < 2 2160 1359 3519
2134  
2135 1359 my $run_length_n = $self->_js_sort_get_pending_run_length( $pending_runs, $n );
2136 1359 my $run_length_nm = $self->_js_sort_get_pending_run_length( $pending_runs, $n - 1 );
2137 1359 my $run_length_nmm = $self->_js_sort_get_pending_run_length( $pending_runs, $n - 2 );
2138  
2139 1359 ▶ return $run_length_nmm > $run_length_nm + $run_length_n ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$run_length_nmm > $run_length_nm + $run_length_n ? : 1038 321 1359
2140 }
2141  
2142 # Examines the stack of runs waiting to be merged, merging adjacent runs until
2143 # the stack invariants are re-established:
2144 # 1. run_length(i - 3) > run_length(i - 2) + run_length(i - 1)
2145 # 2. run_length(i - 2) > run_length(i - 1)
2146 2751 ▶sub _js_sort_merge_collapse {
Subroutine _js_sort_merge_collapse: called CC=6 SCAR=17.9
2147 2751 my ( $self, $sort_state ) = @_;
2148 2751 my $pending_runs = $sort_state->{pending_runs};
2149  
2150 # Reload the stack size because MergeAt might change it.
2151 2751 ▶ while ( $self->_js_sort_get_pending_runs_size($sort_state) > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_js_sort_get_pending_runs_size($sort_state) > 1) 1918 1778 3696
2152 1918 my $n = $self->_js_sort_get_pending_runs_size($sort_state) - 2;
2153  
2154 1918 ▶ if ( !$self->_js_sort_run_invariant_established( $pending_runs, $n + 1 )
Branch: 2 branches
BranchTrueFalseTotal
if (not $self->_js_sort_run_invariant_established($pending_runs, $n + 1) && $self->_js_sort_run_invariant_established($pending_runs, $n)) { } 321 1597 1918
elsif ($self->_js_sort_get_pending_run_length($pending_runs, $n) <= $self->_js_sort_get_pending_run_length($pending_runs, $n + 1)) { } 624 973 1597
Condition100%3/3
$self->_js_sort_run_invariant_established($pending_runs, $n + 1) && $self->_js_sort_run_invariant_established($pending_runs, $n)
!ll&&!rl&&r
31741597
MC/DC100%2/2
$self->_js_sort_run_invariant_established($pending_runs, $n + 1) && $self->_js_sort_run_invariant_established($pending_runs, $n)
$self->_js_sort_run_invariant_established($pending_runs, $n + 1) $self->_js_sort_run_invariant_established($pending_runs, $n)
Truth table100%3/3
A && B
A= $self->_js_sort_run_invariant_established($pending_runs, $n + 1)B= $self->_js_sort_run_invariant_established($pending_runs, $n)
ABresult
0X0
100
111
2155 || !$self->_js_sort_run_invariant_established( $pending_runs, $n ) )
2156 {
2157 321 ▶ --$n
Branch: 1 branch
BranchTrueFalseTotal
if $self->_js_sort_get_pending_run_length($pending_runs, $n - 1) < $self->_js_sort_get_pending_run_length($pending_runs, $n + 1) 7 314 321
2158 if $self->_js_sort_get_pending_run_length( $pending_runs, $n - 1 )
2159 < $self->_js_sort_get_pending_run_length( $pending_runs, $n + 1 );
2160  
2161 321 $self->_js_sort_merge_at( $sort_state, $n );
2162 } elsif ( $self->_js_sort_get_pending_run_length( $pending_runs, $n )
2163 <= $self->_js_sort_get_pending_run_length( $pending_runs, $n + 1 ) )
2164 {
2165 624 $self->_js_sort_merge_at( $sort_state, $n );
2166 } else {
2167 973 last;
2168 }
2169 }
2170 2751 return;
2171 }
2172  
2173 # Regardless of invariants, merge all runs on the stack until only one remains.
2174 # This is used at the end of the mergesort.
2175 1409 ▶sub _js_sort_merge_force_collapse {
Subroutine _js_sort_merge_force_collapse: called CC=4 SCAR=14.0
2176 1409 my ( $self, $sort_state ) = @_;
2177 1409 my $pending_runs = $sort_state->{pending_runs};
2178  
2179 # Reload the stack size because MergeAt might change it.
2180 1409 ▶ while ( $self->_js_sort_get_pending_runs_size($sort_state) > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_js_sort_get_pending_runs_size($sort_state) > 1) 397 1409 1806
2181 397 my $n = $self->_js_sort_get_pending_runs_size($sort_state) - 2;
2182  
2183 397 ▶ --$n
Branch: 1 branch
BranchTrueFalseTotal
if $n > 0 and $self->_js_sort_get_pending_run_length($pending_runs, $n - 1) < $self->_js_sort_get_pending_run_length($pending_runs, $n + 1) 0 397 397
Condition66%2/3
$n > 0 and $self->_js_sort_get_pending_run_length($pending_runs, $n - 1) < $self->_js_sort_get_pending_run_length($pending_runs, $n + 1)
!ll&&!rl&&r
2231740
MC/DC0%0/2
$n > 0 and $self->_js_sort_get_pending_run_length($pending_runs, $n - 1) < $self->_js_sort_get_pending_run_length($pending_runs, $n + 1)
$n > 0 $self->_js_sort_get_pending_run_length($pending_runs, $n - 1) < $self->_js_sort_get_pending_run_length($pending_runs, $n + 1)
Truth table66%2/3
A and B
A= $n > 0B= $self->_js_sort_get_pending_run_length($pending_runs, $n - 1) < $self->_js_sort_get_pending_run_length($pending_runs, $n + 1)
ABresult
0X0
100
111
2184 if $n > 0
2185 && $self->_js_sort_get_pending_run_length( $pending_runs, $n - 1 )
2186 < $self->_js_sort_get_pending_run_length( $pending_runs, $n + 1 );
2187 397 $self->_js_sort_merge_at( $sort_state, $n );
2188 }
2189 1409 return;
2190 }
2191  
2192 1432 ▶sub _js_array_tim_sort_impl {
Subroutine _js_array_tim_sort_impl: called CC=5 SCAR=16.1
2193 1432 my ( $self, $sort_state, $length ) = @_;
2194 1432 ▶ return if $length < 2;
Branch: 1 branch
BranchTrueFalseTotal
if $length < 2 11 1421 1432
2195 1421 my $remaining = $length;
2196  
2197 # March over the array once, left to right, finding natural runs, and
2198 # extending short natural runs to minrun elements.
2199 1421 my $low = 0;
2200 1421 my $min_run_length = $self->_js_sort_compute_min_run_length($remaining);
2201 1421 ▶ while ( $remaining != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remaining != 0) 2763 1409 4172
2202 2763 my $current_run_length = $self->_js_sort_count_and_make_run( $sort_state, $low, $low + $remaining );
2203  
2204 # If the run is short, extend it to min(minRunLength, remaining).
2205 2751 ▶ if ( $current_run_length < $min_run_length ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current_run_length < $min_run_length) 1950 801 2751
2206 1950 ▶ my $forced_run_length = $min_run_length < $remaining ? $min_run_length : $remaining;
Branch: 1 branch
BranchTrueFalseTotal
$min_run_length < $remaining ? : 1192 758 1950
2207 1950 $self->_js_sort_binary_insertion_sort( $sort_state, $low, $low + $current_run_length, $low + $forced_run_length );
2208 1950 $current_run_length = $forced_run_length;
2209 }
2210  
2211 # Push run onto pending-runs stack, and maybe merge.
2212 2751 $self->_js_sort_push_run( $sort_state, $low, $current_run_length );
2213  
2214 2751 $self->_js_sort_merge_collapse($sort_state);
2215  
2216 # Advance to find next run.
2217 2751 $low = $low + $current_run_length;
2218 2751 $remaining = $remaining - $current_run_length;
2219 }
2220  
2221 1409 $self->_js_sort_merge_force_collapse($sort_state);
2222 1409 return;
2223 }
2224  
2225 # Move all non-undefined elements into the work array and count the undefined
2226 # ones. V8 skips holes here; the Perl value model has none (ADR 0001).
2227 1432 ▶sub _js_sort_compact_receiver_elements_into_work_array {
Subroutine _js_sort_compact_receiver_elements_into_work_array: called CC=3 SCAR=11.0
2228 1432 my ( $self, $sort_state ) = @_;
2229 1432 my $receiver = $sort_state->{receiver};
2230 1432 my $receiver_length = $sort_state->{initial_receiver_length};
2231 1432 my $work_array = $sort_state->{work_array};
2232  
2233 1432 my $number_of_undefined = 0;
2234 1432 ▶ for ( my $i = 0; $i < $receiver_length; ++$i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $receiver_length) 128609 1432 130041
2235 128609 my $element = $receiver->[$i];
2236  
2237 128609 ▶ if ( !defined($element) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $element) { } 404 128205 128609
2238 404 $number_of_undefined++;
2239 } else {
2240 128205 push @$work_array, $element;
2241 }
2242 }
2243  
2244 1432 $sort_state->{sort_length} = $receiver_length;
2245 1432 $sort_state->{number_of_undefined} = $number_of_undefined;
2246  
2247 1432 return scalar @$work_array;
2248 }
2249  
2250 # Writing the elements back is a 3 step process:
2251 # 1. Copy the sorted elements from the workarray to the receiver.
2252 # 2. Add {nOfUndefined} undefineds to the receiver.
2253 # 3. Depending on the backing store either delete properties or set them to
2254 # the TheHole up to {sortState.sortLength}.
2255 # Without holes the first two steps reach sortLength, so the third has nothing
2256 # to do.
2257 1420 ▶sub _js_sort_copy_work_array_to_receiver {
Subroutine _js_sort_copy_work_array_to_receiver: called CC=3 SCAR=11.0
2258 1420 my ( $self, $sort_state, $number_of_non_undefined ) = @_;
2259 1420 my $receiver = $sort_state->{receiver};
2260 1420 my $work_array = $sort_state->{work_array};
2261  
2262 1420 my $index = 0;
2263 1420 ▶ for ( ; $index < $number_of_non_undefined; ++$index ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($index < $number_of_non_undefined) 128160 1420 129580
2264 128160 $receiver->[$index] = $work_array->[$index];
2265 }
2266  
2267 1420 my $number_of_undefined_end = $sort_state->{number_of_undefined} + $number_of_non_undefined;
2268 1420 ▶ for ( ; $index < $number_of_undefined_end; ++$index ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($index < $number_of_undefined_end) 404 1420 1824
2269 404 $receiver->[$index] = undef;
2270 }
2271 1420 return;
2272 }
2273  
2274 1432 ▶sub _js_array_tim_sort {
Subroutine _js_array_tim_sort: called CC=1 SCAR=0.0
2275 1432 my ( $self, $sort_state ) = @_;
2276 1432 my $number_of_non_undefined = $self->_js_sort_compact_receiver_elements_into_work_array($sort_state);
2277 1432 $self->_js_array_tim_sort_impl( $sort_state, $number_of_non_undefined );
2278  
2279 # The comparison function or toString might have changed the receiver; V8
2280 # then writes back through the generic accessor -- the same values.
2281 1420 $self->_js_sort_copy_work_array_to_receiver( $sort_state, $number_of_non_undefined );
2282 1420 return;
2283 }
2284  
2285 # ArrayPrototypeSort -- https://tc39.github.io/ecma262/#sec-array.prototype.sort
2286 # Sorts $arr in place and returns it; $comparefn undef is JS undefined.
2287 1582 ▶sub js_array_sort {
Subroutine js_array_sort: called CC=4 SCAR=13.9
Pod undocumented
2288 1582 my ( $self, $arr, $comparefn ) = @_;
2289  
2290 # 1. If comparefn is not undefined and IsCallable(comparefn) is false, throw
2291 # a TypeError exception. (V8 shows the value without side effects.)
2292 1582 ▶ if ( defined($comparefn) && !$self->is_function($comparefn) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $comparefn and not $self->is_function($comparefn)) 99 1483 1582
Condition100%3/3
defined $comparefn and not $self->is_function($comparefn)
!ll&&!rl&&r
70141399
MC/DC100%2/2
defined $comparefn and not $self->is_function($comparefn)
defined $comparefn not $self->is_function($comparefn)
Truth table100%3/3
A and not(B)
A= defined $comparefnB= not $self->is_function($comparefn)
ABresult
0X0
100
111
2293 99 die Text::Nunjucks::Lib::Error->new(
2294 'The comparison function must be either a function or undefined: '
2295 . $self->_runtime->_js_no_side_effects_to_string($comparefn),
2296 name => 'TypeError',
2297 );
2298 }
2299  
2300 # 2. Let obj be ? ToObject(this value).
2301 # 3. Let len be ? ToLength(? Get(obj, "length")).
2302 1483 my $len = scalar @$arr;
2303  
2304 1483 ▶ return $arr if $len < 2;
Branch: 1 branch
BranchTrueFalseTotal
if $len < 2 51 1432 1483
2305  
2306 1432 my $sort_state = $self->_js_sort_new_sort_state( $arr, $comparefn, $len );
2307 1432 $self->_js_array_tim_sort($sort_state);
2308  
2309 1420 return $arr;
2310 }
2311  
2312 #### js_json_stringify -- JSON.stringify(value, null, space)
2313  
2314 # Not a src/lib.js function: the dump filter's JSON.stringify(obj, null,
2315 # spaces) -- ECMAScript's SerializeJSONProperty, SerializeJSONObject,
2316 # SerializeJSONArray and QuoteJSONString over the value model, in their order
2317 # and names, with V8's message for a circular structure. The replacer is null
2318 # at the one call site, so it has no parameter. Returns undef where
2319 # JSON.stringify returns undefined (oracle: u|dump and a macro|dump render '').
2320 #
2321 # The gap is V8's (InitializeGap; oracle, dump(space)): a string's first ten
2322 # UTF-16 code units, an astral character two of them; a number above 0 its
2323 # integer part in spaces, at most ten (1.5 is one, 1/0 ten). V8 departs from
2324 # the spec below 1: a number in (0, 1) has a gap of no spaces that still
2325 # breaks the output into lines, "key": value included (oracle: dump(0.5) is
2326 # "[\n1\n]"). An empty string, a number not above 0 (NaN, -1) and anything
2327 # else -- a boolean, null, an array, an object, keyword arguments, a
2328 # SafeString (no primitive wrapper) -- give no gap.
2329 #
2330 # The values (oracle): undefined and a function serialize to undefined, so a
2331 # property holding one is left out and an array element becomes null; null,
2332 # true and false; a finite number its JS ToString (ADR 0007, -0 is 0), NaN and
2333 # +-Infinity null; a string quoted -- the control characters, '"' and '\'
2334 # escaped, each lone surrogate (ADR 0012) as \uXXXX, U+007F, U+2028, U+2029
2335 # and U+FEFF as they are. An array serializes its elements; any other object
2336 # its own enumerable properties, in keys' order (ADR 0011), each read as
2337 # _entries reads it: a SafeString is {"val": ..., "length": ...}, a regex {}
2338 # (its lastIndex is not enumerable). A callable toJSON member is called with
2339 # the key -- '' at the top, an index as its string -- and its result
2340 # serialized instead (oracle: {'toJSON': m} with a macro m dumps m's
2341 # SafeString output); no prototype the value model reaches has one.
2342 #
2343 # An object met again inside itself throws V8's TypeError, "Converting
2344 # circular structure to JSON" and the circle as V8 prints it (V8 13.6.233.17,
2345 # src/json/json-stringifier.cc: StackPush,
2346 # ConstructCircularStructureErrorMessage, CircularStructureMessageBuilder):
2347 # the object that starts the circle, at most two of the objects after it,
2348 # '...' when more are skipped, the last one, then the key that closes the
2349 # circle -- an index as "index N", a property as "property 'k'", the empty key
2350 # as <anonymous> (oracle). Only arrays and plain objects hold objects, so
2351 # every constructor named is 'Array' or 'Object'. Every join goes through
2352 # js_string_append (ADR 0012): a gap may hold lone surrogates.
2353  
2354 23 my %JS_JSON_ESCAPE = (
2355 "\x08" => '\b',
2356 "\t" => '\t',
2357 "\n" => '\n',
2358 "\f" => '\f',
2359 "\r" => '\r',
2360 '"' => '\"',
2361 '\\' => '\\\\',
2362 );
2363  
2364 # kCircularErrorMessagePrefixCount / kCircularErrorMessagePostfixCount
2365 23 my $JS_JSON_CIRCULAR_PREFIX_COUNT = 2;
2366 23 my $JS_JSON_CIRCULAR_POSTFIX_COUNT = 1;
2367  
2368 377 ▶sub js_json_stringify {
Subroutine js_json_stringify: called CC=6 SCAR=17.9
Pod undocumented
2369 377 my ( $self, $value, $space ) = @_;
2370 377 my $type = $self->_runtime->_js_type($space);
2371 # V8's gap_ is a string or none at all; has_gap is "gap_ != nullptr"
2372 377 my ( $gap, $has_gap ) = ( '', 0 );
2373 377 ▶ if ( $type eq 'string' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'string') { } 22 355 377
elsif ($type eq 'number') { } 44 311 355
2374 22 $gap = $self->js_substring( $space, 0, 10 );
2375 22 ▶ $has_gap = $gap ne '' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$gap ne '' ? : 19 3 22
2376 } elsif ( $type eq 'number' ) {
2377 44 ▶ my $value = $space > 10 ? 10 : $space; # std::min(value, 10.0); NaN fails both tests
Branch: 1 branch
BranchTrueFalseTotal
$space > 10 ? : 7 37 44
2378 44 ▶ if ( $value > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value > 0) 34 10 44
2379 34 $gap = ' ' x int($value); # DoubleToUint32
2380 34 $has_gap = 1;
2381 }
2382 }
2383  
2384 377 my $state = { stack => [], indent => '', gap => $gap, has_gap => $has_gap };
2385 # SerializeJSONProperty(state, '', wrapper) -- wrapper is { '': value }
2386 377 return $self->_js_json_serialize_property( $state, '', 0, $value );
2387 }
2388  
2389 # $key is the property key as a string; $is_index says it is an array index,
2390 # which V8's circle message prints differently. $value is Get(holder, key).
2391 2179 ▶sub _js_json_serialize_property {
Subroutine _js_json_serialize_property: called CC=16 SCAR=27.7
2392 2179 my ( $self, $state, $key, $is_index, $value ) = @_;
2393 2179 my $rt = $self->_runtime;
2394  
2395 # 2. If value is an Object, let toJSON be ? GetV(value, "toJSON"); if it is
2396 # callable, value = ? Call(toJSON, value, << key >>) -- no this (ADR 0009)
2397 2179 ▶ if ( ref($value) && !$rt->_is_none($value) && !$self->is_function($value) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value and not $rt->_is_none($value) and not $self->is_function($value)) 881 1298 2179
Condition100%6/6
ref $value and not $rt->_is_none($value) and not $self->is_function($value)
!ll&&!rl&&r
128117881
ref $value and not $rt->_is_none($value)
!ll&&!rl&&r
125328898
MC/DC100%3/3
ref $value and not $rt->_is_none($value) and not $self->is_function($value)
ref $value not $rt->_is_none($value) not $self->is_function($value)
Truth table100%4/4
A and not(B) and not(C)
A= ref $valueB= not $rt->_is_none($value)C= not $self->is_function($value)
ABCresult
0XX0
10X0
1100
1111
2398 881 my $to_json = $rt->member_lookup( $value, 'toJSON' );
2399 881 ▶ $value = $to_json->($key) if $self->is_function($to_json);
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_function($to_json) 6 875 881
2400 }
2401  
2402 2179 ▶ return undef if !defined($value) || $self->is_function($value);
Branch: 1 branch
BranchTrueFalseTotal
if not defined $value or $self->is_function($value) 52 2127 2179
Condition100%3/3
not defined $value or $self->is_function($value)
l!l&&r!l&&!r
35172127
MC/DC100%2/2
not defined $value or $self->is_function($value)
not defined $value $self->is_function($value)
Truth table100%3/3
not(A) or B
A= not defined $valueB= $self->is_function($value)
ABresult
1X1
011
000
2403 2127 ▶ return 'null' if $rt->_is_none($value);
Branch: 1 branch
BranchTrueFalseTotal
if $rt->_is_none($value) 28 2099 2127
2404 2099 ▶ return ( $value ? 'true' : 'false' ) if is_bool($value);
Branch: 2 branches
BranchTrueFalseTotal
if builtin::is_bool($value) 36 2063 2099
$value ? : 22 14 36
2405 2063 ▶ return $self->_js_json_quote($value) if $self->is_string($value);
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_string($value) 426 1637 2063
2406 1637 ▶ if ( created_as_number($value) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (created_as_number $value) 759 878 1637
2407 759 ▶ return 'null' if $value != $value || $value == $NUM_POS_INF || $value == $NUM_NEG_INF;
Branch: 1 branch
BranchTrueFalseTotal
if $value != $value or $value == $NUM_POS_INF or $value == $NUM_NEG_INF 21 738 759
Condition100%6/6
$value != $value or $value == $NUM_POS_INF or $value == $NUM_NEG_INF
l!l&&r!l&&!r
174738
$value != $value or $value == $NUM_POS_INF
l!l&&r!l&&!r
125742
MC/DC100%3/3
$value != $value or $value == $NUM_POS_INF or $value == $NUM_NEG_INF
$value != $value $value == $NUM_POS_INF $value == $NUM_NEG_INF
Truth table100%4/4
A or B or C
A= $value != $valueB= $value == $NUM_POS_INFC= $value == $NUM_NEG_INF
ABCresult
1XX1
01X1
0011
0000
2408 738 return $self->number_to_string($value);
2409 }
2410 878 ▶ return $self->_js_json_serialize_array( $state, $key, $is_index, $value ) if ref($value) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $value eq "ARRAY" 665 213 878
2411 213 return $self->_js_json_serialize_object( $state, $key, $is_index, $value );
2412 }
2413  
2414 690 ▶sub _js_json_quote {
Subroutine _js_json_quote: called CC=2 SCAR=6.9
2415 690 my ( $self, $s ) = @_;
2416 # A caller string spelling a pair as two surrogate characters is re-paired
2417 # first, so both spellings quote alike (ADR 0012); every surrogate character
2418 # left is a lone one and comes out escaped, so the quotes cannot pair with
2419 # anything.
2420 690 $s = $self->_js_from_units($s);
2421 690 ▶ return '"' . ( $s =~ s{([\x{0}-\x{1F}"\\\x{D800}-\x{DFFF}])}{ $JS_JSON_ESCAPE{$1} // sprintf( '\\u%04x', ord $1 ) }ger ) . '"';
Condition100%2/2
$JS_JSON_ESCAPE{$1} // sprintf("\\u%04x", ord $1)
l!l
3024
MC/DC100%1/1
$JS_JSON_ESCAPE{$1} // sprintf("\\u%04x", ord $1)
$JS_JSON_ESCAPE{$1}
Truth table100%2/2
A
A= $JS_JSON_ESCAPE{$1}
Aresult
11
00
2422 }
2423  
2424 213 ▶sub _js_json_serialize_object {
Subroutine _js_json_serialize_object: called CC=4 SCAR=13.9
2425 213 my ( $self, $state, $key, $is_index, $value ) = @_;
2426 213 $self->_js_json_stack_push( $state, $key, $is_index, $value );
2427 207 my $stepback = $state->{indent};
2428 207 $self->js_string_append( $state->{indent}, $state->{gap} );
2429  
2430 207 my @partial;
2431 207 for my $p ( @{ $self->keys($value) } ) {
2432 297 my $str_p = $self->_js_json_serialize_property( $state, $p, 0, $self->_own_value( $value, $p ) );
2433 279 ▶ next unless defined $str_p;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str_p 15 264 279
2434 264 my $member = $self->_js_json_quote($p) . ':';
2435 264 ▶ $member .= ' ' if $state->{has_gap};
Branch: 1 branch
BranchTrueFalseTotal
if $state->{"has_gap"} 76 188 264
2436 264 $self->js_string_append( $member, $str_p );
2437 264 push @partial, $member;
2438 }
2439  
2440 189 my $final = $self->_js_json_final( $state, '{', '}', \@partial, $stepback );
2441 189 pop @{ $state->{stack} };
2442 189 $state->{indent} = $stepback;
2443 189 return $final;
2444 }
2445  
2446 665 ▶sub _js_json_serialize_array {
Subroutine _js_json_serialize_array: called CC=3 SCAR=11.0
2447 665 my ( $self, $state, $key, $is_index, $value ) = @_;
2448 665 $self->_js_json_stack_push( $state, $key, $is_index, $value );
2449 657 my $stepback = $state->{indent};
2450 657 $self->js_string_append( $state->{indent}, $state->{gap} );
2451  
2452 657 my @partial;
2453 657 my $len = scalar @$value;
2454 657 for my $index ( 0 .. $len - 1 ) {
2455 1505 my $str_p = $self->_js_json_serialize_property( $state, "$index", 1, $value->[$index] );
2456 1478 ▶ push @partial, defined($str_p) ? $str_p : 'null';
Branch: 1 branch
BranchTrueFalseTotal
defined $str_p ? : 1449 29 1478
2457 }
2458  
2459 630 my $final = $self->_js_json_final( $state, '[', ']', \@partial, $stepback );
2460 630 pop @{ $state->{stack} };
2461 630 $state->{indent} = $stepback;
2462 630 return $final;
2463 }
2464  
2465 # The final string SerializeJSONObject and SerializeJSONArray both build.
2466 819 ▶sub _js_json_final {
Subroutine _js_json_final: called CC=6 SCAR=17.9
2467 819 my ( $self, $state, $open, $close, $partial, $stepback ) = @_;
2468 819 ▶ return $open . $close unless @$partial;
Branch: 1 branch
BranchTrueFalseTotal
unless @$partial 87 732 819
2469 732 my $separator = ',';
2470 732 my $final = $open;
2471 732 ▶ if ( $state->{has_gap} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($state->{"has_gap"}) 96 636 732
2472 96 $separator = ",\n";
2473 96 $self->js_string_append( $separator, $state->{indent} );
2474 96 $self->js_string_append( $final, "\n" );
2475 96 $self->js_string_append( $final, $state->{indent} );
2476 }
2477 732 for my $i ( 0 .. $#$partial ) {
2478 1736 ▶ $self->js_string_append( $final, $separator ) if $i > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $i > 0 1004 732 1736
2479 1736 $self->js_string_append( $final, $partial->[$i] );
2480 }
2481 732 ▶ if ( $state->{has_gap} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($state->{"has_gap"}) 96 636 732
2482 96 $self->js_string_append( $final, "\n" );
2483 96 $self->js_string_append( $final, $stepback );
2484 }
2485 732 $self->js_string_append( $final, $close );
2486 732 return $final;
2487 }
2488  
2489 # If state.[[Stack]] contains value, throw a TypeError; else append it.
2490 878 ▶sub _js_json_stack_push {
Subroutine _js_json_stack_push: called CC=3 SCAR=11.0
2491 878 my ( $self, $state, $key, $is_index, $value ) = @_;
2492 878 my $stack = $state->{stack};
2493 878 for my $i ( 0 .. $#$stack ) {
2494 661 ▶ die $self->_js_json_circular_error( $stack, $key, $is_index, $i ) if refaddr( $stack->[$i][2] ) == refaddr($value);
Branch: 1 branch
BranchTrueFalseTotal
if builtin::refaddr($stack->[$i][2]) == builtin::refaddr($value) 14 647 661
2495 }
2496 864 push @$stack, [ $key, $is_index, $value ];
2497 864 return;
2498 }
2499  
2500 14 ▶sub _js_json_circular_error {
Subroutine _js_json_circular_error: called CC=6 SCAR=17.9
2501 14 my ( $self, $stack, $last_key, $last_is_index, $start_index ) = @_;
2502 14 my $index = $start_index;
2503 14 my $stack_size = scalar @$stack;
2504  
2505 14 my $message = 'Converting circular structure to JSON';
2506 14 $self->js_string_append( $message,
2507 "\n --> starting at object with constructor " . $self->_js_json_constructor_name( $stack->[ $index++ ][2] ) );
2508  
2509 # Append a maximum of kCircularErrorMessagePrefixCount normal lines.
2510 14 my $prefix_end = $index + $JS_JSON_CIRCULAR_PREFIX_COUNT;
2511 14 ▶ $prefix_end = $stack_size if $stack_size < $prefix_end;
Branch: 1 branch
BranchTrueFalseTotal
if $stack_size < $prefix_end 8 6 14
2512 14 ▶ for ( ; $index < $prefix_end; ++$index ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($index < $prefix_end) 17 14 31
2513 17 $self->_js_json_circular_normal_line( $message, $stack->[$index] );
2514 }
2515  
2516 # If the circle consists of too many objects, we skip them and just print
2517 # an ellipsis.
2518 14 ▶ $self->js_string_append( $message, "\n | ..." ) if $stack_size > $index + $JS_JSON_CIRCULAR_POSTFIX_COUNT;
Branch: 1 branch
BranchTrueFalseTotal
if $stack_size > $index + $JS_JSON_CIRCULAR_POSTFIX_COUNT 4 10 14
2519  
2520 # The postfix lines count from the back of the stack; none is printed twice.
2521 14 my $postfix_start = $stack_size - $JS_JSON_CIRCULAR_POSTFIX_COUNT;
2522 14 ▶ $index = $postfix_start if $index < $postfix_start;
Branch: 1 branch
BranchTrueFalseTotal
if $index < $postfix_start 4 10 14
2523 14 ▶ for ( ; $index < $stack_size; ++$index ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($index < $stack_size) 6 14 20
2524 6 $self->_js_json_circular_normal_line( $message, $stack->[$index] );
2525 }
2526  
2527 14 $self->js_string_append( $message, "\n --- " );
2528 14 $self->js_string_append( $message, $self->_js_json_circular_key( $last_key, $last_is_index ) );
2529 14 $self->js_string_append( $message, ' closes the circle' );
2530 14 return Text::Nunjucks::Lib::Error->new( $message, name => 'TypeError' );
2531 }
2532  
2533 # Appends to the caller's message ($_[1], aliased).
2534 23 ▶sub _js_json_circular_normal_line {
Subroutine _js_json_circular_normal_line: called CC=1 SCAR=0.0
2535 23 my ( $self, undef, $entry ) = @_;
2536 23 $self->js_string_append( $_[1], "\n | " );
2537 23 $self->js_string_append( $_[1], $self->_js_json_circular_key( $entry->[0], $entry->[1] ) );
2538 23 $self->js_string_append( $_[1], ' -> object with constructor ' . $self->_js_json_constructor_name( $entry->[2] ) );
2539 23 return;
2540 }
2541  
2542 37 ▶sub _js_json_circular_key {
Subroutine _js_json_circular_key: called CC=3 SCAR=11.0
2543 37 my ( $self, $key, $is_index ) = @_;
2544 37 ▶ return 'index ' . $key if $is_index;
Branch: 1 branch
BranchTrueFalseTotal
if $is_index 23 14 37
2545 14 ▶ return '<anonymous>' if $key eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "" 4 10 14
2546 10 my $text = "property '";
2547 10 $self->js_string_append( $text, $key );
2548 10 $self->js_string_append( $text, "'" );
2549 10 return $text;
2550 }
2551  
2552 37 ▶sub _js_json_constructor_name {
Subroutine _js_json_constructor_name: called CC=2 SCAR=6.9
2553 37 my ( $self, $object ) = @_;
2554 37 ▶ return ref($object) eq 'ARRAY' ? "'Array'" : "'Object'";
Branch: 1 branch
BranchTrueFalseTotal
ref $object eq 'ARRAY' ? : 25 12 37
2555 }
2556  
2557 #### node built-ins -- path, fs, console (ADR 0018)
2558  
2559 # Not src/lib.js functions: the one home of the node built-ins the loaders call
2560 # -- src/loader.js's path.resolve / path.dirname, src/node-loaders.js's
2561 # path.normalize, path.resolve, fs.existsSync, fs.readFileSync(p, 'utf-8') and
2562 # console.log -- next to the JS built-ins above. As the oracle's node
2563 # (v24.19.0) has them, posix flavour: the separator is '/' and only '/', a
2564 # backslash is an ordinary character (ADR 0018). Source: node's lib/path.js as
2565 # that node reports it (posix.resolve / normalize / dirname and
2566 # normalizeString), pinned by t/data/node-builtins.json
2567 # (maint/node-builtins-fixtures). The path functions are lexical -- '..' and
2568 # '.' collapse on the string, the file system is never asked, symlinks stay as
2569 # they are -- and only resolve reads the process's working directory. Each
2570 # checks its arguments first, as node's do (_node_validate_string): anything
2571 # but a string throws node's ERR_INVALID_ARG_TYPE, a TypeError -- a search path
2572 # is whatever the caller passed FileSystemLoader.
2573  
2574 # process.cwd() -- the working directory as the system reports it (getcwd(3),
2575 # as libuv's uv_cwd), physical, no trailing '/'.
2576 331 ▶sub node_process_cwd { return Cwd::getcwd() }
Subroutine node_process_cwd: called CC=1 SCAR=0.0
Pod undocumented
2577  
2578 # path.resolve(...args) -- the shortcut compares strictly (===), so only a
2579 # string is the cwd there; the loop validates each argument it reaches, from
2580 # the last one back to the first absolute one (node: resolve(5, '/a') is '/a').
2581 1175 ▶sub node_path_resolve {
Subroutine node_path_resolve: called CC=14 SCAR=26.6
Pod undocumented
2582 1175 my ( $self, @args ) = @_;
2583 1175 ▶ if ( @args == 0 || ( @args == 1 && ( $self->_strict_eq( $args[0], '' ) || $self->_strict_eq( $args[0], '.' ) ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args == 0 or @args == 1 and $self->_strict_eq($args[0], "") || $self->_strict_eq($args[0], ".")) 39 1136 1175
Condition100%9/9
@args == 0 or @args == 1 and $self->_strict_eq($args[0], "") || $self->_strict_eq($args[0], ".")
l!l&&r!l&&!r
1381136
@args == 1 and $self->_strict_eq($args[0], "") || $self->_strict_eq($args[0], ".")
!ll&&!rl&&r
76037638
$self->_strict_eq($args[0], "") or $self->_strict_eq($args[0], ".")
l!l&&r!l&&!r
2513376
MC/DC100%4/4
@args == 0 or @args == 1 and $self->_strict_eq($args[0], "") || $self->_strict_eq($args[0], ".")
@args == 0 @args == 1 $self->_strict_eq($args[0], "") $self->_strict_eq($args[0], ".")
Truth table100%5/5
A or B and C or D
A= @args == 0B= @args == 1C= $self->_strict_eq($args[0], "")D= $self->_strict_eq($args[0], ".")
ABCDresult
1XXX1
011X1
01011
00XX0
01000
2584 39 my $cwd = $self->node_process_cwd;
2585 39 ▶ if ( substr( $cwd, 0, 1 ) eq '/' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($cwd, 0, 1) eq "/") 39 0 39
2586 39 return $cwd;
2587 }
2588 }
2589 1136 my $resolved_path = '';
2590 1136 my $resolved_absolute = 0;
2591  
2592 1136 ▶ for ( my $i = $#args; $i >= 0 && !$resolved_absolute; $i-- ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i >= 0 and not $resolved_absolute) 1658 1043 2701
Condition100%3/3
$i >= 0 and not $resolved_absolute
!ll&&!rl&&r
7343091658
MC/DC100%2/2
$i >= 0 and not $resolved_absolute
$i >= 0 not $resolved_absolute
Truth table100%3/3
A and not(B)
A= $i >= 0B= not $resolved_absolute
ABresult
0X0
100
111
2593 1658 my $path = $args[$i];
2594 1658 $self->_node_validate_string( $path, 'paths[' . $i . ']' );
2595  
2596 # Skip empty entries
2597 1565 ▶ if ( length($path) == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $path == 0) 70 1495 1565
2598 70 next;
2599 }
2600  
2601 1495 $resolved_path = $path . '/' . $resolved_path;
2602 1495 ▶ $resolved_absolute = substr( $path, 0, 1 ) eq '/' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
substr($path, 0, 1) eq '/' ? : 751 744 1495
2603 }
2604  
2605 1043 ▶ if ( !$resolved_absolute ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($resolved_absolute) 292 751 1043
2606 292 my $cwd = $self->node_process_cwd;
2607 292 $resolved_path = $cwd . '/' . $resolved_path;
2608 292 ▶ $resolved_absolute = substr( $cwd, 0, 1 ) eq '/' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
substr($cwd, 0, 1) eq '/' ? : 292 0 292
2609 }
2610  
2611 # At this point the path should be resolved to a full absolute path, but
2612 # handle relative paths to be safe (might happen when process.cwd() fails)
2613  
2614 # Normalize the path
2615 1043 $resolved_path = $self->_node_normalize_string( $resolved_path, !$resolved_absolute );
2616  
2617 1043 ▶ if ($resolved_absolute) {
Branch: 1 branch
BranchTrueFalseTotal
if ($resolved_absolute) 1043 0 1043
2618 1043 return '/' . $resolved_path;
2619 }
2620 0 ▶ return length($resolved_path) > 0 ? $resolved_path : '.';
Branch: 1 branch
BranchTrueFalseTotal
length $resolved_path > 0 ? : 0 0 0
2621 }
2622  
2623 # path.normalize(path)
2624 769 ▶sub node_path_normalize {
Subroutine node_path_normalize: called CC=7 SCAR=19.5
Pod undocumented
2625 769 my ( $self, $path ) = @_;
2626 769 $self->_node_validate_string( $path, 'path' );
2627  
2628 728 ▶ return '.' if length($path) == 0;
Branch: 1 branch
BranchTrueFalseTotal
if length $path == 0 53 675 728
2629  
2630 675 my $is_absolute = substr( $path, 0, 1 ) eq '/';
2631 675 my $trailing_separator = substr( $path, -1 ) eq '/';
2632  
2633 # Normalize the path
2634 675 $path = $self->_node_normalize_string( $path, !$is_absolute );
2635  
2636 675 ▶ if ( length($path) == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $path == 0) 61 614 675
2637 61 ▶ return '/' if $is_absolute;
Branch: 1 branch
BranchTrueFalseTotal
if $is_absolute 44 17 61
2638 17 ▶ return $trailing_separator ? './' : '.';
Branch: 1 branch
BranchTrueFalseTotal
$trailing_separator ? : 3 14 17
2639 }
2640 614 ▶ $path .= '/' if $trailing_separator;
Branch: 1 branch
BranchTrueFalseTotal
if $trailing_separator 176 438 614
2641  
2642 614 ▶ return $is_absolute ? '/' . $path : $path;
Branch: 1 branch
BranchTrueFalseTotal
$is_absolute ? : 238 376 614
2643 }
2644  
2645 # path.dirname(path)
2646 761 ▶sub node_path_dirname {
Subroutine node_path_dirname: called CC=9 SCAR=22.0
Pod undocumented
2647 761 my ( $self, $path ) = @_;
2648 761 $self->_node_validate_string( $path, 'path' );
2649 730 ▶ return '.' if length($path) == 0;
Branch: 1 branch
BranchTrueFalseTotal
if length $path == 0 53 677 730
2650 677 my $has_root = substr( $path, 0, 1 ) eq '/';
2651 677 my $end = -1;
2652 677 my $matched_slash = 1;
2653 677 ▶ for ( my $i = length($path) - 1; $i >= 1; --$i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i >= 1) 2985 143 3128
2654 2985 ▶ if ( substr( $path, $i, 1 ) eq '/' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($path, $i, 1) eq '/') { } 846 2139 2985
2655 846 ▶ if ( !$matched_slash ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($matched_slash) 534 312 846
2656 534 $end = $i;
2657 534 last;
2658 }
2659 }
2660 else {
2661 # We saw the first non-path separator
2662 2139 $matched_slash = 0;
2663 }
2664 }
2665  
2666 677 ▶ return $has_root ? '/' : '.' if $end == -1;
Branch: 2 branches
BranchTrueFalseTotal
if $end == -1 143 534 677
$has_root ? : 72 71 143
2667 534 ▶ return '//' if $has_root && $end == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $has_root and $end == 1 9 525 534
Condition100%3/3
$has_root and $end == 1
!ll&&!rl&&r
2472789
MC/DC100%2/2
$has_root and $end == 1
$has_root $end == 1
Truth table100%3/3
A and B
A= $has_rootB= $end == 1
ABresult
0X0
100
111
2668 525 return substr( $path, 0, $end );
2669 }
2670  
2671 # normalizeString(path, allowAboveRoot, separator, isPathSeparator) -- the
2672 # posix call, separator '/' and isPosixPathSeparator, fixed. Resolves . and ..
2673 # elements in a path with directory names. Counts characters where node counts
2674 # UTF-16 code units: the counts only ever measure the segments between two
2675 # separators, and a surrogate is never a '/' or a '.', so both cut the same.
2676 1718 ▶sub _node_normalize_string {
Subroutine _node_normalize_string: called CC=20 SCAR=30.0
2677 1718 my ( $self, $path, $allow_above_root ) = @_;
2678 1718 my $res = '';
2679 1718 my $last_segment_length = 0;
2680 1718 my $last_slash = -1;
2681 1718 my $dots = 0;
2682 1718 my $code = '';
2683 1718 ▶ for ( my $i = 0; $i <= length($path); ++$i ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i <= length $path) 45189 458 45647
2684 45189 ▶ if ( $i < length($path) ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($i < length $path) { } 43471 1718 45189
elsif ($code eq '/') { } 1260 458 1718
2685 43471 $code = substr( $path, $i, 1 );
2686 }
2687 elsif ( $code eq '/' ) {
2688 1260 last;
2689 }
2690 else {
2691 458 $code = '/';
2692 }
2693  
2694 43929 ▶ if ( $code eq '/' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($code eq '/') { } 11090 32839 43929
elsif ($code eq '.' and $dots != -1) { } 2919 29920 32839
2695 11090 ▶ if ( $last_slash == $i - 1 || $dots == 1 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($last_slash == $i - 1 or $dots == 1) { } 4082 7008 11090
elsif ($dots == 2) { } 289 6719 7008
Condition100%3/3
$last_slash == $i - 1 or $dots == 1
l!l&&r!l&&!r
38712117008
MC/DC100%2/2
$last_slash == $i - 1 or $dots == 1
$last_slash == $i - 1 $dots == 1
Truth table100%3/3
A or B
A= $last_slash == $i - 1B= $dots == 1
ABresult
1X1
011
000
2696 # NOOP
2697 }
2698 elsif ( $dots == 2 ) {
2699 289 ▶ if ( length($res) < 2
Branch: 1 branch
BranchTrueFalseTotal
if (length $res < 2 or $last_segment_length != 2 or substr($res, -1, 1) ne "." or substr($res, -2, 1) ne ".") 289 0 289
Condition88%8/9
length $res < 2 or $last_segment_length != 2 or substr($res, -1, 1) ne "." or substr($res, -2, 1) ne "."
l!l&&r!l&&!r
279100
length $res < 2 or $last_segment_length != 2 or substr($res, -1, 1) ne "."
l!l&&r!l&&!r
2502910
length $res < 2 or $last_segment_length != 2
l!l&&r!l&&!r
9115939
MC/DC0%0/4
length $res < 2 or $last_segment_length != 2 or substr($res, -1, 1) ne "." or substr($res, -2, 1) ne "."
length $res < 2 $last_segment_length != 2 substr($res, -1, 1) ne "." substr($res, -2, 1) ne "."
Truth table80%4/5
A or B or C or D
A= length $res < 2B= $last_segment_length != 2C= substr($res, -1, 1) ne "."D= substr($res, -2, 1) ne "."
ABCDresult
1XXX1
01XX1
001X1
00011
00000
2700 || $last_segment_length != 2
2701 || substr( $res, -1, 1 ) ne '.'
2702 || substr( $res, -2, 1 ) ne '.' )
2703 {
2704 289 ▶ if ( length($res) > 2 ) {
Branch: 2 branches
BranchTrueFalseTotal
if (length $res > 2) { } 184 105 289
elsif (length $res != 0) { } 36 69 105
2705 184 my $last_slash_index = length($res) - $last_segment_length - 1;
2706 184 ▶ if ( $last_slash_index == -1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($last_slash_index == -1) { } 25 159 184
2707 25 $res = '';
2708 25 $last_segment_length = 0;
2709 }
2710 else {
2711 159 $res = substr( $res, 0, $last_slash_index );
2712 159 $last_segment_length = length($res) - 1 - rindex( $res, '/' );
2713 }
2714 184 $last_slash = $i;
2715 184 $dots = 0;
2716 184 next;
2717 }
2718 elsif ( length($res) != 0 ) {
2719 36 $res = '';
2720 36 $last_segment_length = 0;
2721 36 $last_slash = $i;
2722 36 $dots = 0;
2723 36 next;
2724 }
2725 }
2726 69 ▶ if ($allow_above_root) {
Branch: 1 branch
BranchTrueFalseTotal
if ($allow_above_root) 28 41 69
2727 28 ▶ $res .= length($res) > 0 ? '/..' : '..';
Branch: 1 branch
BranchTrueFalseTotal
length $res > 0 ? : 0 28 28
2728 28 $last_segment_length = 2;
2729 }
2730 }
2731 else {
2732 6719 ▶ if ( length($res) > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $res > 0) { } 5120 1599 6719
2733 5120 $res .= '/' . substr( $path, $last_slash + 1, $i - $last_slash - 1 );
2734 }
2735 else {
2736 1599 $res = substr( $path, $last_slash + 1, $i - $last_slash - 1 );
2737 }
2738 6719 $last_segment_length = $i - $last_slash - 1;
2739 }
2740 10870 $last_slash = $i;
2741 10870 $dots = 0;
2742 }
2743 ▶ elsif ( $code eq '.' && $dots != -1 ) {
Condition100%3/3
$code eq "." and $dots != -1
!ll&&!rl&&r
2849014302919
MC/DC100%2/2
$code eq "." and $dots != -1
$code eq "." $dots != -1
Truth table100%3/3
A and B
A= $code eq "."B= $dots != -1
ABresult
0X0
100
111
2744 2919 ++$dots;
2745 }
2746 else {
2747 29920 $dots = -1;
2748 }
2749 }
2750 1718 return $res;
2751 }
2752  
2753 # validateString(value, name) -- node's lib/internal/validators.js: anything
2754 # but a string throws ERR_INVALID_ARG_TYPE(name, 'string', value), a TypeError
2755 # (Lib::Error, ADR 0010) whose message lib/internal/errors.js builds. Only the
2756 # shape the path functions' names take is ported: 'path' and 'paths[i]' end
2757 # in no ' argument' and hold no '.', so node writes `The "<name>" argument`.
2758 # Measured in node: `The "path" argument must be of type string. Received
2759 # null`, `The "paths[1]" argument ... Received type number (5)`.
2760 3188 ▶sub _node_validate_string {
Subroutine _node_validate_string: called CC=2 SCAR=6.9
2761 3188 my ( $self, $value, $name ) = @_;
2762 3188 ▶ return if $self->is_string($value);
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_string($value) 3023 165 3188
2763 165 die Text::Nunjucks::Lib::Error->new(
2764 'The "' . $name . '" argument must be of type string. Received ' . $self->_node_determine_specific_type($value),
2765 name => 'TypeError',
2766 );
2767 }
2768  
2769 # determineSpecificType(value) -- how node's ERR_INVALID_ARG_TYPE shows the
2770 # value it got, over the kinds the port models (none is a string here, and
2771 # bigint and symbol have no Perl image). Measured in node: null, undefined,
2772 # 'type number (5)', '(-0)', '(NaN)', '(Infinity)', '(1e+21)', 'type boolean
2773 # (true)', 'function <name>' -- a Perl coderef has no name (k88), so
2774 # 'function ', as an anonymous JS function. An object shows its constructor's
2775 # name: an array 'an instance of Array', a regex 'RegExp', a SafeString
2776 # 'String' (SafeString.prototype has no constructor of its own, String's is
2777 # inherited), a dict, caller hash or keyword arguments 'Object'. A plain
2778 # object with an own 'constructor' member is shown through that member, as
2779 # node reads value.constructor: a function by its name (a coderef's is '',
2780 # where JS names a function written as a member after it: 'an instance of
2781 # constructor'), an object by its own 'name' ({'constructor': {'name':
2782 # 'Foo'}} -> 'an instance of Foo'); anything
2783 # else falsy or nameless is util.inspect(value, { depth: -1 }), '[Object]';
2784 # a truthy primitive cannot be searched with `in` and V8 throws ("Cannot use
2785 # 'in' operator to search for 'name' in 1"). Any other blessed object is a
2786 # plain object to the port (ADR 0016): 'an instance of Object', the port's
2787 # choice -- it has no JS counterpart to measure.
2788 165 ▶sub _node_determine_specific_type {
Subroutine _node_determine_specific_type: called CC=21 SCAR=30.4
2789 165 my ( $self, $value ) = @_;
2790 165 my $rt = $self->_runtime;
2791 165 ▶ if ( $rt->_is_none($value) ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($rt->_is_none($value)) { } 6 159 165
elsif (not defined $value) { } 6 153 159
2792 6 return 'null';
2793 }
2794 elsif ( !defined($value) ) {
2795 6 return 'undefined';
2796 }
2797  
2798 153 ▶ my $type = $self->is_function($value) ? 'function' : $rt->_js_type($value);
Branch: 1 branch
BranchTrueFalseTotal
$self->is_function($value) ? : 6 147 153
2799  
2800 153 ▶ if ( $type eq 'number' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "number") 42 111 153
2801 42 ▶ if ( $value == 0 ) {
Branch: 4 branches
BranchTrueFalseTotal
if ($value == 0) { } 10 32 42
elsif ($value != $value) { } 5 27 32
elsif ($value == $NUM_POS_INF) { } 5 22 27
elsif ($value == $NUM_NEG_INF) { } 5 17 22
2802 10 ▶ return $rt->op_div( 1, $value ) == $NUM_NEG_INF ? 'type number (-0)' : 'type number (0)';
Branch: 1 branch
BranchTrueFalseTotal
$rt->op_div(1, $value) == $NUM_NEG_INF ? : 5 5 10
2803 }
2804 elsif ( $value != $value ) {
2805 5 return 'type number (NaN)';
2806 }
2807 elsif ( $value == $NUM_POS_INF ) {
2808 5 return 'type number (Infinity)';
2809 }
2810 elsif ( $value == $NUM_NEG_INF ) {
2811 5 return 'type number (-Infinity)';
2812 }
2813 17 return 'type number (' . $self->number_to_string($value) . ')';
2814 }
2815 111 ▶ if ( $type eq 'boolean' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "boolean") 11 100 111
2816 11 ▶ return $value ? 'type boolean (true)' : 'type boolean (false)';
Branch: 1 branch
BranchTrueFalseTotal
$value ? : 6 5 11
2817 }
2818 100 ▶ if ( $type eq 'function' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "function") 6 94 100
2819 6 return 'function ' . $rt->_js_function_name($value);
2820 }
2821  
2822 # 'object': value.constructor && 'name' in value.constructor
2823 94 ▶ return 'an instance of Array' if $self->is_array($value);
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_array($value) 11 83 94
2824 83 ▶ return 'an instance of RegExp' if $rt->_is_regex($value);
Branch: 1 branch
BranchTrueFalseTotal
if $rt->_is_regex($value) 5 78 83
2825 78 ▶ return 'an instance of String' if $rt->_is_safe_string($value);
Branch: 1 branch
BranchTrueFalseTotal
if $rt->_is_safe_string($value) 5 73 78
2826 73 ▶ return 'an instance of Object' unless $self->has_own_prop( $value, 'constructor' );
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_own_prop($value, "constructor") 17 56 73
2827 56 my $ctor = $self->_own_value( $value, 'constructor' );
2828 56 ▶ if ( $rt->_truthy($ctor) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rt->_truthy($ctor)) 41 15 56
2829 41 ▶ die Text::Nunjucks::Lib::Error->new(
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ctor 16 25 41
2830 "Cannot use 'in' operator to search for 'name' in " . $rt->_js_to_string($ctor),
2831 name => 'TypeError',
2832 ) unless ref($ctor);
2833 25 ▶ return 'an instance of ' . $rt->_js_function_name($ctor) if $self->is_function($ctor);
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_function($ctor) 0 25 25
2834 25 ▶ return 'an instance of ' . $rt->_js_to_string( $rt->member_lookup( $ctor, 'name' ) )
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_own_prop($ctor, "name") 15 10 25
2835 if $self->has_own_prop( $ctor, 'name' );
2836 }
2837 25 return '[Object]';
2838 }
2839  
2840 # fs.existsSync(path) -- true if the path exists, a directory as well; false,
2841 # never an exception, for anything node cannot look up (a name with a NUL is
2842 # an invalid argument to node, and so false). node hands the system the
2843 # path's UTF-8 bytes, whatever its characters; so does this.
2844 169 ▶sub node_fs_exists_sync {
Subroutine node_fs_exists_sync: called CC=3 SCAR=11.0
Pod undocumented
2845 169 my ( $self, $path ) = @_;
2846 169 ▶ return 0 if index( $path, "\0" ) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($path, "\0") != -1 1 168 169
2847 168 my $bytes = $self->_node_fs_path_bytes($path);
2848 168 ▶ return -e $bytes ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
-e $bytes ? : 130 38 168
2849 }
2850  
2851 # fs.readFileSync(path, 'utf-8') -- the file's bytes, decoded as node decodes
2852 # UTF-8 (_node_utf8_decode: a BOM stays a U+FEFF, malformed bytes become
2853 # U+FFFD), per ADR 0012's I/O contract. A failure throws node's error, an
2854 # Error whose message is libuv's '<CODE>: <description>, <syscall>' -- the
2855 # path, as given, follows an open: "EISDIR: illegal operation on a directory,
2856 # read" for a directory, "EACCES: permission denied, open '<path>'" for a file
2857 # that cannot be read, "ENOENT: no such file or directory, open '<path>'" for
2858 # a dangling symlink (measured in node). A plain open and read, as node's
2859 # open(2) and read(2), not Path::Tiny: its slurp takes flock(LOCK_SH) first,
2860 # which blocks while another process holds LOCK_EX (node reads at once) and
2861 # fails where flock is not supported. Each failure is that syscall's errno.
2862 133 ▶sub node_fs_read_file_sync_utf8 {
Subroutine node_fs_read_file_sync_utf8: called CC=4 SCAR=13.9
Pod undocumented
2863 133 my ( $self, $path ) = @_;
2864 133 ▶ open( my $fh, '<:raw', $self->_node_fs_path_bytes($path) )
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $self->_node_fs_path_bytes($path) or die $self->_node_uv_exception($! + 0, "open", $path) 131 2 133
2865 or die $self->_node_uv_exception( $! + 0, 'open', $path );
2866 131 my $bytes = '';
2867 131 while (1) {
2868 258 my $n = read( $fh, $bytes, 65536, length($bytes) );
2869 258 ▶ die $self->_node_uv_exception( $! + 0, 'read' ) unless defined $n;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n 4 254 258
2870 254 ▶ last if $n == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $n == 0 127 127 254
2871 }
2872 127 close($fh);
2873 127 return $self->_node_utf8_decode($bytes);
2874 }
2875  
2876 301 ▶sub _node_fs_path_bytes {
Subroutine _node_fs_path_bytes: called CC=1 SCAR=0.0
2877 301 my ( $self, $path ) = @_;
2878 301 my $bytes = $path;
2879 301 utf8::encode($bytes);
2880 301 return $bytes;
2881 }
2882  
2883 # libuv's error descriptions (uv_strerror) for the errors a read of an existing
2884 # path can meet, as node's util.getSystemErrorMap() lists them. Any other
2885 # errno keeps libuv's message shape with the system's own text, lowercased.
2886 23 my %NODE_UV_ERROR_MESSAGE = (
2887 EACCES => 'permission denied',
2888 EIO => 'i/o error',
2889 EISDIR => 'illegal operation on a directory',
2890 EMFILE => 'too many open files',
2891 ENFILE => 'file table overflow',
2892 ENOENT => 'no such file or directory',
2893 EPERM => 'operation not permitted',
2894 );
2895  
2896 # libuv's name for an errno the system knows by two (util.getSystemErrorMap()
2897 # lists EAGAIN and ENOTSUP, never EWOULDBLOCK or EOPNOTSUPP); any other errno
2898 # with two names (EDEADLK / EDEADLOCK, not in libuv's map) takes the first in
2899 # sort order, so the code never depends on hash order.
2900 23 my %NODE_UV_ERRNO_ALIAS = (
2901 EOPNOTSUPP => 'ENOTSUP',
2902 EWOULDBLOCK => 'EAGAIN',
2903 );
2904  
2905 # node's uvException: `${code}: ${message}, ${syscall}` plus ` '${path}'`.
2906 6 ▶sub _node_uv_exception {
Subroutine _node_uv_exception: called CC=5 SCAR=16.8
2907 6 my ( $self, $errno, $syscall, $path ) = @_;
2908 6 local $! = $errno;
2909 6 my $strerror = "$!";
2910 0 ▶ my ($code) = sort { $a cmp $b } CORE::map { $NODE_UV_ERRNO_ALIAS{$_} // $_ } grep { $!{$_} } CORE::keys %!;
Condition33%1/3
$NODE_UV_ERRNO_ALIAS{$_} // $_
l!l&&r!l&&!r
060
MC/DC0%0/2
$NODE_UV_ERRNO_ALIAS{$_} // $_
$NODE_UV_ERRNO_ALIAS{$_} $_
Truth table33%1/3
A // B
A= $NODE_UV_ERRNO_ALIAS{$_}B= $_
ABresult
1X1
011
000
2911 6 ▶ $code //= 'UNKNOWN';
Condition50%1/2
$code //= "UNKNOWN"
l!l
60
MC/DC0%0/1
$code //= "UNKNOWN"
$code
Truth table50%1/2
A
A= $code
Aresult
11
00
2912 6 ▶ my $message = $code . ': ' . ( $NODE_UV_ERROR_MESSAGE{$code} // lc $strerror ) . ', ' . $syscall;
Condition50%1/2
$NODE_UV_ERROR_MESSAGE{$code} // lc $strerror
l!l
60
MC/DC0%0/1
$NODE_UV_ERROR_MESSAGE{$code} // lc $strerror
$NODE_UV_ERROR_MESSAGE{$code}
Truth table50%1/2
A
A= $NODE_UV_ERROR_MESSAGE{$code}
Aresult
11
00
2913 6 ▶ $message .= " '" . $path . "'" if defined $path;
Branch: 1 branch
BranchTrueFalseTotal
if defined $path 2 4 6
2914 6 return Text::Nunjucks::Lib::Error->new($message);
2915 }
2916  
2917 # node's UTF-8 decoder, the WHATWG Encoding Standard's: a BOM is kept (a
2918 # U+FEFF character, oracle: a file starting EF BB BF renders U+FEFF first),
2919 # and every maximal subpart of an ill-formed sequence becomes one U+FFFD --
2920 # a lead byte with the continuation bytes that can still follow it, else a
2921 # single byte (oracle: C0 80 -> two, ED A0 80 -> three, F4 90 80 80 -> four,
2922 # E2 82 'b' -> one and 'b'). Perl's own strict decoder replaces differently
2923 # (one U+FFFD for each of those) and refuses noncharacters such as U+10FFFF,
2924 # which node decodes. Well-formed input -- what Perl's lax utf8::decode
2925 # accepts, minus surrogates and code points past U+10FFFF -- decodes in one
2926 # step; anything else runs the standard's decoder, byte by byte.
2927 970 ▶sub _node_utf8_decode {
Subroutine _node_utf8_decode: called CC=20 SCAR=30.0
2928 970 my ( $self, $bytes ) = @_;
2929 970 my $str = $bytes;
2930 970 ▶ return $str if utf8::decode($str) && $str !~ /[\x{D800}-\x{DFFF}]|[^\x{0}-\x{10FFFF}]/;
Branch: 1 branch
BranchTrueFalseTotal
if utf8::decode($str) and not $str =~ /[\x{D800}-\x{DFFF}]|[^\x{0}-\x{10FFFF}]/ 204 766 970
Condition100%3/3
utf8::decode($str) and not $str =~ /[\x{D800}-\x{DFFF}]|[^\x{0}-\x{10FFFF}]/
!ll&&!rl&&r
75016204
MC/DC100%2/2
utf8::decode($str) and not $str =~ /[\x{D800}-\x{DFFF}]|[^\x{0}-\x{10FFFF}]/
utf8::decode($str) not $str =~ /[\x{D800}-\x{DFFF}]|[^\x{0}-\x{10FFFF}]/
Truth table100%3/3
A and not(B)
A= utf8::decode($str)B= not $str =~ /[\x{D800}-\x{DFFF}]|[^\x{0}-\x{10FFFF}]/
ABresult
0X0
100
111
2931  
2932 # Encoding Standard, 8.1.1 UTF-8 decoder (error mode replacement).
2933 766 my $out = '';
2934 766 my $code_point = 0;
2935 766 my $bytes_seen = 0;
2936 766 my $bytes_needed = 0;
2937 766 my $lower_boundary = 0x80;
2938 766 my $upper_boundary = 0xBF;
2939 766 my $i = 0;
2940 766 my $n = length($bytes);
2941 766 while (1) {
2942 7788 ▶ if ( $i >= $n ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i >= $n) 766 7022 7788
2943 # end-of-queue
2944 766 ▶ $out .= "\x{FFFD}" if $bytes_needed != 0;
Branch: 1 branch
BranchTrueFalseTotal
if $bytes_needed != 0 199 567 766
2945 766 last;
2946 }
2947 7022 my $byte = ord( substr( $bytes, $i, 1 ) );
2948 7022 ▶ if ( $bytes_needed == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bytes_needed == 0) 4079 2943 7022
2949 4079 $i++;
2950 4079 ▶ if ( $byte <= 0x7F ) {
Branch: 4 branches
BranchTrueFalseTotal
if ($byte <= 127) { } 246 3833 4079
elsif ($byte >= 194 and $byte <= 223) { } 189 3644 3833
elsif ($byte >= 224 and $byte <= 239) { } 1003 2641 3644
elsif ($byte >= 240 and $byte <= 244) { } 777 1864 2641
2951 246 $out .= chr($byte);
2952 }
2953 ▶ elsif ( $byte >= 0xC2 && $byte <= 0xDF ) {
Condition100%3/3
$byte >= 194 and $byte <= 223
!ll&&!rl&&r
16172027189
MC/DC100%2/2
$byte >= 194 and $byte <= 223
$byte >= 194 $byte <= 223
Truth table100%3/3
A and B
A= $byte >= 194B= $byte <= 223
ABresult
0X0
100
111
2954 189 $bytes_needed = 1;
2955 189 $code_point = $byte & 0x1F;
2956 }
2957 ▶ elsif ( $byte >= 0xE0 && $byte <= 0xEF ) {
Condition100%3/3
$byte >= 224 and $byte <= 239
!ll&&!rl&&r
161710241003
MC/DC100%2/2
$byte >= 224 and $byte <= 239
$byte >= 224 $byte <= 239
Truth table100%3/3
A and B
A= $byte >= 224B= $byte <= 239
ABresult
0X0
100
111
2958 1003 ▶ $lower_boundary = 0xA0 if $byte == 0xE0;
Branch: 1 branch
BranchTrueFalseTotal
if $byte == 224 406 597 1003
2959 1003 ▶ $upper_boundary = 0x9F if $byte == 0xED;
Branch: 1 branch
BranchTrueFalseTotal
if $byte == 237 350 653 1003
2960 1003 $bytes_needed = 2;
2961 1003 $code_point = $byte & 0xF;
2962 }
2963 ▶ elsif ( $byte >= 0xF0 && $byte <= 0xF4 ) {
Condition100%3/3
$byte >= 240 and $byte <= 244
!ll&&!rl&&r
1617247777
MC/DC100%2/2
$byte >= 240 and $byte <= 244
$byte >= 240 $byte <= 244
Truth table100%3/3
A and B
A= $byte >= 240B= $byte <= 244
ABresult
0X0
100
111
2964 777 ▶ $lower_boundary = 0x90 if $byte == 0xF0;
Branch: 1 branch
BranchTrueFalseTotal
if $byte == 240 433 344 777
2965 777 ▶ $upper_boundary = 0x8F if $byte == 0xF4;
Branch: 1 branch
BranchTrueFalseTotal
if $byte == 244 344 433 777
2966 777 $bytes_needed = 3;
2967 777 $code_point = $byte & 0x7;
2968 }
2969 else {
2970 1864 $out .= "\x{FFFD}";
2971 }
2972 4079 next;
2973 }
2974 2943 ▶ if ( $byte < $lower_boundary || $byte > $upper_boundary ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($byte < $lower_boundary or $byte > $upper_boundary) 1143 1800 2943
Condition100%3/3
$byte < $lower_boundary or $byte > $upper_boundary
l!l&&r!l&&!r
3647791800
MC/DC100%2/2
$byte < $lower_boundary or $byte > $upper_boundary
$byte < $lower_boundary $byte > $upper_boundary
Truth table100%3/3
A or B
A= $byte < $lower_boundaryB= $byte > $upper_boundary
ABresult
1X1
011
000
2975 # the byte is not consumed: it is read again as the start of what follows
2976 1143 ( $code_point, $bytes_needed, $bytes_seen ) = ( 0, 0, 0 );
2977 1143 ( $lower_boundary, $upper_boundary ) = ( 0x80, 0xBF );
2978 1143 $out .= "\x{FFFD}";
2979 1143 next;
2980 }
2981 1800 $i++;
2982 1800 ( $lower_boundary, $upper_boundary ) = ( 0x80, 0xBF );
2983 1800 $code_point = ( $code_point << 6 ) | ( $byte & 0x3F );
2984 1800 $bytes_seen++;
2985 1800 ▶ next if $bytes_seen != $bytes_needed;
Branch: 1 branch
BranchTrueFalseTotal
if $bytes_seen != $bytes_needed 1173 627 1800
2986 627 $out .= chr($code_point);
2987 627 ( $code_point, $bytes_needed, $bytes_seen ) = ( 0, 0, 0 );
2988 }
2989 766 return $out;
2990 }
2991  
2992 # console.log(message) -- one line on standard output. The port's only caller
2993 # passes one string, whose util.format is the string itself.
2994 3 ▶sub node_console_log {
Subroutine node_console_log: called CC=1 SCAR=0.0
Pod undocumented
2995 3 my ( $self, $message ) = @_;
2996 3 print {*STDOUT} $message . "\n";
2997 3 return;
2998 }
2999  
3000 23 1;
3001  
3002 __END__
« blib/lib/Text/Nunjucks/Transformer.pm ↑ Summary blib/lib/Text/Nunjucks/Compiler.pm »