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