blib/lib/Decl/Parser.pm

filter: Statementstmt 88.0% 229 / 260 Branchbran 76.4% 107 / 140 Conditioncond 66.6% 22 / 33 MC/DCmcdc 50.0% 10 / 20 Subroutinesub 87.0% 47 / 54 Podpod 100% 31 / 31 totaltotal 82.9% 446 / 538 CC 90 SCAR 18.6
CC
90
Cov
83%
debug_next_token
30.0
anything
20.0
__ANON__
14.0
CRAP 6.4
« blib/lib/Decl/Semantics/Code.pm ↑ Summary blib/lib/Decl.pm »
1 package Decl::Parser;
2
3 13 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 13 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 13 ▶use Decl::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 13 ▶use Iterator::Simple qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 13 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 13 ▶use Text::Balanced qw(extract_codeblock);
Subroutine BEGIN: called CC=1 SCAR=0.0
9
10 =head1 NAME
11
12 Decl::Parser - implements a parser to be defined using Decl::Semantics::Parse.
13
14 =head1 VERSION
15
16 Version 0.01
17
18 =cut
19
20 13 our $VERSION = '0.01';
21
22
23 =head1 SYNOPSIS
24
25 The L<Decl::Semantics::Parse> module uses the structure of a "parse" tag to build a parser. The parser it builds, though,
26 is implemented using this class. And in fact this class also exposes a procedural API for building parsers, if you need to bypass the
27 parser builder. It's the work of but a moment to realize that you need to bypass the parser builder when building a parser to parse parser
28 specifications. (If you could parse I<that>, I'm impressed.)
29
30 The idea is to build this parser with as few external dependencies as possible. Then it might be useful outside the framework as well.
31
32 These parsers are based on those in Mark Jason Dominus' fantastic book I<Higher-Order Perl>. They consist of a tokenizer that is a chain
33 of lesser tokenizers, registered actions that can be carried out on intermediate parses, and rules that build structure from a sequence
34 of tokens.
35
36 =head2 new()
37
38 Instantiates a blank parser.
39
40 =cut
41
42 40 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
43 40 my $class = shift;
44 40 return bless {
45 tokenizers => [],
46 lexer => undef,
47 actions => {},
48 rules => {},
49 rulelist => [],
50 cmps => {},
51 parser => undef,
52 user => {}, # A place to stash action-specific data gleaned from input or ... wherever.
53 }, $class;
54 }
55
56 =head1 BUILDING THE PARSER
57
58 To build a parser, we add tokenizers, rules, and actions.
59
60 =head2 add_tokenizer()
61
62 Each parser has a tokenizer, which is a list of atomic tokenizers consisting of regular expressions to examine incoming text and spit it back
63 out in categorized chunks of low-level meaning.
64
65 Each atomic tokenizer consists of a label, a regex pattern, and an optional callback to be called to produce the token. Intervening text that
66 does not match the token's pattern is passed through unchanged, allowing later tokenizers in the chain to break that up.
67
68 The C<add_tokenizer> function just pushes an atomic tokenizer onto the list. Later, C<lexer> is called to tie those all together into a full
69 lexer.
70
71 Possible extension: C<$pattern> could be a coderef instead of a string, to permit more flexibility in the design of tokenizers.
72
73 =cut
74
75 301 ▶sub add_tokenizer {
Subroutine add_tokenizer: called CC=2 SCAR=6.9
Pod documented
76 301 my ($self, $label, $pattern, $handler) = @_;
77
78 301 ▶ push @{$self->{tokenizers}}, [$label, $pattern, $handler ? $handler : sub { [ $_[1], $_[0] ] }];
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$handler ? : 26 275 301
79 }
80
81 =head2 action()
82
83 Adds a named action to the list of actions that can be integrated into the parser. Also used to retrieve a named action.
84
85 =cut
86
87 4217 ▶sub action {
Subroutine action: called CC=2 SCAR=6.9
Pod documented
88 4217 my ($self, $name, $action) = @_;
89
90 4217 ▶ $self->{actions}->{$name} = $action if defined $action;
Branch: 1 branch
BranchTrueFalseTotal
if defined $action 65 4152 4217
91 4217 $self->{actions}->{$name};
92 }
93
94 =head2 add_rule($name, $rule), get_rule($name), list_rules(), clear_rule($name);
95
96 The C<add_rule> function adds a rule. The rule is expressed in a sort of restricted Perl to assemble the available parser atoms into something useful.
97 Rule cross-references
98 can be indicated by enclosing the name of the rule in angle brackets <>; that will be substituted by a reference to a parser built with that rule. The purpose
99 of this API is to provide a simple but procedural way to assemble a basic parser - one that we can then use to parse our declarative structures.
100
101 The target Perl code again leans heavily on Dominus, with some extensions and simplifications to make things easier in our context.
102
103 Multiple rules added under the same name will be considered alternatives, and treated as such when the parser is built.
104
105 The C<clear_rule> function clears the information associated with a rule name. I'm not sure it will ever be used, but it just seems so easy that it would
106 be silly not to put it in here. It does I<not> delete the rule from the list of rules, so the rule's precedence (if any) will be unchanged.
107
108 =cut
109
110 247 ▶sub add_rule {
Subroutine add_rule: called CC=2 SCAR=7.0
Pod documented
111 247 my ($self, $name, $rule) = @_;
112 247 $self->{rules}->{$name} = $rule;
113 247 $self->{cmps}->{$name} = $self->make_component('', '\&nothing');
114 247 ▶ push @{$self->{rulelist}}, $name unless grep { $_ eq $name} @{$self->{rulelist}};
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $name;} @{$$self{"rulelist"};} 247 0 247
115 }
116 2161 ▶sub list_rules { @{$_[0]->{rulelist}} }
Subroutine list_rules: called CC=1 SCAR=0.0
Pod documented
117 247 ▶sub get_rule { $_[0]->{rules}->{$_[1]} }
Subroutine get_rule: called CC=1 SCAR=0.0
Pod documented
118 0 ▶sub clear_rule {
Subroutine clear_rule: not called CC=1 SCAR=6.9
Pod documented
119 0 my ($self, $name) = @_;
120 0 $self->{rules}->{$name} = [];
121 0 $self->{cmps}->{$name} = $self->make_component('', '\&nothing');
122 }
123
124 =head1 USING THE PARSER
125
126 =head2 lexer($input), _t()
127
128 The C<lexer> function creates a lexer using the list of tokenizers already registered, using the input stream provided. The lexer is an iterator, with a peek function to
129 check the next token without consuming it. Tokens are arrayrefs or plain strings.
130
131 This leans heavily on Dominus.
132
133 Note that the input may itself be a token stream.
134
135 If called in a list context, returns the full list of tokens instead of an iterator. I hope that's what you wanted.
136
137 The C<_t> function does most of the heavy lifting, and *really* leans on Dominus. I've extended his lexer framework with two features: first, if a lexer
138 is simply passed a string as its input, it will still work, by creating a single-use interator. Second, token labels that end in an asterisk are filtered
139 out of the final token string.
140
141 Dominus's framework provides for suppression of tokens using the token building function (e.g. sub {''} to suppress whitespace in the outgoing token stream),
142 but there's a surprising problem with that approach - if the resulting stream is fed into the next atomic tokenizer in a chain, neighboring unparsed text
143 will be pushed back together! This is a natural result of the fact that blockwise reading of files needs to be supported without breaking tokens that span
144 block boundaries; the final tokenizer in the chain necessarily treats the output of earlier tokenizers like blocks.
145
146 But what if I want to tokenize into whitespace first, then, say, find all words starting with 't' and treat them as special tokens? OK, so this was a silly
147 test case, and yet it seems intuitively to be something like what I'd want to do in some situations. The naive approach is this:
148
149 parse t
150 tokens
151 WHITESPACE "\s+" { "" }
152 TWORDS "^t.*"
153
154 If I give that the string "this is a test string", I don't get five tokens, two of which are TWORDS. I get one TWORD token with the value
155 "thisisateststring". That is because by swallowing the "tokenicity" of the whitespace, we're actually just ignoring the whitespace.
156
157 Bad!
158
159 So instead, we put an asterisk on the whitespace specification, so that it will be suppressed I<after> the tokenizing process is complete, that is, at
160 the end of the tokenizer chain. In the meantime, though, the whitespace tokens are still there to hold their place in the queue.
161
162 parse t
163 tokens
164 WHITESPACE* "\s+"
165 TWORDS "^t.*"
166
167 =cut
168
169 2107 ▶sub lexer {
Subroutine lexer: called CC=6 SCAR=17.9
Pod documented
170 2107 my ($self, $input) = @_;
171
172 2107 ▶ return $self->tokens($input) if wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if wantarray 3 2104 2107
173
174 2104 my @tokenizers = @{$self->{tokenizers}};
175 2104 ▶ while (@tokenizers) {
Branch: 1 branch
BranchTrueFalseTotal
if (@tokenizers) 16473 2104 18577
176 16473 my $t = shift @tokenizers;
177
178 16473 ▶ if ($t->[0] eq 'CODEBLOCK') {
Branch: 1 branch
BranchTrueFalseTotal
if ($t->[0] eq "CODEBLOCK") 1002 15471 16473
179 1002 ▶ my $pattern = $t->[1] || "{}";
Condition100%2/2
$t->[1] || '{}'
l!l
99012
MC/DC100%1/1
$t->[1] || '{}'
$t->[1]
Truth table100%2/2
A
A= $t->[1]
Aresult
11
00
180 1002 my $prefix = "[^\\" . substr($pattern,0,1) . "]*";
181 1002 ▶ $t->[1] = sub { my @r = eval { extract_codeblock ($_[0], $pattern, $prefix) }; defined $r[0] && $r[0] ne '' ? ($r[2], $r[0], $r[1]) : $_[0] } unless ref $pattern;
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 2 branches
BranchTrueFalseTotal
unless ref $pattern 12 990 1002
defined $r[0] && $r[0] ne '' ? : 9 1995 2004
Condition66%2/3
defined $r[0] and $r[0] ne ""
!ll&&!rl&&r
199509
MC/DC50%1/2
defined $r[0] and $r[0] ne ""
defined $r[0] $r[0] ne ""
Truth table66%2/3
A and B
A= defined $r[0]B= $r[0] ne ""
ABresult
0X0
100
111
182 }
183 16473 $input = _t($input, @$t);
184 }
185 3974 ▶ ifilter $input, sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
186 3974 ▶ return $_ unless ref $_;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $_ 2158 1816 3974
187 1816 ▶ return $_ unless $$_[0] =~ /\*$/; # Skip tokens whose labels end in *.
Branch: 1 branch
BranchTrueFalseTotal
unless $_->[0] =~ /\*$/ 931 885 1816
188 885 return;
189 }
190 2104 }
191
192 16473 ▶sub _t {
Subroutine _t: called CC=3 SCAR=11.0
193 16473 my ($input, $label, $pattern, $handler) = @_;
194 16473 my @tokens;
195 16473 my $buf = '';
196 16473 ▶ unless (ref $input) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $input) 2104 14369 16473
197 2104 $input = iter ([$input]); # Make $input iterable if it's just a string.
198 }
199 16473 my $split = $pattern;
200 16473 ▶ $split = sub { split /($pattern)/, $_[0] } unless ref $pattern;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pattern 15471 1002 16473
201 35070 ▶ iterator {
Subroutine __ANON__: called CC=14 SCAR=26.4
202 35070 ▶ while (@tokens == 0 && defined $buf) {
Branch: 1 branch
BranchTrueFalseTotal
if (@tokens == 0 and defined $buf) 33219 28934 62153
Condition100%3/3
@tokens == 0 and defined $buf
!ll&&!rl&&r
125661636833219
MC/DC100%2/2
@tokens == 0 and defined $buf
@tokens == 0 defined $buf
Truth table100%3/3
A and B
A= @tokens == 0B= defined $buf
ABresult
0X0
100
111
203 33219 my $i = $input->();
204
205 33219 ▶ if (ref $i) { # $i is itself a token!
Branch: 1 branch
BranchTrueFalseTotal
if (ref $i) 6136 27083 33219
206 6136 my ($sep, $tok) = $split->($buf);
207 6136 ▶ $tok = $handler->($tok, $label) if defined $tok;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tok 235 5901 6136
208 6136 ▶ push @tokens, grep defined && $_ ne "", $sep, $tok, $i;
Condition100%3/3
defined $_ && $_ ne ''
!ll&&!rl&&r
8417439948
MC/DC100%2/2
defined $_ && $_ ne ''
defined $_ $_ ne ''
Truth table100%3/3
A && B
A= defined $_B= $_ ne ''
ABresult
0X0
100
111
209 6136 $buf = "";
210 6136 last;
211 }
212
213 # $i is just a bunch of new text.
214 27083 ▶ $buf .= $i if defined $i;
Branch: 1 branch
BranchTrueFalseTotal
if defined $i 10696 16387 27083
215 27083 my @newtoks = $split->($buf);
216 27083 ▶ while (@newtoks > 2 || @newtoks && ! defined $i) {
Branch: 1 branch
BranchTrueFalseTotal
if (@newtoks > 2 or @newtoks and not defined $i) 8161 27083 35244
Condition100%6/6
@newtoks > 2 or @newtoks and not defined $i
l!l&&r!l&&!r
1088707327083
@newtoks and not defined $i
!ll&&!rl&&r
16387106967073
MC/DC100%3/3
@newtoks > 2 or @newtoks and not defined $i
@newtoks > 2 @newtoks not defined $i
Truth table100%4/4
A or B and not(C)
A= @newtoks > 2B= @newtoksC= not defined $i
ABCresult
1XX1
0111
00X0
0100
217 8161 push @tokens, shift(@newtoks);
218 8161 ▶ push @tokens, $handler->(shift(@newtoks), $label) if @newtoks;
Branch: 1 branch
BranchTrueFalseTotal
if @newtoks 1587 6574 8161
219 }
220 27083 $buf = join '', @newtoks;
221 27083 ▶ undef $buf if ! defined $i;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $i 16387 10696 27083
222 27083 @tokens = grep $_ ne "", @tokens;
223 }
224 35070 ▶ return (defined $_[0] and $_[0] eq 'peek') ? $tokens[0] : shift (@tokens);
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] && $_[0] eq 'peek' ? : 0 35070 35070
Condition33%1/3
defined $_[0] and $_[0] eq "peek"
!ll&&!rl&&r
3507000
MC/DC0%0/2
defined $_[0] and $_[0] eq "peek"
defined $_[0] $_[0] eq "peek"
Truth table33%1/3
A and B
A= defined $_[0]B= $_[0] eq "peek"
ABresult
0X0
100
111
225 }
226 16473 }
227
228
229 =head2 tokens($input)
230
231 If you know you've got a limited number of tokens and just want to grab the whole list, use C<tokens>, which just returns a list.
232
233 =cut
234
235 4 ▶sub tokens {
Subroutine tokens: called CC=2 SCAR=6.9
Pod documented
236 4 my ($self, $input) = @_;
237 4 my $lexer = $self->lexer ($input);
238 4 my @list = ();
239 4 ▶ while (defined (my $t = $lexer->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $t = &$lexer())) 33 4 37
240 33 push @list, $t;
241 }
242 4 return @list;
243 }
244
245 =head2 tokenstream($input)
246
247 Finally, if you need a lazily evaluated stream for your token output (and hey, who doesn't?) call tokenstream. (Note: you'll want a stream
248 if you're passing your lexer to a recursive-descent parser as below, because you need to be able to unwind the stream if one of your rules doesn't
249 match.)
250
251 =cut
252
253 2099 ▶sub tokenstream {
Subroutine tokenstream: called CC=1 SCAR=0.0
Pod documented
254 2099 my ($self, $input) = @_;
255 2099 my $lexer = $self->lexer ($input);
256 2099 lazyiter ($lexer);
257 }
258
259 =head2 PARSER COMPONENTS: parser, nothing, anything, end_of_input, token, token_silent, literal, word, p_and, p_or, series, one_or_more, list_of, optional, debug, debug_next_token
260
261 These are not methods; they're functions. They are the little subparsers that we hack together to make a full parser. The output of each of these
262 parsers is an arrayref containing a flat list of tokens it has matched in the token stream it's given as input. Each token is itself an arrayref of
263 two parts (a cons pair), with the first being the type, and second the token value. Bare words surviving the lexer are converted into individual
264 tokens of type '' (empty string), allowing tokens to be treated uniformly.
265
266 =cut
267
268 1702 ▶sub parser (&) { $_[0] }
Subroutine parser: called CC=1 SCAR=0.0
Pod documented
269 9271 ▶sub nothing {
Subroutine nothing: called CC=1 SCAR=0.0
Pod documented
270 9271 my $input = shift;
271 9271 return (undef, $input);
272 }
273 0 ▶sub debug {
Subroutine debug: not called CC=2 SCAR=17.9
Pod documented
274 0 my $message = shift;
275 0 ▶ return \&nothing unless $message;
Branch: 1 branch
BranchTrueFalseTotal
unless $message 0 0 0
276 0 ▶ my $parser = parser {
Subroutine __ANON__: not called CC=1 SCAR=6.9
277 0 my $input = shift;
278 0 print STDERR $message;
279 0 return (undef, $input);
280 }
281 0 }
282 0 ▶sub debug_next_token {
Subroutine debug_next_token: not called CC=5 SCAR=34.0
Pod documented
283 0 my $input = shift;
284 0 print STDERR "at this point the input stream is:\n" . Dumper($input);
285 0 ▶ if (not defined $input) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $input) { } 0 0 0
286 0 print STDERR "no more tokens\n";
287 } else {
288 0 my $next = car($input);
289 0 ▶ if (not defined $next) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $next) { } 0 0 0
290 0 print STDERR "car(input) is not defined\n";
291 } else {
292 0 ▶ my $carn = car($next) || '<undefined>';
Condition0%0/2
&car($next) || '<undefined>'
l!l
00
MC/DC0%0/1
&car($next) || '<undefined>'
&car($next)
Truth table0%0/2
A
A= &car($next)
Aresult
11
00
293 0 ▶ my $cdrn = cdr($next) || '<undefined>';
Condition0%0/2
&cdr($next) || '<undefined>'
l!l
00
MC/DC0%0/1
&cdr($next) || '<undefined>'
&cdr($next)
Truth table0%0/2
A
A= &cdr($next)
Aresult
11
00
294 0 print STDERR "next token: ['$carn', '$cdrn']\n";
295 }
296 }
297 0 return (undef, $input);
298 }
299 996 ▶sub end_of_input {
Subroutine end_of_input: called CC=2 SCAR=6.9
Pod documented
300 996 my $input = shift;
301 996 ▶ defined($input) ? () : (undef, undef);
Branch: 1 branch
BranchTrueFalseTotal
defined $input ? : 5 991 996
302 }
303 110 ▶sub token {
Subroutine token: called CC=2 SCAR=7.0
Pod documented
304 110 my $wanted = shift;
305 110 ▶ $wanted = [$wanted] unless ref $wanted;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $wanted 16 94 110
306 4844 ▶ my $parser = parser {
Subroutine __ANON__: called CC=8 SCAR=21.0
307 4844 my $input = shift;
308 4844 ▶ return unless defined $input;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $input 4547 297 4844
309 297 my $next = car($input);
310 297 ▶ return unless defined $next;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $next 0 297 297
311 297 ▶ return unless ref $next;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $next 9 288 297
312 288 for my $i (0 .. $#$wanted) {
313 288 ▶ next unless defined $wanted->[$i];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $wanted->[$i] 0 288 288
314 288 ▶ return unless $wanted->[$i] eq $next->[$i];
Branch: 1 branch
BranchTrueFalseTotal
unless $wanted->[$i] eq $next->[$i] 66 222 288
315 }
316 222 ▶ $next = ['', $next] unless ref $next;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $next 0 222 222
317 222 return ($next, cdr($input));
318 110 };
319
320 110 return $parser;
321 }
322 249 ▶sub token_silent {
Subroutine token_silent: called CC=2 SCAR=7.0
Pod documented
323 249 my $wanted = shift;
324 249 ▶ $wanted = [$wanted] unless ref $wanted;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $wanted 41 208 249
325 4362 ▶ my $parser = parser {
Subroutine __ANON__: called CC=8 SCAR=21.0
326 4362 my $input = shift;
327 4362 ▶ return unless defined $input;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $input 3125 1237 4362
328 1237 my $next = car($input);
329 1237 ▶ return unless defined $next;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $next 0 1237 1237
330 1237 ▶ return unless ref $next;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $next 8 1229 1237
331 1229 for my $i (0 .. $#$wanted) {
332 1229 ▶ next unless defined $wanted->[$i];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $wanted->[$i] 0 1229 1229
333 1229 ▶ return unless $wanted->[$i] eq $next->[$i];
Branch: 1 branch
BranchTrueFalseTotal
unless $wanted->[$i] eq $next->[$i] 534 695 1229
334 }
335 695 ▶ $next = ['', $next] unless ref $next;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $next 0 695 695
336 695 return (undef, cdr($input));
337 249 };
338
339 249 return $parser;
340 }
341 7 ▶sub literal {
Subroutine literal: called CC=1 SCAR=0.0
Pod documented
342 7 my $wanted = shift;
343 33 ▶ my $parser = parser {
Subroutine __ANON__: called CC=6 SCAR=17.9
344 33 my $input = shift;
345 33 ▶ return unless defined $input;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $input 4 29 33
346 29 my $next = car($input);
347 29 ▶ return unless defined $next;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $next 0 29 29
348 29 my $value;
349 29 ▶ if (ref $next) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $next) { } 24 5 29
350 24 $value = $next->[1];
351 } else {
352 5 $value = $next;
353 }
354 29 ▶ return unless $value eq $wanted;
Branch: 1 branch
BranchTrueFalseTotal
unless $value eq $wanted 3 26 29
355 26 ▶ $next = ['', $next] unless ref $next;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $next 3 23 26
356 26 return ($next, cdr($input));
357 7 };
358
359 7 return $parser;
360 }
361 5050 ▶sub word { # Need this for undecorated, non-token text.
Subroutine word: called CC=4 SCAR=13.9
Pod documented
362 5050 my $input = shift;
363 5050 ▶ return unless defined $input;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $input 2456 2594 5050
364 2594 my $next = car($input);
365 2594 ▶ return unless defined $next;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $next 0 2594 2594
366 2594 ▶ return if ref $next;
Branch: 1 branch
BranchTrueFalseTotal
if ref $next 417 2177 2594
367 2177 return (['', $next], cdr($input));
368 }
369 0 ▶sub anything {
Subroutine anything: not called CC=4 SCAR=30.0
Pod documented
370 0 my $input = shift;
371 0 ▶ return unless defined $input;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $input 0 0 0
372 0 my $next = car($input);
373 0 ▶ return unless defined $next;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $next 0 0 0
374 0 ▶ return ($next, cdr($input)) if ref $next;
Branch: 1 branch
BranchTrueFalseTotal
if ref $next 0 0 0
375 0 return (['', $next], cdr($input));
376 }
377 472 ▶sub p_and {
Subroutine p_and: called CC=2 SCAR=6.9
Pod documented
378 472 my @p = @_;
379 472 ▶ return \&nothing if @p == 0;
Branch: 1 branch
BranchTrueFalseTotal
if @p == 0 0 472 472
380
381 18730 ▶ my $parser = parser {
Subroutine __ANON__: called CC=7 SCAR=19.5
382 18730 my $input = shift;
383 18730 my $v;
384 my @values;
385 18730 for (@p) {
386 30009 ▶ ($v, $input) = $_->($input) or return;
Branch: 1 branch
BranchTrueFalseTotal
($v, $input) = &$_($input) or return 15502 14507 30009
387 15502 ▶ if (ref car($v)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref &car($v)) { } 1272 14230 15502
388 1272 foreach (@$v) {
389 3729 ▶ push @values, $_ if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 3729 0 3729
390 }
391 } else {
392 14230 ▶ push @values, $v if defined $v;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v 3273 10957 14230
393 }
394 }
395 4223 return (\@values, $input);
396 }
397 472 }
398 289 ▶sub p_or {
Subroutine p_or: called CC=3 SCAR=11.1
Pod documented
399 289 my @p = @_;
400 0 ▶ return parser { return () } if @p == 0;
Subroutine __ANON__: not called CC=1 SCAR=1.2
Branch: 1 branch
BranchTrueFalseTotal
if @p == 0 0 289 289
401 289 ▶ return $p[0] if @p == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @p == 1 0 289 289
402 13542 ▶ my $parser = parser {
Subroutine __ANON__: called CC=3 SCAR=11.0
403 13542 my $input = shift;
404 13542 my ($v, $newinput);
405 13542 for (@p) {
406 24708 ▶ if (($v, $newinput) = $_->($input)) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = &$_($input)) 12765 11943 24708
407 12765 return ($v, $newinput);
408 }
409 }
410 777 return;
411 }
412 289 }
413 105 ▶sub series { # TODO: long series (like, oh, series of lines in a parsed body of over 150 lines or so) generate deep recursion warnings.
Subroutine series: called CC=1 SCAR=0.0
Pod documented
414 # So this is elegant - but not a good solution. Instead, we should collect matches until one doesn't match, i.e.
415 # make "series" a primary parser instead of relying on and/or.
416 105 my $p = shift;
417 105 my $p_star;
418 105 ▶ $p_star = p_or(p_and($p, parser {$p_star->(@_) }), \&nothing);
Subroutine __ANON__: called CC=1 SCAR=0.0
419 }
420 39 ▶sub one_or_more {
Subroutine one_or_more: called CC=1 SCAR=0.0
Pod documented
421 39 my $p = shift;
422 39 p_and ($p, series($p));
423 }
424 42 ▶sub list_of {
Subroutine list_of: called CC=6 SCAR=18.0
Pod documented
425 42 my ($element, $separator) = @_;
426 42 ▶ if (defined $separator and not ref $separator) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $separator and not ref $separator) 41 1 42
Condition66%2/3
defined $separator and not ref $separator
!ll&&!rl&&r
1041
MC/DC50%1/2
defined $separator and not ref $separator
defined $separator not ref $separator
Truth table66%2/3
A and not(B)
A= defined $separatorB= not ref $separator
ABresult
0X0
100
111
427 41 ▶ if ($separator =~ /\*$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($separator =~ /\*$/) { } 40 1 41
428 40 $separator =~ s/\*$//;
429 40 $separator = token_silent($separator);
430 } else {
431 1 $separator = token ($separator);
432 }
433 }
434 42 ▶ $separator = token($separator) if ref $separator eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $separator eq "ARRAY" 0 42 42
435 42 ▶ $separator = token_silent('COMMA') unless defined $separator;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $separator 1 41 42
436 42 return p_and($element, series(p_and ($separator, $element)));
437 }
438 105 ▶sub optional { p_or (p_and (@_), \&nothing) }
Subroutine optional: called CC=1 SCAR=0.0
Pod documented
439
440 =head2 build(), make_component($name, $spec), get_parser($name), parse($input), execute($defined input)
441
442 The C<build> function takes the rules that have been added to the parser, and builds the actual parser using C<make_parser>, which is also available for
443 external use. The C<make_parser> function runs in the context of the parser itself and uses C<eval> to build its parser. Each parser built with C<build>
444 or C<make_parser> is named. Its output, if it matches, is a two-part arrayref, with the first element being its name and the second the arrayref list of
445 tokens or subvalues that it matched.
446
447 An anonymous parser (name '' or undef) just returns the list of tokens, without the level of structure. The same applies to any name ending in an asterisk.
448
449 This should probably be covered in more detail in the tutorial, but the principle used here is that of the recursive-descent parser. A recursive-descent
450 parser can effectively be constructed as a series of little parsers that are glued together by combination functions. Each of these parsers consumes a series
451 of tokens, and returns a value; the default value is an arrayref (a pair, if you're Pythonic) consisting of the name or tag of the parser, followed
452 by the list of tokens consumed. The sum total of all those arrayrefs is an abstract syntax tree for the expression being parsed.
453
454 When a parser is invoked in a macro context, that syntax tree is converted into a structure of Decl::Node objects (a nodal structure), with or
455 without subclass decoration, depending on where the macro is expanded. But when we call a parser from Perl directly, we get the arrayrefs.
456
457 By defining actions and invoking them during the parse, we can also modify that structure as it's being built, or even build something else entirely, like
458 a numeric result of a calculation or perhaps some callable code. This is still pretty hand-wavy, as I still haven't got my head around actual applications.
459
460 At any rate, the rule specifications passed to C<add_rule> are pretty straightforward:
461
462 C<token(['TOKEN'])> matches a token by that name.
463 C<token['type', 'text'])> matches a specific token.
464 C<literal('text')> matches either a token by text, or a bare word. It converts the bare word to ['', 'word'].
465 C<regex('regex')> matches a bare word using a regex. If the regex has parentheses in it, the output value may be one or more tokens with the contents.
466 C<<parser>> matches a named parser rule, and expands to C<$eta_parser> in order to permit self-reference. (See Dominus Chapter 8.)
467 C<\&nothing> is the null parser, used to build complex rules.
468 C<\&anything> is the universal token, used to match things like comments.
469 C<\&end_of_input> is the end of input.
470 C<\&word> is any bare word (non-token text). It also converts the bare word to ['', 'word'].
471 C<p_or()> is Dominus's "alternate" function, because I don't like to type that much.
472 C<p_and()> is Dominus's "concatenate" function, for the same reason.
473 C<series()> is just a function that matches a series of whatever it's called on.
474 C<list_of()> is a function. It matches a delimited series of its first argument, delimited by tokens of its second argument. If omitted, the delimiter is COMMA.
475 C<optional()> is a function that matches either its contents or nothing.
476
477 Note that the only code-munging done here is reference to other rules. It's difficult for me to avoid code generation because it's so fun, but since parser
478 specifications are supposed to be pretty general code, it's really not safe.
479
480 The order of addition of rules determines the order they'll be processed in. When the parser is built, it will check for consistency and dangling rule
481 references (i.e. rules you mention but don't define), perform the eta expansions needed for self-reference, and build all the subparsers.
482
483 =cut
484 253 ▶sub make_component {
Subroutine make_component: called CC=5 SCAR=17.3
Pod documented
485 253 my ($self, $name, $code) = @_;
486 253 my $parser;
487
488 253 ▶ while ($code =~ /<(\w+)>/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($code =~ /<(\w+)>/) 0 253 253
489 0 my $pref = $1;
490 0 ▶ $self->{cmps}->{$pref} = $self->make_component('', '\&nothing') unless $self->{cmps}->{$pref};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"cmps"}{$pref} 0 0 0
491 0 $code =~ s/<$pref>/parser { \$pref->(\@_) }/g;
492 }
493 253 $parser = eval ($code);
494 253 ▶ warn "make_component: $@\n>>> $code" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 253 253
495 253 ▶ return $parser unless $name;
Branch: 1 branch
BranchTrueFalseTotal
unless $name 251 2 253
496 2 ▶ parser {
Subroutine __ANON__: called CC=2 SCAR=6.9
497 2 my $input = shift;
498 2 my $v;
499 2 ▶ ($v, $input) = $parser->($input) or return;
Branch: 1 branch
BranchTrueFalseTotal
($v, $input) = &$parser($input) or return 1 1 2
500 1 [$name, $v];
501 }
502 2 }
503 2087 ▶sub get_parser { $_[0]->{cmps}->{$_[1]} }
Subroutine get_parser: called CC=1 SCAR=0.0
Pod documented
504 39 ▶sub build {
Subroutine build: called CC=5 SCAR=16.1
Pod documented
505 39 my ($self) = @_;
506 39 $self->{cmps} = {}; # Start from scratch on every build, of course.
507
508 39 my $code = "sub {\n";
509 39 foreach my $name ($self->list_rules()) {
510 247 $code .= "my (\$p__$name, \$p__${name}_anon);\n";
511 }
512 39 foreach my $name ($self->list_rules()) {
513 #$self->{cmps}->{$name} = $self->make_component($name, $self->get_rule($name));
514 247 my $rule = $self->get_rule($name);
515 247 ▶ while ($rule =~ /<(\w+)>/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rule =~ /<(\w+)>/) 221 247 468
516 221 my $pref = $1;
517 221 $rule =~ s/<$pref>/parser { \$p__$pref->(\@_) }/g;
518 }
519
520 247 $code .= "\n\$p__${name}_anon = $rule;\n";
521 247 $code .= "\$p__$name = parser {\n";
522 247 $code .= " my \$input = shift;\n";
523 247 $code .= " my \$v;\n";
524 #$code .= " print STDERR \"Calling parser $name\\n\";\n";
525 247 $code .= " (\$v, \$input) = \$p__${name}_anon->(\$input) or return;\n";
526 #$code .= " print STDERR \"Parser $name succeeded\\n\";\n";
527 247 $code .= " (['$name', \$v], \$input);\n";
528 247 $code .= "};\n";
529 247 $code .= "\$self->{cmps}->{'$name'} = \$p__$name;\n";
530 }
531 39 $code .= "}\n";
532 #print STDERR $code;
533 39 my $builder = eval $code;
534 39 ▶ warn "building: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 39 39
535 39 $self->{parser} = $builder->();
536 }
537
538 2083 ▶sub parse {
Subroutine parse: called CC=2 SCAR=7.0
Pod documented
539 2083 my ($self, $input) = @_;
540 2083 ▶ $input = $self->tokenstream($input) unless ref $input eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $input eq "ARRAY" 2083 0 2083
541 2083 my @rules = $self->list_rules();
542 2083 my $first = $self->get_parser($rules[0]);
543 2083 my ($output, $remainder) = $first->($input);
544 2083 return $output;
545 }
546
547 2076 ▶sub execute {
Subroutine execute: called CC=3 SCAR=11.8
Pod documented
548 2076 my ($self) = @_;
549 2076 ▶ my $input_builder = $self->action('input') || sub { $_[1] };
Subroutine __ANON__: called CC=1 SCAR=0.1
Condition66%2/3
$self->action('input') || sub { $_[1]; }
l!l&&r!l&&!r
17563200
MC/DC0%0/2
$self->action('input') || sub { $_[1]; }
$self->action('input') sub { $_[1]; }
Truth table66%2/3
A || B
A= $self->action('input')B= sub { $_[1]; }
ABresult
1X1
011
000
550 2076 my $parse_result = $self->parse($input_builder->(@_));
551 0 ▶ my $output_builder = $self->action('output') || sub { $_[0] };
Subroutine __ANON__: not called CC=1 SCAR=2.0
Condition33%1/3
$self->action('output') || sub { $_[0]; }
l!l&&r!l&&!r
207600
MC/DC0%0/2
$self->action('output') || sub { $_[0]; }
$self->action('output') sub { $_[0]; }
Truth table33%1/3
A || B
A= $self->action('output')B= sub { $_[0]; }
ABresult
1X1
011
000
552 2076 $output_builder->($parse_result, @_);
553 }
554
555 =head1 AUTHOR
556
557 Michael Roberts, C<< <michael at vivtek.com> >>
558
559 =head1 BUGS
560
561 Please report any bugs or feature requests to C<bug-decl at rt.cpan.org>, or through
562 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Decl>. I will be notified, and then you'll
563 automatically be notified of progress on your bug as I make changes.
564
565 =head1 LICENSE AND COPYRIGHT
566
567 Copyright 2010 Michael Roberts.
568
569 This program is free software; you can redistribute it and/or modify it
570 under the terms of either: the GNU General Public License as published
571 by the Free Software Foundation; or the Artistic License.
572
573 See http://dev.perl.org/licenses/ for more information.
574
575 =cut
576
577 13 1; # End of Decl::Parser
« blib/lib/Decl/Semantics/Code.pm ↑ Summary blib/lib/Decl.pm »