blib/lib/JQ/XS.pm

filter: Statementstmt 98.1% 104 / 106 Branchbran 87.5% 63 / 72 Conditioncond 100% 6 / 6 MC/DCmcdc 100% 3 / 3 Subroutinesub 93.7% 15 / 16 Podpod 100% 7 / 7 totaltotal 94.2% 198 / 210 CC 41 SCAR 22.6
CC
41
Cov
94%
new
19.0
_output_flags
10.0
library_paths
5.1
CRAP 9.6
↑ Summary XS.xs »
1 package JQ::XS;
2  
3 6 ▶use 5.026003;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 6 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 6 require XSLoader;
10 6 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 # process() blesses JSON booleans into JSON::PP::Boolean, so that class needs
13 # its overloads (numification, increment, fallback, ...) loaded. Other JSON
14 # modules install those operators into JSON::PP::Boolean themselves --
15 # Cpanel::JSON::XS does, and JSON::XS does it through Types::Serialiser -- and
16 # loading JSON::PP::Boolean on top of them redefines the operators, which warns
17 # under -w. So only load it when nobody has set the class up yet; "((" is the
18 # marker overload.pm installs in every overloaded class.
19 #
20 # Load it as JSON::PP rather than JSON::PP::Boolean on its own: a later
21 # Cpanel::JSON::XS reads $JSON::PP::VERSION to decide whether the operators
22 # need installing, and warns about it being undefined if it finds the boolean
23 # class loaded without its parent.
24 6 ▶BEGIN {
Subroutine BEGIN: called CC=2 SCAR=7.6
25 6 ▶ require JSON::PP unless JSON::PP::Boolean->can('((');
Branch: 1 branch
BranchTrueFalseTotal
unless "JSON::PP::Boolean"->can("((") 0 6 6
26 }
27  
28 6 our $VERSION = '2.04';
29  
30 6 XSLoader::load('JQ::XS', $VERSION);
31  
32 # Constants
33 sub JQ_DEBUG_TRACE () { 1 }
34 sub JQ_DEBUG_TRACE_DETAIL () { 2 }
35 sub JQ_DEBUG_TRACE_ALL () { 3 }
36  
37 # jv_dump_string flags, from jq's jv.h. Not exported: the output options
38 # below are the supported way to ask for these, and the bit layout is jq's
39 # private business.
40 sub JV_PRINT_PRETTY () { 1 }
41 sub JV_PRINT_ASCII () { 2 }
42 sub JV_PRINT_COLOR () { 4 }
43 sub JV_PRINT_SORTED () { 8 }
44 sub JV_PRINT_TAB () { 64 }
45  
46 6 our @EXPORT_OK = qw(
47 JQ_DEBUG_TRACE
48 JQ_DEBUG_TRACE_DETAIL
49 JQ_DEBUG_TRACE_ALL
50 jq_version
51 features
52 set_colors
53 parse_json
54 parse_json_stream
55 to_json
56 );
57  
58 =head1 NAME
59  
60 JQ::XS - Perl wrapper for libjq
61  
62 =head1 SYNOPSIS
63  
64 use JQ::XS;
65  
66 my $jq = JQ::XS->new('.foo[] | select(. > 2)');
67  
68 # Perl data interface
69 my @results = $jq->process({ foo => [1, 3, 5] });
70 # Returns: (3, 5)
71  
72 # JSON text interface
73 my @out = $jq->process_json('{"foo":[1,3,5]}');
74 # Returns: ('3', '5')
75  
76 # Named arguments, as jq's --arg/--argjson give you
77 my $greet = JQ::XS->new('"\($greeting), \(.name)!"',
78 vars => { greeting => 'Hello' });
79 my ($msg) = $greet->process({ name => 'Alice' }); # "Hello, Alice!"
80  
81 # Output formatting, as jq's -S/--tab/-r give you
82 my $pretty = JQ::XS->new('.', tab => 1, sort_keys => 1);
83 print $pretty->process_json('{"b":1,"a":2}'), "\n";
84  
85 # Refuse filters that pull in modules from disk
86 my $safe = do {
87 delete local $ENV{HOME}; # ...including the ~/.jq jq adds on its own
88 JQ::XS->new($untrusted, allow_includes => 0);
89 };
90  
91 # The debug, stderr and input/inputs builtins
92 my $sum = JQ::XS->new('[., inputs] | add',
93 inputs => [2, 3],
94 debug => sub { warn "jq: $_[0]\n" });
95 my ($total) = $sum->process(1); # 6
96  
97 # Get the program source
98 my $prog = $jq->program;
99  
100 =head1 DESCRIPTION
101  
102 JQ::XS provides a clean object-oriented wrapper around libjq, the C library
103 behind the jq command-line tool. It allows you to:
104  
105 - Compile and execute jq filter programs
106 - Process Perl data structures (hashes, arrays, numbers, strings)
107 - Process JSON text
108 - Pass named and positional arguments to a filter
109 - Format JSON output the way the jq command line does
110 - Serve the C<input>, C<inputs>, C<debug> and C<stderr> builtins from Perl
111 - Restrict what a filter may load from disk
112 - Handle errors gracefully with Perl exceptions (croak)
113  
114 =head1 METHODS
115  
116 =head2 new($program, %options)
117  
118 Creates a new JQ::XS object by compiling the given jq filter program.
119  
120 my $jq = JQ::XS->new('.foo');
121  
122 Croaks with an error message if the program fails to compile.
123  
124 The remaining arguments are name/value pairs. Every one of them has a
125 matching method, so anything that can be passed here can also be changed
126 later; the exceptions are C<vars>, C<args>, C<attrs>, C<library_paths> and
127 C<allow_includes>, which take effect while the program is being compiled and
128 so have to be given up front.
129  
130 =over 4
131  
132 =item vars => \%hash
133  
134 Named arguments, as C<jq --arg> and C<jq --argjson> pass them. Each key
135 becomes a C<$variable> in the program, and the values are arbitrary Perl data
136 converted the same way C<process()> converts its input.
137  
138 my $jq = JQ::XS->new('.[] | select(.dept == $dept)',
139 vars => { dept => 'sales' });
140  
141 =item args => \@list
142  
143 Positional arguments, as C<jq --args> passes them. They are available to the
144 program as C<$ARGS.positional>.
145  
146 C<$ARGS> is always defined, whether or not either option was given:
147 C<$ARGS.named> holds C<vars> and C<$ARGS.positional> holds C<args>, exactly
148 as on the jq command line.
149  
150 =item allow_includes => 0
151  
152 Reject the program if it contains an C<include> or C<import> directive,
153 rather than compiling it and letting it read C<.jq> files from disk. Defaults
154 to true, i.e. modules work as they always have. It does not stop jq importing
155 F<~/.jq> -- see L</RESTRICTING MODULE LOADING> for that.
156  
157 =item library_paths => \@dirs
158  
159 Where C<include> and C<import> look for modules -- jq's C<-L> option, and its
160 C<JQ_LIBRARY_PATH> attribute. See L</RESTRICTING MODULE LOADING> for what
161 this does and does not prevent.
162  
163 Defaults to empty, which is not what the jq command line defaults to: jq adds
164 two directories beside its own binary, and a library embedded in someone
165 else's program has no business reading those uninvited. It does not keep
166 F<~/.jq> out, which jq imports without consulting the library path at all --
167 see L</RESTRICTING MODULE LOADING>.
168  
169 =item attrs => \%hash
170  
171 jq attributes to set before the program is compiled, for anything
172 C<library_paths> does not cover: C<JQ_ORIGIN>, C<PROGRAM_ORIGIN>, and
173 C<JQ_LIBRARY_PATH> itself. See L<attr()|/attr($name)> and
174 L<set_attr()|/set_attr($name, $value)>.
175  
176 =item flags => $flags
177  
178 Flags for each run of the program, OR'd together from L</CONSTANTS>. Only
179 jq's execution tracing lives here. See L<flags()|/flags($flags)>.
180  
181 =item die_on_halt_error => 1
182  
183 Turn a filter's C<halt_error> into a Perl exception. See
184 L<die_on_halt_error()|/die_on_halt_error($bool)>.
185  
186 =item debug => \&code
187  
188 =item stderr => \&code
189  
190 =item inputs => \&code | \@values
191  
192 Perl code behind the C<debug>, C<stderr> and C<input>/C<inputs> builtins,
193 which do nothing at all otherwise. See
194 L<set_debug_cb()|/set_debug_cb(\&code)>,
195 L<set_stderr_cb()|/set_stderr_cb(\&code)> and
196 L<set_inputs()|/set_inputs($source)>.
197  
198 =item pretty, indent, tab, sort_keys, ascii, color, raw
199  
200 How C<process_json()> formats its output. See
201 L<set_output()|/set_output(%options)>.
202  
203 =back
204  
205 =head2 process($data)
206  
207 Processes Perl data through the compiled jq filter. Takes a Perl scalar
208 (which can be a reference to a hash or array) and returns a list of
209 results. Each result is a Perl data structure.
210  
211 my @results = $jq->process({ name => 'Alice' });
212  
213 In scalar context, returns an arrayref of results.
214  
215 my $results_ref = scalar($jq->process($data));
216  
217 Croaks if the jq filter produces a runtime error or if the processing fails.
218  
219 =head2 Boolean handling
220  
221 JSON booleans returned by a filter become L<JSON::PP::Boolean> objects,
222 which behave as true/false in boolean context and stringify to C<1> and
223 C<0>. They compare equal to the C<JSON::PP::true> and C<JSON::PP::false>
224 constants.
225  
226 my ($is_big) = JQ::XS->new('. > 2')->process(5); # JSON::PP::true
227  
228 On input, the following are converted to JSON C<true>/C<false>:
229  
230 =over 4
231  
232 =item * L<JSON::PP::Boolean>, C<Types::Serialiser::Boolean>, or L<boolean>
233 objects (by their truth value)
234  
235 =item * unblessed references to a plain scalar, e.g. C<\1> and C<\0>
236  
237 =item * Perl's native boolean values, i.e. the results of comparison and
238 logical operators and of C<builtin::true>/C<builtin::false>
239  
240 $jq->process($x > $y); # jq sees true or false, not 1 or ""
241  
242 On perls before 5.36 this only works for a boolean passed directly to
243 C<process()>; a copy (e.g. stored in a hash or array first) loses its
244 boolean identity and is treated as an ordinary number/string. On perl
245 5.36 and later, copies keep their boolean flag and are recognized
246 anywhere in the structure.
247  
248 =back
249  
250 =head2 Number handling
251  
252 jq holds every number as an IEEE double, so that is the precision a value
253 has once it has been through a filter. This is invisible on most perls,
254 whose NVs are doubles as well, but a perl built with C<-Duselongdouble> or
255 C<-Dusequadmath> carries more precision in an NV than jq can represent, and
256 a number that makes the round trip comes back as the nearest double:
257  
258 # on a perl whose archname ends in -ld or -quadmath
259 my ($n) = JQ::XS->new('.')->process(3.14);
260 print $n; # 3.14000000000000012, the double nearest 3.14
261  
262 Nothing is lost beyond double precision, and the value is the same one jq
263 itself would compute; only the digits an over-wide NV would have kept are
264 gone. Where that matters, narrow the input to a double first, so both
265 sides agree:
266  
267 my $n = unpack 'd', pack 'd', 3.14;
268  
269 C<process_json()> is not affected. It returns JSON text straight from jq,
270 which from jq 1.7 onwards reproduces the literal of any number it has not
271 done arithmetic on, so precision beyond a double survives intact.
272  
273 =head2 process_json($json_text, %options)
274  
275 Like process, but takes JSON text as input and returns a list of JSON
276 strings (one for each output).
277  
278 my @json_out = $jq->process_json('{"name":"Alice"}');
279  
280 Croaks if the JSON input is invalid or if the jq filter produces a runtime
281 error.
282  
283 Any options given here are merged over the object's own output options for
284 this one call, and are the same ones L<set_output()|/set_output(%options)>
285 takes:
286  
287 my @pretty = $jq->process_json($json, indent => 4, sort_keys => 1);
288  
289 =head2 program()
290  
291 Returns the source code of the compiled jq filter program.
292  
293 my $src = $jq->program;
294  
295 =head1 OUTPUT FORMATTING
296  
297 =head2 set_output(%options)
298  
299 Sets how C<process_json()> formats its results, and returns the object.
300 Options not mentioned are reset to their defaults, so this replaces the
301 current settings rather than adding to them; to change one and keep the rest,
302 merge L</output_options()> yourself, or pass the option to C<process_json()>
303 for a single call.
304  
305 $jq->set_output(indent => 2, sort_keys => 1);
306  
307 Each option corresponds to a jq command-line switch:
308  
309 =over 4
310  
311 =item pretty => 1
312  
313 Indent output by two spaces, one value per line, as jq does by default. The
314 JQ::XS default is jq's C<-c>: everything on one line.
315  
316 =item indent => $n
317  
318 Indent by C<$n> spaces, C<$n> being 0 to 7 -- jq's C<--indent n>. As in jq,
319 C<indent =E<gt> 0> still puts one value per line, just without indentation;
320 it is not the same as compact output.
321  
322 =item tab => 1
323  
324 Indent with tabs -- jq's C<--tab>. Wins over C<indent> and C<pretty>, as it
325 does in jq.
326  
327 =item sort_keys => 1
328  
329 Emit object keys in sorted order -- jq's C<-S>.
330  
331 =item ascii => 1
332  
333 Escape all non-ASCII characters -- jq's C<-a>.
334  
335 =item color => 1
336  
337 Colorize the output with ANSI escapes -- jq's C<-C>.
338 L<set_colors()|/set_colors($spec)> chooses the colors.
339  
340 =item raw => 1
341  
342 Emit a result that is a JSON string as the string itself, without quotes or
343 escapes -- jq's C<-r>. Results of every other type are still JSON.
344  
345 Note that C<raw> with C<ascii> behaves as C<jq -r -a> does, which is to say
346 that C<ascii> wins and strings come out quoted and escaped.
347  
348 =back
349  
350 =head2 output_options()
351  
352 Returns a hashref copy of the options L<set_output()|/set_output(%options)>
353 was last given.
354  
355 =head1 HALT AND EXIT
356  
357 A filter can stop itself with jq's C<halt> or C<halt_error>. Neither is an
358 error as far as C<process()> is concerned -- results produced before the halt
359 are still returned -- so these three methods, all of which describe the most
360 recent run, are how you find out that it happened.
361  
362 =head2 halted()
363  
364 True if the last run ended in C<halt> or C<halt_error>.
365  
366 =head2 exit_code()
367  
368 The exit code the filter halted with, or C<undef> if it did not halt (or
369 halted without one). This is what the jq command line would have exited with.
370  
371 =head2 error_message()
372  
373 The message C<halt_error> was given, or C<undef>. Usually a string, but
374 C<halt_error> accepts any JSON value and this returns it converted like any
375 other result.
376  
377 =head2 die_on_halt_error($bool)
378  
379 Sets whether C<halt_error> raises a Perl exception carrying its message, and
380 returns the previous setting. Off by default, which is why the message would
381 otherwise be silently dropped -- there is no stderr for it to go to. Plain
382 C<halt> never raises, having no message; use L</halted()> for that.
383  
384 $jq->die_on_halt_error(1);
385 my @out = eval { $jq->process($data) };
386 warn "filter gave up: $@" if $@;
387  
388 =head1 CALLBACKS
389  
390 libjq leaves the C<debug>, C<stderr>, C<input> and C<inputs> builtins
391 unconnected, so until you give them somewhere to go, C<debug> and C<stderr>
392 discard their input and C<inputs> produces nothing.
393  
394 An exception thrown by a callback is not lost, but it cannot be raised from
395 where it happens either -- that would abandon a jq program mid-run. A C<debug>
396 or C<stderr> exception is re-raised by C<process()> once the run has finished;
397 an C<inputs> exception becomes a jq error, which the filter's own C<try>/
398 C<catch> can see, and which otherwise surfaces as the run's runtime error.
399  
400 =head2 set_debug_cb(\&code)
401  
402 Sets the code called for each C<debug> in the filter, with the value being
403 debugged as its only argument. Pass no argument, or C<undef>, to disconnect it
404 again. Returns nothing.
405  
406 $jq->set_debug_cb(sub { warn 'DEBUG: ' . to_json($_[0]) . "\n" });
407  
408 =head2 set_stderr_cb(\&code)
409  
410 The same, for the C<stderr> builtin.
411  
412 jq grew C<jq_set_stderr_cb> in 1.7, so under C<JQ_SYSTEM=1> against an older
413 libjq this croaks rather than silently doing nothing, and
414 L<features()|/features()> reports C<stderr_cb> as false. The vendored build
415 always has it.
416  
417 =head2 set_inputs($source)
418  
419 Connects the C<input> and C<inputs> builtins to C<$source>, and returns the
420 object. C<$source> is either an arrayref, whose elements are handed out in
421 order, or a code ref called once per value:
422  
423 $jq->set_inputs(sub { my $line = <$fh>; defined $line ? $line : () });
424  
425 Returning an empty list ends the stream. Returning C<undef> does not: that is
426 one more value, JSON C<null>. Pass C<undef> as C<$source> to disconnect.
427  
428 =head1 RESTRICTING MODULE LOADING
429  
430 A jq program can pull definitions in from C<.jq> files on disk:
431  
432 include "foo"; # ./foo.jq, or a library path
433 import "bar" as bar {search:"/x"}; # /x/bar.jq
434  
435 Which is worth thinking about if the programs you compile come from somewhere
436 you do not control.
437  
438 A definition gets in from disk two ways -- a directive in the program, or the
439 F<~/.jq> jq imports on its own -- and they need different answers. Both happen
440 while the program is being compiled, which is to say inside C<new()>: nothing
441 is loaded later, and nothing you change on an object afterwards unloads what
442 it compiled with.
443  
444 =head2 Directives in the program
445  
446 C<allow_includes =E<gt> 0> rejects any program containing one of these
447 directives, at compile time, before jq has looked at the filesystem:
448  
449 my $jq = JQ::XS->new($untrusted, allow_includes => 0); # croaks on include
450  
451 This is decided from the program text, but it is exact rather than a guess:
452 jq's grammar only accepts C<include> and C<import> in the program prologue, so
453 that is the only place they can be, and legal programs that merely use the
454 words elsewhere -- C<{include: 1}>, C<.foo.include> -- still compile.
455  
456 =head2 Where those directives look
457  
458 C<library_paths> does not decide whether a directive may load anything, only
459 where it looks, as jq's C<-L> does:
460  
461 my $jq = JQ::XS->new($prog, library_paths => ['/usr/share/myapp/jq']);
462  
463 but it cannot by itself stop a program from loading anything, because jq
464 searches the current directory when a program does not say where to look, and
465 a program that does say -- C<include "x" {search:"/tmp"};> -- is not searching
466 the library paths at all. C<allow_includes =E<gt> 0> is the one that decides
467 whether a program may load modules; C<library_paths> only steers the ones it
468 is already allowed to load.
469  
470 =head2 The F<~/.jq> jq imports on its own
471  
472 jq imports F<~/.jq> into every program it compiles, whether or not the program
473 asks for it, and neither option above prevents it:
474  
475 =over 4
476  
477 =item *
478  
479 C<allow_includes =E<gt> 0> does not see it. That option reads the program
480 text, and this import is not in the program text -- jq's linker prepends it to
481 every program on its way to being compiled.
482  
483 =item *
484  
485 C<library_paths> does not apply to it. The import carries its own search path,
486 the home directory, and jq consults C<JQ_LIBRARY_PATH> only for an import that
487 names no path of its own. An empty C<library_paths> is simply not consulted.
488  
489 =back
490  
491 So whatever F<~/.jq> defines is in scope for the program, and can shadow
492 builtins for it. The import is marked optional, so it is silent when there is
493 no such file, which is why this tends to go unnoticed on hosts that do not
494 happen to have one.
495  
496 jq locates that file through C<$HOME>, and skips the import when C<$HOME> is
497 unset. Take C<HOME> out of the environment for the call and nothing is
498 imported:
499  
500 my $jq = do {
501 delete local $ENV{HOME};
502 JQ::XS->new($prog);
503 };
504  
505 Only C<new()> has to be inside that scope. The import is resolved as the
506 program is compiled and is then fixed in the compiled program, so restoring
507 C<HOME> before you run anything neither unloads a F<~/.jq> that was already
508 imported nor lets one in afterwards. Nothing else in jq reads C<$HOME>, and
509 unsetting it changes nothing else about how a program runs.
510  
511 Use C<delete local>, not C<local $ENV{HOME} = ''>. An empty C<HOME> is still a
512 home directory as far as jq is concerned, one whose F<~/.jq> is F</.jq>: the
513 import is skipped only because that file usually does not exist, not because
514 jq declined to look for it. C<delete local> is what makes it not look.
515  
516 On anything but Windows, C<HOME> is the only variable jq consults. On Windows
517 it falls back to C<USERPROFILE>, and then to C<HOMEDRIVE> and C<HOMEPATH>,
518 when C<HOME> is unset, so all of them have to go:
519  
520 delete local @ENV{qw(HOME USERPROFILE HOMEDRIVE HOMEPATH)};
521  
522 =head2 Loading nothing at all
523  
524 Together, for a program you did not write:
525  
526 my $jq = do {
527 delete local $ENV{HOME};
528 JQ::XS->new($untrusted, allow_includes => 0);
529 };
530  
531 C<library_paths> does not appear because it does not need to: it already
532 defaults to empty, and with includes refused there is nothing left to steer.
533  
534 =head2 library_paths(\@dirs)
535  
536 Without an argument, returns the current module search path as an arrayref.
537 With one, replaces it and returns the object.
538  
539 Setting it after construction does not retroactively change what the compiled
540 program included; it is the C<modulemeta> builtin and jq's C<$__loc__>
541 machinery that read it later.
542  
543 =head1 RESTRICTING ENVIRONMENT ACCESS
544  
545 A jq program can read the process environment two different ways, and they are
546 independent of each other:
547  
548 =over 4
549  
550 =item *
551  
552 C<$ENV> is resolved while the program is compiled. jq's compiler rewrites
553 every reference to C<$ENV> that nothing else has already bound into a constant
554 built by walking the process's environment -- the same object C<jq -n '$ENV'>
555 prints on the command line.
556  
557 =item *
558  
559 C<env> is an ordinary builtin function. It reads the environment itself,
560 fresh, each time it runs.
561  
562 =back
563  
564 Neither is behind an attribute or a flag the way L</RESTRICTING MODULE
565 LOADING> is: libjq offers no switch for either, and JQ::XS adds no option of
566 its own. What follows is something you do to the program text yourself, before
567 it is compiled, rather than anything the module does for you.
568  
569 =head2 Shadowing both
570  
571 jq only substitutes the real environment for C<$ENV> when nothing has bound
572 that name already, and C<env> is only special until something earlier in the
573 program redefines it -- an ordinary C<def> shadows a builtin exactly as it
574 would shadow any other definition, for everything lexically after it. Put both
575 ahead of a program and neither name reaches the real environment:
576  
577 def env: {};
578 {} as $ENV | (
579 ... the program ...
580 )
581  
582 C<env> and C<$ENV> both come back C<{}> inside the parentheses, and C<env.FOO>
583 / C<$ENV.FOO> come back C<null>, whatever C<FOO> actually holds in the process
584 running it.
585  
586 =head2 Mind the closing paren
587  
588 jq comments run to the end of the line, so the wrapper's own closing paren is
589 easy to lose inside one if the program being wrapped ends in a C<#> comment
590 with no newline of its own after it:
591  
592 # BUG: that ')' is inside the comment, not code
593 my $wrapped = 'def env: {}; {} as $ENV | (' . $program . ')';
594  
595 That particular case fails safely -- jq reports a syntax error for the
596 now-unclosed paren rather than compiling into something unintended -- but it
597 is still a confusing way to make an otherwise fine program stop working. Give
598 the closing paren its own line instead, so a trailing comment can only ever
599 reach the newline before it:
600  
601 my $wrapped = 'def env: {}; {} as $ENV | (' . "\n"
602 . $program . "\n"
603 . ')';
604 my $jq = JQ::XS->new($wrapped, allow_includes => 0);
605  
606 =head2 Programs that use import/include
607  
608 This prologue is textual, so it has to come before whatever the program does,
609 and that only works when the program has no C<import> or C<include> directive
610 of its own: jq's grammar allows those only at the very start of a program, a
611 position this prologue has just taken for itself. Wrap a program that begins
612 with one and jq reports a plain syntax error -- C<unexpected import> -- rather
613 than the clearer "not allowed" L</RESTRICTING MODULE LOADING> gives, because
614 the parse never gets far enough for that check to run.
615  
616 Pairing the prologue with C<allow_includes =E<gt> 0> costs nothing, then: such
617 a program was never going to be allowed a directive in the first place, so the
618 prologue rules out no case that was still open. That is the combination to
619 reach for when the program is one you did not write, as in the example above.
620  
621 For a program you do control and want both for, put the prologue after the
622 directives rather than before them -- C<import "x" as m; def env: {}; {} as
623 $ENV | ( ... )> compiles fine. Doing the same to a program you did not write
624 means finding where its prologue ends, which is jq lexing rather than a
625 regexp, so it is worth it only when you already know the shape of what you are
626 wrapping.
627  
628 =head2 Exposing a filtered subset instead
629  
630 Rather than writing the replacement into the program text -- and having to
631 think about escaping whatever it contains -- pass it through
632 L<new()|/new($program, %options)>'s C<vars> option instead, and reference it
633 from the prologue:
634  
635 my $jq = JQ::XS->new(
636 'def env: $__jqxs_env; $__jqxs_env as $ENV | (' . "\n"
637 . $program . "\n"
638 . ')',
639 vars => { __jqxs_env => { PATH => $ENV{PATH} } }, # Perl's %ENV here
640 );
641  
642 C<env> and C<$ENV> now both come back C<{"PATH": ...}> inside the program,
643 with the rest of the process's environment out of reach -- a way to hand a
644 filter the one or two variables it legitimately needs without handing it
645 everything.
646  
647 =head1 ATTRIBUTES
648  
649 =head2 attr($name)
650  
651 Returns the jq attribute C<$name>, or C<undef> if it was never set. jq keeps
652 C<JQ_LIBRARY_PATH>, C<JQ_ORIGIN> and C<PROGRAM_ORIGIN> here.
653  
654 =head2 set_attr($name, $value)
655  
656 Sets one. Attributes that affect compilation have to be set through
657 C<new()>'s C<attrs> option instead, since by the time you have an object the
658 program is already compiled.
659  
660 =head1 EXECUTION FLAGS
661  
662 =head2 flags($flags)
663  
664 Sets the flags each run passes to jq, and returns the previous value. The
665 only flags jq defines are the execution traces in L</CONSTANTS>, which write
666 to the process's standard error.
667  
668 $jq->flags(JQ_DEBUG_TRACE);
669  
670 =head2 dump_disassembly($indent)
671  
672 Writes the compiled program's bytecode to standard output, as jq's
673 C<--debug-dump-disasm> does. C<$indent> defaults to 0.
674  
675 jq prints this from C, to the process's file descriptor 1 rather than through
676 Perl's C<STDOUT> handle, so reopening C<STDOUT> in Perl will not capture it;
677 redirect the file descriptor if you need to.
678  
679 =head1 FUNCTIONS
680  
681 These are all exportable.
682  
683 =head2 jq_version()
684  
685 Returns the version of the jq compiled into this build, e.g. C<'1.8.2'>, or
686 C<undef> if the module was built against the libjq the operating system
687 packages (see L</EMBEDDED JQ>).
688  
689 use JQ::XS qw(jq_version);
690 print jq_version(); # 1.8.2
691  
692 =head2 parse_json($text)
693  
694 Parses one JSON value with jq's own parser and returns it as Perl data, with
695 the same type mapping C<process()> uses. Croaks if the text is not a single
696 valid JSON value.
697  
698 =head2 parse_json_stream($text)
699  
700 The same, for text holding any number of JSON values one after another --
701 which is what the jq command line reads from a file or a pipe, and what
702 C<parse_json()> rejects. Returns them as a list.
703  
704 my @values = parse_json_stream("1 2 {\"a\":3}"); # (1, 2, {a=>3})
705  
706 =head2 to_json($data, %options)
707  
708 Serializes Perl data to JSON with jq's own printer. Takes the formatting
709 options L<set_output()|/set_output(%options)> takes, apart from C<raw>:
710  
711 print to_json($data, indent => 2, sort_keys => 1), "\n";
712  
713 =head2 set_colors($spec)
714  
715 Sets the colors C<color =E<gt> 1> output uses, in the format of jq's
716 C<JQ_COLORS> environment variable -- a colon-separated list of ANSI SGR
717 sequences for null, false, true, numbers, strings, arrays, objects and object
718 keys:
719  
720 set_colors('0;90:0;39:0;39:0;39:0;32:1;39:1;39:34;1');
721  
722 Returns true if the specification was understood. This is a global setting
723 inside libjq, not a per-object one, so it affects every JQ::XS object in the
724 process.
725  
726 =head2 features()
727  
728 Returns a hashref describing what this build of the module can do, which
729 under C<JQ_SYSTEM=1> depends on the libjq it was linked against:
730  
731 =over 4
732  
733 =item embedded_jq
734  
735 True if the jq engine is compiled into the module, false under
736 C<JQ_SYSTEM=1>. The same distinction L<jq_version()|/jq_version()> reports by
737 returning C<undef>.
738  
739 =item stderr_cb
740  
741 True if L<set_stderr_cb()|/set_stderr_cb(\&code)> works, i.e. if the libjq
742 has the C<jq_set_stderr_cb> that jq 1.7 added.
743  
744 =back
745  
746 =head1 CONSTANTS
747  
748 The following constants are available via @EXPORT_OK:
749  
750 JQ_DEBUG_TRACE - value 1
751 JQ_DEBUG_TRACE_DETAIL - value 2
752 JQ_DEBUG_TRACE_ALL - value 3
753  
754 They are the flags L<flags()|/flags($flags)> accepts.
755  
756 =head1 EMBEDDED JQ
757  
758 From version 2.00, JQ::XS does not use the libjq the operating system packages.
759 It ships an upstream jq release under F<vendor/>, compiles it at install time
760 and links it statically, so the installed module has no libjq to find at
761 runtime and behaves the same way on every distribution regardless of the jq
762 version that distribution ships. L</jq_version()> reports which jq that is.
763  
764 Building needs only a C compiler, C<make> and a POSIX shell; jq's own release
765 tarball is self-contained, and its bundled oniguruma is built too, so the regex
766 builtins (C<test>, C<match>, C<capture>, C<sub>, C<gsub>, C<scan>, C<splits>)
767 work without an external library.
768  
769 To link the OS libjq instead, configure with:
770  
771 perl Makefile.PL JQ_SYSTEM=1
772  
773 in which case L</jq_version()> returns C<undef> and the filter semantics are
774 whatever the installed libjq implements. Everything the XS uses has been in
775 libjq since jq 1.5 bar one: C<jq_set_stderr_cb>, behind
776 L<set_stderr_cb()|/set_stderr_cb(\&code)>, arrived in 1.7, and Makefile.PL
777 link-probes for it -- against an older libjq the build says so and
778 L<features()|/features()> reports C<stderr_cb> as false.
779  
780 One caveat worth knowing before choosing that build, since it cannot be
781 worked around from here: the jq 1.6 that RHEL 8 and Debian 11 ship corrupts
782 its own heap in C<jq_teardown> after a filter has called C<halt_error>, which
783 aborts the process when the JQ::XS object is freed. Later jq releases are
784 fine, and so is the embedded build.
785  
786 =head1 AUTHOR
787  
788 James Rouzier E<lt>rouzier@gmail.comE<gt>
789  
790 =head1 COPYRIGHT AND LICENSE
791  
792 Copyright (C) 2026 James Rouzier
793  
794 This library is free software; you can redistribute it and/or modify
795 it under the terms of the MIT license. See the LICENSE file included
796 with this distribution.
797  
798 =cut
799  
800 # program(), the accessors, the callback setters and DESTROY are implemented
801 # in XS; the object is a blessed pointer to a C struct (T_PTROBJ), not a
802 # hashref, which is why every option below has to be stored on the C side.
803  
804 6 my %OUTPUT_OPTION = map { $_ => 1 }
805 qw(pretty indent tab sort_keys ascii color raw);
806  
807 6 my %NEW_OPTION = map { $_ => 1 } qw(
808 vars args attrs library_paths allow_includes
809 flags die_on_halt_error debug stderr inputs
810 );
811  
812 # Compile a set of output options down to the (jv_dump_string flags, raw)
813 # pair the XS side works with.
814 97 ▶sub _output_flags {
Subroutine _output_flags: called CC=10 SCAR=23.0
815 97 my ($opts) = @_;
816  
817 97 my @unknown = sort grep { !$OUTPUT_OPTION{$_} } keys %$opts;
818 97 ▶ croak 'Unknown output option: ' . join(', ', @unknown) if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 96 97
819  
820 96 my $flags = 0;
821  
822 # jq's own precedence, from its main.c: --tab beats --indent, and the
823 # default is -c (compact) rather than the pretty output jq gives a tty.
824 96 ▶ if ($opts->{tab}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($opts->{'tab'}) { } 2 94 96
elsif (defined $opts->{'indent'}) { } 4 90 94
elsif ($opts->{'pretty'}) { } 3 87 90
825 2 $flags |= JV_PRINT_TAB | JV_PRINT_PRETTY;
826 }
827 elsif (defined $opts->{indent}) {
828 croak 'indent must be an integer from 0 to 7'
829 4 ▶ unless $opts->{indent} =~ /\A[0-7]\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $opts->{"indent"} =~ /\A[0-7]\z/u 1 3 4
830 # jq's JV_PRINT_INDENT_FLAGS: the width goes in bits 8-10. Zero is
831 # not compact, it is "one value per line, unindented", same as jq.
832 3 $flags |= JV_PRINT_PRETTY | ($opts->{indent} << 8);
833 }
834 elsif ($opts->{pretty}) {
835 3 $flags |= JV_PRINT_PRETTY | (2 << 8);
836 }
837  
838 95 ▶ $flags |= JV_PRINT_SORTED if $opts->{sort_keys};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"sort_keys"} 4 91 95
839 95 ▶ $flags |= JV_PRINT_ASCII if $opts->{ascii};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"ascii"} 3 92 95
840 95 ▶ $flags |= JV_PRINT_COLOR if $opts->{color};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"color"} 1 94 95
841  
842 95 ▶ return ($flags, $opts->{raw} ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'raw'} ? : 3 92 95
843 }
844  
845 103 ▶sub new {
Subroutine new: called CC=19 SCAR=29.5
Pod documented
846 103 my ($class, $program, %opts) = @_;
847  
848 # The output options share the one flat option list, so split them out
849 # before checking what is left for typos.
850 103 my %output;
851 103 for my $key (keys %OUTPUT_OPTION) {
852 721 ▶ $output{$key} = delete $opts{$key} if exists $opts{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{$key} 15 706 721
853 }
854  
855 103 my @unknown = sort grep { !$NEW_OPTION{$_} } keys %opts;
856 103 ▶ croak 'Unknown option to JQ::XS->new: ' . join(', ', @unknown) if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 102 103
857  
858 102 ▶ my $vars = $opts{vars} || {};
Condition100%2/2
$opts{'vars'} || {}
l!l
498
MC/DC100%1/1
$opts{'vars'} || {}
$opts{'vars'}
Truth table100%2/2
A
A= $opts{'vars'}
Aresult
11
00
859 102 ▶ ref $vars eq 'HASH' or croak 'vars must be a hash reference';
Branch: 1 branch
BranchTrueFalseTotal
ref $vars eq "HASH" or croak("vars must be a hash reference") 101 1 102
860 101 ▶ my $args = $opts{args} || [];
Condition100%2/2
$opts{'args'} || []
l!l
1100
MC/DC100%1/1
$opts{'args'} || []
$opts{'args'}
Truth table100%2/2
A
A= $opts{'args'}
Aresult
11
00
861 101 ▶ ref $args eq 'ARRAY' or croak 'args must be an array reference';
Branch: 1 branch
BranchTrueFalseTotal
ref $args eq "ARRAY" or croak("args must be an array reference") 101 0 101
862  
863 # What jq's main.c hands jq_compile_args: the named arguments, plus an
864 # ARGS that collects them next to the positional ones. Always passing
865 # ARGS is what makes $ARGS defined in every program, as it is in jq.
866 101 my %compile_args = (
867 %$vars,
868 ARGS => { named => {%$vars}, positional => [@$args] },
869 );
870  
871 101 ▶ my %attrs = %{ $opts{attrs} || {} };
Condition100%2/2
$opts{'attrs'} || {}
l!l
1100
MC/DC100%1/1
$opts{'attrs'} || {}
$opts{'attrs'}
Truth table100%2/2
A
A= $opts{'attrs'}
Aresult
11
00
872 101 ▶ if (my $paths = $opts{library_paths}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $paths = $opts{"library_paths"}) 4 97 101
873 4 ▶ ref $paths eq 'ARRAY'
Branch: 1 branch
BranchTrueFalseTotal
ref $paths eq "ARRAY" or croak("library_paths must be an array reference") 4 0 4
874 or croak 'library_paths must be an array reference';
875 4 $attrs{JQ_LIBRARY_PATH} = [@$paths];
876 }
877  
878 # Always leave JQ_LIBRARY_PATH holding an array, never unset. An empty
879 # one is the right default for a library -- jq's command line defaults to
880 # searching ~/.jq, which is not somewhere a module embedded in someone
881 # else's program should read from uninvited -- and it also steps around a
882 # jq 1.6 bug that a JQ_SYSTEM=1 build can still meet: 1.6's
883 # jq_get_lib_dirs() hands the unset attribute straight to jv_array_concat
884 # without checking it, and the failed assertion aborts the process while
885 # any program containing an include is being compiled.
886 101 ▶ $attrs{JQ_LIBRARY_PATH} = [] unless exists $attrs{JQ_LIBRARY_PATH};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $attrs{"JQ_LIBRARY_PATH"} 97 4 101
887  
888 my $allow_includes =
889 101 ▶ exists $opts{allow_includes} ? ($opts{allow_includes} ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $opts{'allow_includes'} ? : 18 83 101
$opts{'allow_includes'} ? : 0 18 18
890  
891 101 my $self =
892 _new($class, $program, \%compile_args, \%attrs, $allow_includes);
893  
894 # Everything from here on is settable after the fact, so it goes through
895 # the same methods a caller would use.
896 91 $self->set_output(%output);
897 90 ▶ $self->flags($opts{flags}) if defined $opts{flags};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"flags"} 1 89 90
898 90 ▶ $self->die_on_halt_error(1) if $opts{die_on_halt_error};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"die_on_halt_error"} 1 89 90
899 90 ▶ $self->set_debug_cb($opts{debug}) if defined $opts{debug};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"debug"} 3 87 90
900 89 ▶ $self->set_stderr_cb($opts{stderr}) if defined $opts{stderr};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"stderr"} 1 88 89
901 89 ▶ $self->set_inputs($opts{inputs}) if defined $opts{inputs};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"inputs"} 7 82 89
902  
903 88 return $self;
904 }
905  
906 93 ▶sub set_output {
Subroutine set_output: called CC=1 SCAR=0.0
Pod documented
907 93 my ($self, %opts) = @_;
908 93 my ($flags, $raw) = _output_flags(\%opts);
909 91 _set_output($self, \%opts, $flags, $raw);
910 91 return $self;
911 }
912  
913 8 ▶sub set_inputs {
Subroutine set_inputs: called CC=4 SCAR=13.9
Pod documented
914 8 my ($self, $source) = @_;
915  
916 8 ▶ if (!defined $source) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $source) { } 0 8 8
elsif (ref $source eq 'CODE') { } 4 4 8
elsif (ref $source eq 'ARRAY') { } 3 1 4
917 0 $self->set_input_cb(undef);
918 }
919 elsif (ref $source eq 'CODE') {
920 4 $self->set_input_cb($source);
921 }
922 elsif (ref $source eq 'ARRAY') {
923 # One element per call, then the empty list that ends the stream. The
924 # elements are copied, so that a caller mutating their array partway
925 # through a run cannot move the cursor out from under it.
926 3 my @queue = @$source;
927 3 my $i = 0;
928 3 ▶ $self->set_input_cb(sub { $i < @queue ? $queue[ $i++ ] : () });
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$i < @queue ? : 3 4 7
929 }
930 else {
931 1 croak 'inputs must be a code reference or an array reference';
932 }
933  
934 7 return $self;
935 }
936  
937 3 ▶sub library_paths {
Subroutine library_paths: called CC=5 SCAR=16.4
Pod documented
938 3 my $self = shift;
939  
940 3 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 1 2 3
941 1 my $paths = shift;
942 1 ▶ $paths = [] unless defined $paths;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $paths 0 1 1
943 1 ▶ ref $paths eq 'ARRAY'
Branch: 1 branch
BranchTrueFalseTotal
ref $paths eq "ARRAY" or croak("library_paths must be an array reference") 1 0 1
944 or croak 'library_paths must be an array reference';
945 1 $self->set_attr('JQ_LIBRARY_PATH', [@$paths]);
946 1 return $self;
947 }
948  
949 2 my $paths = $self->attr('JQ_LIBRARY_PATH');
950 2 ▶ return defined $paths ? $paths : [];
Branch: 1 branch
BranchTrueFalseTotal
defined $paths ? : 2 0 2
951 }
952  
953 # Pass $_[0] through unaliased: copying it (my $data = ...) would strip
954 # the identity of Perl's native boolean SVs on perls before 5.36.
955 76 ▶sub process {
Subroutine process: called CC=2 SCAR=6.9
Pod documented
956 76 my $self = shift;
957 76 my $results = _xs_process($self, $_[0], 0, -1, 0);
958 69 ▶ return wantarray ? @$results : $results;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 66 3 69
959 }
960  
961 18 ▶sub process_json {
Subroutine process_json: called CC=3 SCAR=11.0
Pod documented
962 18 my $self = shift;
963 18 my $text = shift;
964  
965 # -1 tells the XS side to use the object's own output options; anything
966 # given here is merged over them for this call only.
967 18 my ($flags, $raw) = (-1, 0);
968 18 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 1 17 18
969 1 my %opts = (%{ $self->output_options }, @_);
970 1 ($flags, $raw) = _output_flags(\%opts);
971 }
972  
973 18 my $results = _xs_process($self, $text, 1, $flags, $raw);
974 17 ▶ return wantarray ? @$results : $results;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 17 0 17
975 }
976  
977 4 ▶sub to_json {
Subroutine to_json: called CC=2 SCAR=6.9
Pod documented
978 4 my $data = shift;
979 4 my %opts = @_;
980 4 ▶ croak 'to_json does not take a raw option' if $opts{raw};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"raw"} 1 3 4
981 3 my ($flags) = _output_flags(\%opts);
982 3 return _to_json($data, $flags);
983 }
984  
985 # Don't clone the underlying C struct into new ithreads.
986 0 ▶sub CLONE_SKIP { 1 }
Subroutine CLONE_SKIP: not called CC=1 SCAR=6.9
987  
988 6 1;
↑ Summary XS.xs »