Axk/Core.pm

filter: Statementstmt 20.4% 19 / 93 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 20 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 50.0% 7 / 14 Podpod n/a totaltotal 14.6% 26 / 177 CC 30 SCAR 46.4
CC
30
Cov
13%
load_script_text
241.7
_run_worklist
56.0
_run_pre_file
20.0
CRAP 103.9
« Axk/Language.pm ↑ Summary Axk/Sandbox.pm »
1 #!perl
2 # Copyright (c) 2018 cxw42. All rights reserved. Artistic 2.
3  
4 # Style note: Hungarian prefixes are used on scalars:
5 # "hr" (hash ref), "lr" (list ref), "sr" (string ref), "nr" (numeric ref),
6 # "dr" ("do," i.e., block ref), "ref" (unspecified ref),
7 # "b" or "is" (boolean), "s" (string)
8  
9 package XML::Axk::Core;
10 2 ▶use XML::Axk::Base qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use XML::Axk::Preparse;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 our $VERSION = '0.001006';
15  
16 =encoding UTF-8
17  
18 =head1 NAME
19  
20 XML::Axk::Core - awk-like XML processor, core
21  
22 =head1 USAGE
23  
24 my $core = XML::Axk::Core->new(\%opts);
25 $core->load_script_file($filename);
26 $core->load_script_text($source_text, $filename);
27 $core->run(@input_filenames);
28  
29 =head1 OPTIONS
30  
31 A filename of C<-> represents standard input.
32  
33 =head1 OVERVIEW
34  
35 axk coordinates languages and backends to process XML files. Backends read
36 XML input and provide it to an axk script. Languages are the way that
37 script is expressed. Languages and backends can be mixed arbitrarily,
38 as long as the backend provides the API the language needs.
39  
40 A single axk script can include code in any number of languages, but can
41 only use one backend. The first backend referenced (implicitly or
42 explicitly) is the one used.
43  
44 Each language has a default backend, but the user can specify a different
45 backend using a pragma.
46  
47 =head1 SUBROUTINES
48  
49 =head2 XML::Axk::Core->new
50  
51 Constructor. Takes a hash ref of options
52  
53 =head1 METHODS
54  
55 =cut
56  
57 # Wrapper around string eval, way up here so it can't see any of the
58 # lexicals below.
59 sub eval_nolex {
60 0 ▶ eval shift;
Subroutine eval_nolex: not called CC=1 SCAR=6.9
61 0 return $@;
62 } #eval_nolex
63  
64 2 ▶use XML::Axk::Language ();
Subroutine BEGIN: called CC=1 SCAR=0.0
65 2 ▶use XML::Axk::Sandbox;
Subroutine BEGIN: called CC=1 SCAR=0.0
66  
67 # Private vars ========================================================== {{{1
68  
69 # For giving each script a unique package name
70 my $scriptnumber = 0;
71  
72 # }}}1
73 # Loading =============================================================== {{{1
74  
75 =head2 load_script_file
76  
77 Load the named script file from disk, but do not execute it. Usage:
78  
79 $core->load_script_file(filename => $name[, ...])
80  
81 =cut
82  
83 # TODO permit specifying an Ln?
84 # @param $self
85 # @param $fn {String} Filename to load
86 sub load_script_file {
87 0 ▶ my $self = shift;
Subroutine load_script_file: not called CC=3 SCAR=24.8
88 0 my %args = @_;
89  
90 0 ▶ my $fn = $args{filename} or croak 'Need a filename';
Branch: 1 branch
BranchTrueFalseTotal
my $fn = $args{"filename"} or croak("Need a filename") 0 0 0
91 0 ▶ open(my $fh, '<', $fn) or croak "Cannot open $fn";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $fn or croak("Cannot open $fn") 0 0 0
92 0 my $contents = do { local $/; <$fh> };
93 0 close $fh;
94  
95 0 $self->load_script_text(text => $contents, filename => $fn,
96 auto_language => false);
97 # false => scripts on disk MUST specify a Ln directive. This is a
98 # design decision, so we don't have issues like Python 2/3.
99  
100 } #load_script_file
101  
102 =head2 load_script_text
103  
104 Load the given text, but do not execute it. Usage:
105  
106 $core->load_script_text(text => $text[, filename => $name][, ...])
107  
108 =cut
109  
110 # @param $self
111 # @param $text {String} The source text, **which load_script_text may modify.**
112 # @param $filename {String} Filename to use in debugging messages
113 # @param $auto_language {boolean, default false} If true, add a Ln directive for the
114 # current version if there isn't one in the script.
115 # @param $language {String} If provided, the language to use for the first
116 # chunk of the text.
117 sub load_script_text {
118 0 ▶ my $self = shift;
Subroutine load_script_text: not called CC=16 SCAR=54.9
119 0 my %args = @_;
120  
121 0 ▶ my $text = $args{text} or croak 'Need script text';
Branch: 1 branch
BranchTrueFalseTotal
my $text = $args{"text"} or croak("Need script text") 0 0 0
122 0 ▶ my $fn = $args{filename} // '(anonymous)';
Condition0%0/2
$args{"filename"} // "(anonymous)"
l!l
00
MC/DC0%0/1
$args{"filename"} // "(anonymous)"
$args{"filename"}
Truth table0%0/2
A
A= $args{"filename"}
Aresult
11
00
123  
124 0 my $curr_lang = $args{language};
125 0 my $add_Ln = $args{auto_language};
126 0 ▶ croak 'language and auto_language are mutually exclusive' if $curr_lang && $add_Ln;
Branch: 1 branch
BranchTrueFalseTotal
if $curr_lang and $add_Ln 0 0 0
Condition0%0/3
$curr_lang and $add_Ln
!ll&&!rl&&r
000
MC/DC0%0/2
$curr_lang and $add_Ln
$curr_lang $add_Ln
Truth table0%0/3
A and B
A= $curr_langB= $add_Ln
ABresult
0X0
100
111
127  
128 # Text to wrap around the script
129 0 my ($leader, $trailer) = ('', '');
130  
131 0 my $hrInitialPragmas = {};
132 0 ▶ if($add_Ln || $curr_lang) {
Branch: 1 branch
BranchTrueFalseTotal
if ($add_Ln or $curr_lang) 0 0 0
Condition0%0/3
$add_Ln or $curr_lang
l!l&&r!l&&!r
000
MC/DC0%0/2
$add_Ln or $curr_lang
$add_Ln $curr_lang
Truth table0%0/3
A or B
A= $add_LnB= $curr_lang
ABresult
1X1
011
000
133 0 ▶ $hrInitialPragmas = { L => {$curr_lang ? (name => '' . $curr_lang) : ()} };
Branch: 1 branch
BranchTrueFalseTotal
$curr_lang ? : 0 0 0
134 }
135  
136 0 my ($lrPieces, $has_lang) = XML::Axk::Preparse::pieces(\$text, $hrInitialPragmas);
137  
138 0 ▶ unless($has_lang || $curr_lang) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_lang or $curr_lang) 0 0 0
Condition0%0/3
$has_lang or $curr_lang
l!l&&r!l&&!r
000
MC/DC0%0/2
$has_lang or $curr_lang
$has_lang $curr_lang
Truth table0%0/3
A or B
A= $has_langB= $curr_lang
ABresult
1X1
011
000
139 0 ▶ if($add_Ln) {
Branch: 1 branch
BranchTrueFalseTotal
if ($add_Ln) { } 0 0 0
140 0 $lrPieces->[0]->{pragmas}->{L}->{digits} = 1; # default language
141 } else {
142 0 die "No language (Ln) specified in file $fn";
143 }
144 }
145  
146 0 my $srNewText = XML::Axk::Preparse::assemble($fn, $lrPieces);
147 0 $text = $$srNewText;
148  
149 0 ▶ $text .= "\n" unless substr($text, length($text)-1) eq "\n";
Branch: 1 branch
BranchTrueFalseTotal
unless substr($text, length($text) - 1) eq "\n" 0 0 0
150  
151 # Mark the filename for the sake of error messages.
152 0 $leader .= ";\n#line 1 \"$fn\"\n";
153 # Extra ; so the #line directive is in its own statement.
154 # Thanks to https://www.effectiveperlprogramming.com/2011/06/set-the-line-number-and-filename-of-string-evals/
155  
156 # Put the user's script in its own package, with its own sandbox
157 0 ++$scriptnumber;
158 0 my $scriptname = SCRIPT_PKG_PREFIX . $scriptnumber;
159 0 my $sandbox = XML::Axk::Sandbox->new($self, $scriptname);
160  
161 { # preload the sandbox into the script's package
162 2 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.2
163 0 ${"${scriptname}::_AxkSandbox"} = $sandbox;
164 }
165  
166 0 $leader = "package $scriptname {\n" .
167 "use XML::Axk::Base;\n" .
168 $leader;
169 0 $trailer .= "\n;};\n";
170  
171 0 $text = ($leader . $text . $trailer);
172  
173 0 ▶ if($self->{options}->{SHOW} && ref $self->{options}->{SHOW} eq 'ARRAY' &&
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"options"}{"SHOW"} and ref $self->{"options"}{"SHOW"} eq "ARRAY" and &any(sub { $_ eq "source"; } , @{$$self{"options"}{"SHOW"};})) 0 0 0
Condition0%0/6
$self->{"options"}{"SHOW"} and ref $self->{"options"}{"SHOW"} eq "ARRAY" and &any(sub { $_ eq "source"; } , @{$$self{"options"}{"SHOW"};})
!ll&&!rl&&r
000
$self->{"options"}{"SHOW"} and ref $self->{"options"}{"SHOW"} eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/3
$self->{"options"}{"SHOW"} and ref $self->{"options"}{"SHOW"} eq "ARRAY" and &any(sub { $_ eq "source"; } , @{$$self{"options"}{"SHOW"};})
$self->{"options"}{"SHOW"} ref $self->{"options"}{"SHOW"} eq "ARRAY" &any(sub { $_ eq "source"; } , @{$$self{"options"}{"SHOW"};})
Truth table0%0/4
A and B and C
A= $self->{"options"}{"SHOW"}B= ref $self->{"options"}{"SHOW"} eq "ARRAY"C= &any(sub { $_ eq "source"; } , @{$$self{"options"}{"SHOW"};})
ABCresult
0XX0
10X0
1100
1111
174 0 ▶ any {$_ eq 'source'} @{$self->{options}->{SHOW}}) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
175 0 say "****************Loading $fn:\n$text\n****************";
176 }
177  
178 # TODO? un-taint the source text so we can run under -T
179 0 my $at = eval_nolex $text;
180 0 ▶ croak "Could not parse '$fn': $at" if $at;
Branch: 1 branch
BranchTrueFalseTotal
if $at 0 0 0
181 } #load_script_text
182  
183 # }}}1
184 # Running =============================================================== {{{1
185  
186 sub _run_pre_file {
187 0 ▶ my ($self, $infn) = @_ or croak("Need a filename");
Subroutine _run_pre_file: not called CC=4 SCAR=30.0
Branch: 1 branch
BranchTrueFalseTotal
my($self, $infn) = or croak("Need a filename") 0 0 0
188  
189 0 foreach my $drAction (@{$self->{pre_file}}) {
190 0 eval { &$drAction($infn) }; # which context are they evaluated in?
191 0 ▶ croak "pre_file: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
192 }
193 } # _run_pre_file
194  
195 sub _run_post_file {
196 0 ▶ my ($self, $infn) = @_ or croak("Need a filename");
Subroutine _run_post_file: not called CC=4 SCAR=30.0
Branch: 1 branch
BranchTrueFalseTotal
my($self, $infn) = or croak("Need a filename") 0 0 0
197  
198 0 foreach my $drAction (@{$self->{post_file}}) {
199 # TODO? make the last-seen node available to the action?
200 # Similar to awk, in which the END block sees the last line as $0.
201 0 eval { &$drAction($infn) }; # which context are they evaluated in?
202 0 ▶ croak "post_file: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
203 }
204 } # _run_post_file
205  
206 # _run_worklist
207 sub _run_worklist {
208 0 ▶ my $self = shift;
Subroutine _run_worklist: not called CC=7 SCAR=40.3
209 0 my $now = shift; # $now = HI, BYE, or CIAO
210  
211 0 my %CPs = ( # Core parameters
212 NOW => $now,
213 @_
214 );
215  
216 # Assign the SPs from the CPs --
217  
218 0 ▶ while (my ($lang, $drUpdater) = each %{$self->{updaters}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$$self{"updaters"};}) 0 0 0
219 0 $drUpdater->($self->{sp}->{$lang}, %CPs);
220 }
221  
222 # Run the worklist -------------
223  
224 0 foreach my $lrItem (@{$self->{worklist}}) {
225 #say Dumper($lrItem);
226 0 my ($refPattern, $refAction, $when) = @$lrItem;
227 #say "At time $now: running ", Dumper($lrItem);
228  
229 0 ▶ next if $when && ($now != $when); # CIAO is the only falsy one
Branch: 1 branch
BranchTrueFalseTotal
if $when and $now != $when 0 0 0
Condition0%0/3
$when and $now != $when
!ll&&!rl&&r
000
MC/DC0%0/2
$when and $now != $when
$when $now != $when
Truth table0%0/3
A and B
A= $whenB= $now != $when
ABresult
0X0
100
111
230  
231 0 ▶ next unless $refPattern->test(\%CPs);
Branch: 1 branch
BranchTrueFalseTotal
unless $refPattern->test(\%CPs) 0 0 0
232 # Matchers use CPs so they are independent of language.
233  
234 0 eval { &$refAction }; # which context are they evaluated in?
235 0 ▶ die "action: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
236 } #foreach worklist item
237 } #_run_worklist
238  
239 sub run_sax_fh {
240 my ($self, $fh, $infn) = @_ or croak("Need a filehandle and filename");
241 my $runner;
242 eval {
243 2 ▶ use XML::Axk::SAX::Runner;
Subroutine BEGIN: called CC=1 SCAR=2.6
244 $runner = XML::Axk::SAX::Runner->new($self);
245 };
246 die $@ if $@;
247  
248 $self->_run_pre_file($infn);
249 $runner->run($fh, $infn);
250 $self->_run_post_file($infn);
251  
252 } #run_sax_fh()
253  
254 =head2 run
255  
256 Run the loaded script or scripts. Takes a list of inputs. Strings are treated
257 as filenames; references to strings are treated as raw data to be run
258 as if read off disk. A filename of '-' represents STDIN. To process a
259 disk file named '-', read its contents first and pass them in as a ref.
260  
261 =cut
262  
263 sub run {
264 my $self = shift;
265  
266 #say "SPs:\n", Dumper(\%XML::Axk::Language::SP_Registry);
267  
268 foreach my $drAction (@{$self->{pre_all}}) {
269 eval { &$drAction }; # which context are they evaluated in?
270 croak "pre_all: $@" if $@;
271 }
272  
273 foreach my $infn (@_) {
274 my $fh;
275 #say "Processing $infn";
276  
277 # TODO? Clear the SPs before each file for consistency?
278  
279 # For now, just process lines rather than XML nodes.
280 if($infn eq '-') { # stdin
281 open($fh, '<-') or croak "Can't open stdin: $!";
282 } else { # disk file
283 open($fh, "<", $infn) or croak "Can't open $infn: $!";
284 # if $infn is a reference, its contents will be used -
285 # http://www.perlmonks.org/?node_id=745018
286 }
287  
288 $self->run_sax_fh($fh, $infn); # TODO permit selecting DOM mode
289  
290 close($fh) or warn "close failed: $!";
291  
292 } #foreach input filename
293  
294 foreach my $drAction (@{$self->{post_all}}) {
295 # TODO? pass the last-seen node? (see note above)
296 eval { &$drAction }; # which context are they evaluated in?
297 croak "post_all: $@" if $@;
298 }
299  
300 } #run()
301  
302 # }}}1
303 # Constructor and accessors ============================================= {{{1
304  
305 sub _globalname { # static int->str
306 my $idx = shift;
307 return "XML::Axk::Core::_I${idx}";
308 } #_globalname()
309  
310 # For giving each instance of Core a unique package name (_globalname)
311 my $_instance_number = 0;
312  
313 sub new {
314 my $class = shift;
315 my $hrOpts = shift // {};
316  
317 # Create the instance.
318 my $data = {
319 _id => ++$_instance_number,
320 options => $hrOpts,
321  
322 # Load these in the order they are defined in the scripts.
323 pre_all => [], # List of \& to run before reading the first file
324 pre_file => [], # List of \& to run before reading each file
325 worklist => [], # List of [$refCondition, \&action, $when] to be run against each node.
326 post_file => [], # List of \& to run after reading each file
327 post_all => [], # List of \& to run after reading the last file
328  
329 # Script parameters, indexed by language name (X::A::L::Ln).
330 # Format: { lang name => { varname with sigil => value, ... }, ... }
331 sp => {},
332  
333 # Per-language updaters, indexed by language name
334 updaters => {},
335  
336 };
337 my $self = bless($data, $class);
338  
339 # Load this instance into the global namespace so the Ln packages can
340 # get at it
341 do {
342 no strict 'refs';
343 ${_globalname($_instance_number)} = $self;
344 };
345  
346 return $self;
347 } #new()
348  
349 # Allocate the SPs for a particular language.
350 # All the SPs must be given in one call. Subsequent calls are nops.
351 sub allocate_sps {
352 my $self = shift;
353 my $lang = shift;
354 return if exists $self->{sp}->{$lang};
355 my $hr = $self->{sp}->{$lang} = {};
356  
357 for my $name (@_) {
358 my $sigil = substr($name, 0, 1);
359 $self->{sp}->{$lang}->{$name} = undef, next if $sigil eq '$';
360 $self->{sp}->{$lang}->{$name} = [], next if $sigil eq '@';
361 }
362  
363 #say Dumper \%{$self->{sp}};
364 } #allocate_sp()
365  
366 sub set_updater {
367 my $self = shift;
368 my $lang = shift;
369 return if exists $self->{updaters}->{$lang};
370 $self->{updaters}->{$lang} = shift // sub {};
371 } #set_updater()
372  
373 # RO accessors
374 sub id {
375 return shift->{_id};
376 }
377  
378 sub global_name {
379 return _globalname(shift->{_id});
380 }
381  
382 # }}}1
383  
384 # No import() --- callers should refer to the symbols with their
385 # fully- qualified names.
386 1;
387 # === Documentation ===================================================== {{{1
388  
389 =pod
390  
391 =head1 AUTHOR
392  
393 Christopher White, C<cxwembedded at gmail.com>
394  
395 =head1 SUPPORT
396  
397 You can find documentation for this module with the perldoc command.
398  
399 perldoc XML::Axk::Core
400  
401 You can also look for information at:
402  
403 =over 4
404  
405 =item * GitHub: The project's main repository and issue tracker
406  
407 L<https://github.com/cxw42/axk>
408  
409 =item * RT: CPAN's request tracker
410  
411 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=XML-Axk>
412  
413 =back
414  
415 =head1 NOTE
416  
417 I just recently found out about L<Web::Scraper>, which has some overlapping
418 functionality. However, XML::Axk is targeted specifically at XML, rather
419 than HTML, and should eventually support dedicated, non-Perl script languages.
420  
421 =head1 LICENSE AND COPYRIGHT
422  
423 Copyright (c) 2018 Christopher White. All rights reserved.
424  
425 This program is free software; you can redistribute it and/or modify it
426 under the terms of the the Artistic License (2.0). Details are in the LICENSE
427 file accompanying this distribution.
428  
429 =cut
430  
431 # }}}1
432 # vi: set ts=4 sts=4 sw=4 et ai fo=cql foldmethod=marker foldlevel=0: #
« Axk/Language.pm ↑ Summary Axk/Sandbox.pm »