FA/Element.pm

filter: Statementstmt 87.7% 172 / 196 Branchbran 66.1% 45 / 68 Conditioncond 42.3% 11 / 26 MC/DCmcdc 18.7% 3 / 16 Subroutinesub 90.0% 27 / 30 Podpod 83.3% 10 / 12 totaltotal 77.0% 268 / 348 CC 51 SCAR 25.7
CC
51
Cov
79%
build_stt
33.0
advance
15.6
validate_params
9.9
CRAP 13.1
↑ Summary FA.pm »
1 package Set::FA::Element;
2  
3 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 4 ▶use Log::Handler;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 4 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 4 ▶use Types::Standard qw/Any ArrayRef Bool HashRef Str/;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 has accepting =>
13 (
14 0 ▶ default => sub{return []},
Subroutine __ANON__: not called CC=1 SCAR=6.9
15 4 is => 'rw',
16 isa => ArrayRef,
17 required => 0,
18 );
19  
20 has actions =>
21 (
22 32 ▶ default => sub{return {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
23 4 is => 'rw',
24 isa => HashRef,
25 required => 0,
26 );
27  
28 has current => # Internal.
29 (
30 33 ▶ default => sub{return ''},
Subroutine __ANON__: called CC=1 SCAR=0.0
31 4 is => 'rw',
32 isa => Str,
33 required => 0,
34 );
35  
36 has die_on_loop =>
37 (
38 33 ▶ default => sub{return 0},
Subroutine __ANON__: called CC=1 SCAR=0.0
39 4 is => 'rw',
40 isa => Bool,
41 required => 0,
42 );
43  
44 has id =>
45 (
46 3 ▶ default => sub{return ''},
Subroutine __ANON__: called CC=1 SCAR=0.0
47 4 is => 'rw',
48 isa => Str,
49 required => 0,
50 );
51  
52 has logger =>
53 (
54 33 ▶ default => sub{return undef},
Subroutine __ANON__: called CC=1 SCAR=0.0
55 4 is => 'rw',
56 isa => Any,
57 required => 0,
58 );
59  
60 has match => # Internal.
61 (
62 33 ▶ default => sub{return ''},
Subroutine __ANON__: called CC=1 SCAR=0.0
63 4 is => 'rw',
64 isa => Str,
65 required => 0,
66 );
67  
68 has maxlevel =>
69 (
70 32 ▶ default => sub{return 'notice'},
Subroutine __ANON__: called CC=1 SCAR=0.0
71 4 is => 'rw',
72 isa => Str,
73 required => 0,
74 );
75  
76 has minlevel =>
77 (
78 33 ▶ default => sub{return 'error'},
Subroutine __ANON__: called CC=1 SCAR=0.0
79 4 is => 'rw',
80 isa => Str,
81 required => 0,
82 );
83  
84 has start =>
85 (
86 0 ▶ default => sub{return ''},
Subroutine __ANON__: not called CC=1 SCAR=6.9
87 4 is => 'rw',
88 isa => Str,
89 required => 0,
90 );
91  
92 has stt => # Internal.
93 (
94 33 ▶ default => sub{return {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
95 4 is => 'rw',
96 isa => HashRef,
97 required => 0,
98 );
99  
100 has transitions =>
101 (
102 0 ▶ default => sub{return []},
Subroutine __ANON__: not called CC=1 SCAR=6.9
103 4 is => 'rw',
104 isa => ArrayRef,
105 required => 0,
106 );
107  
108 4 our $VERSION = '2.01';
109  
110 # -----------------------------------------------
111  
112 sub BUILD
113 33 ▶{
Subroutine BUILD: called CC=2 SCAR=7.0
Pod undocumented
114 33 my($self) = @_;
115  
116 33 ▶ if (! defined $self -> logger)
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->logger) 33 0 33
117 {
118 33 $self -> logger(Log::Handler -> new);
119 33 $self -> logger -> add
120 (
121 screen =>
122 {
123 maxlevel => $self -> maxlevel,
124 message_layout => '%m',
125 minlevel => $self -> minlevel,
126 utf8 => 1,
127 }
128 );
129 }
130  
131 33 $self -> validate_params;
132 33 $self -> build_stt;
133 33 $self -> current($self -> start);
134  
135 } # End of BUILD.
136  
137 # -----------------------------------------------
138  
139 sub accept
140 34 ▶{
Subroutine accept: called CC=1 SCAR=0.0
Pod documented
141 34 my($self, $input) = @_;
142  
143 34 $self -> log(debug => 'Entered accept()');
144  
145 34 return $self -> final($self -> advance($input) );
146  
147 } # End of accept.
148  
149 # -----------------------------------------------
150  
151 sub advance
152 38 ▶{
Subroutine advance: called CC=7 SCAR=27.5
Pod documented
153 38 my($self, $input) = @_;
154  
155 38 $self -> log(debug => 'Entered advance()');
156  
157 38 my($output);
158  
159 38 ▶ while ($input)
Branch: 1 branch
BranchTrueFalseTotal
if ($input) 439 38 477
160 {
161 439 $output = $self -> step($input);
162  
163 439 ▶ if (length($output) >= length($input) )
Branch: 1 branch
BranchTrueFalseTotal
if (length $output >= length $input) 0 439 439
164 {
165 0 ▶ my($prefix) = $input ? '<' . join('> <', map{$_ ge ' ' && $_ le '~' ? sprintf('%s', $_) : sprintf('0x%02x', ord $_)} grep{/./} split(//, substr($input, 0, 5) ) ) . '>' : '';
Branch: 2 branches
BranchTrueFalseTotal
$input ? : 0 0 0
$_ ge ' ' && $_ le '~' ? : 0 0 0
Condition0%0/3
$_ ge " " and $_ le "~"
!ll&&!rl&&r
000
MC/DC0%0/2
$_ ge " " and $_ le "~"
$_ ge " " $_ le "~"
Truth table0%0/3
A and B
A= $_ ge " "B= $_ le "~"
ABresult
0X0
100
111
166  
167 0 ▶ $self -> log( ($self -> die_on_loop ? 'error' : 'warning') => "State: '" . $self -> current . "' is not consuming input. Next 5 chars: $prefix");
Branch: 1 branch
BranchTrueFalseTotal
$self->die_on_loop ? : 0 0 0
168 }
169  
170 439 $input = $output;
171 }
172  
173 38 return $self -> current;
174  
175 } # End of advance.
176  
177 # -----------------------------------------------
178  
179 sub build_stt
180 33 ▶{
Subroutine build_stt: called CC=23 SCAR=35.0
Pod documented
181 33 my($self) = @_;
182 33 my(%action) = %{$self -> actions};
183  
184 # Reformat the actions.
185  
186 33 my($entry_exit);
187 my($state);
188 33 my($trigger);
189  
190 33 for $state (keys %action)
191 {
192 1 for $trigger (keys %{$action{$state} })
193 {
194 2 ▶ if ($trigger !~ /^(entry|exit)$/)
Branch: 1 branch
BranchTrueFalseTotal
unless ($trigger =~ /^(entry|exit)$/) 0 2 2
195 {
196 0 $self -> log(error => "Action table contains the unknown trigger '$trigger'. Use entry/exit");
197 }
198 }
199 }
200  
201 # Reformat the acceptings.
202  
203 33 my(@accepting) = @{$self -> accepting};
204 33 my($row) = 0;
205  
206 33 my(%accept);
207 33 my($entry_fn, $entry_name, $exit_fn, $exit_name);
208 33 my($last);
209 33 my($next);
210 33 my($rule_sub, $rule);
211 33 my(%stt);
212  
213 33 @accept{@accepting} = (1) x @accepting;
214  
215 33 for my $item (@{$self -> transitions})
216 {
217 124 $row++;
218  
219 124 ▶ if (ref($item ne 'ARRAY') || ($#$item < 2) )
Branch: 1 branch
BranchTrueFalseTotal
if (ref($item ne "ARRAY") or $item->$#* < 2) 0 124 124
Condition33%1/3
ref($item ne "ARRAY") or $item->$#* < 2
l!l&&r!l&&!r
00124
MC/DC0%0/2
ref($item ne "ARRAY") or $item->$#* < 2
ref($item ne "ARRAY") $item->$#* < 2
Truth table33%1/3
A or B
A= ref($item ne "ARRAY")B= $item->$#* < 2
ABresult
1X1
011
000
220 {
221 0 $self -> log(error => "Transition table row $row has too few columns");
222 }
223  
224 124 ($state, $rule, $next) = @$item;
225  
226 # Allow first column of transition table to be empty (meaning ditto),
227 # as long as there is a state name somewhere above the missing element.
228  
229 124 ▶ if (! defined $state)
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $state) 0 124 124
230 {
231 0 $state = $last;
232 }
233  
234 124 ▶ if (! defined($state && $rule && $next) )
Branch: 1 branch
BranchTrueFalseTotal
unless (defined($state && $rule && $next)) 0 124 124
Condition33%2/6
$state && $rule && $next
!ll&&!rl&&r
00124
$state and $rule
!ll&&!rl&&r
00124
MC/DC0%0/3
$state && $rule && $next
$state $rule $next
Truth table25%1/4
A and B && C
A= $stateB= $ruleC= $next
ABCresult
0XX0
10X0
1100
1111
235 {
236 0 $self -> log(error => "Transition table row $row lacks state name/rule/next state name");
237 }
238  
239 124 ▶ if (ref($rule) eq 'CODE')
Branch: 1 branch
BranchTrueFalseTotal
if (ref $rule eq 'CODE') { } 0 124 124
240 {
241 0 $rule_sub = $rule;
242 }
243 else
244 {
245 # Warning: $regexp must be declared in this scope.
246  
247 124 my($regexp) = qr/^($rule)(.*)/;
248 $rule_sub = sub
249 722 ▶ {
Subroutine __ANON__: called CC=2 SCAR=6.9
250 722 my($class, $input) = @_;
251  
252 722 ▶ return $input =~ $regexp ? ($1, $2) : (undef, undef);
Branch: 1 branch
BranchTrueFalseTotal
$input =~ /$regexp/ ? : 460 262 722
253 124 };
254 }
255  
256 # The 3rd item in each arrayref is only used for debugging.
257  
258 124 ▶ if ($stt{$state})
Branch: 1 branch
BranchTrueFalseTotal
if ($stt{$state}) { } 55 69 124
259 {
260 55 push @{$stt{$state}{rule} }, [$rule_sub, $next, $rule];
261 }
262 else
263 {
264 69 $entry_fn = $entry_name = $exit_fn = $exit_name = '';
265  
266 69 ▶ if ($action{$state} && $action{$state}{entry})
Branch: 1 branch
BranchTrueFalseTotal
if ($action{$state} and $action{$state}{"entry"}) 1 68 69
Condition66%2/3
$action{$state} and $action{$state}{"entry"}
!ll&&!rl&&r
6801
MC/DC50%1/2
$action{$state} and $action{$state}{"entry"}
$action{$state} $action{$state}{"entry"}
Truth table66%2/3
A and B
A= $action{$state}B= $action{$state}{"entry"}
ABresult
0X0
100
111
267 {
268 1 $entry_fn = $action{$state}{entry};
269  
270 1 ▶ if (ref $entry_fn eq 'ARRAY')
Branch: 1 branch
BranchTrueFalseTotal
if (ref $entry_fn eq 'ARRAY') { } 0 1 1
271 {
272 0 $entry_name = $$entry_fn[1];
273 0 $entry_fn = $$entry_fn[0];
274 }
275 else
276 {
277 1 $entry_name = $entry_fn;
278 }
279 }
280  
281 69 ▶ if ($action{$state} && $action{$state}{exit})
Branch: 1 branch
BranchTrueFalseTotal
if ($action{$state} and $action{$state}{"exit"}) 1 68 69
Condition66%2/3
$action{$state} and $action{$state}{"exit"}
!ll&&!rl&&r
6801
MC/DC50%1/2
$action{$state} and $action{$state}{"exit"}
$action{$state} $action{$state}{"exit"}
Truth table66%2/3
A and B
A= $action{$state}B= $action{$state}{"exit"}
ABresult
0X0
100
111
282 {
283 1 $exit_fn = $action{$state}{exit};
284  
285 1 ▶ if (ref $exit_fn eq 'ARRAY')
Branch: 1 branch
BranchTrueFalseTotal
if (ref $exit_fn eq 'ARRAY') { } 0 1 1
286 {
287 0 $exit_name = $$exit_fn[1];
288 0 $exit_fn = $$exit_fn[0];
289 }
290 else
291 {
292 1 $exit_name = $exit_fn;
293 }
294 }
295  
296 $stt{$state} =
297 {
298 69 ▶ accept => $accept{$state} || 0,
Condition100%2/2
$accept{$state} || 0
l!l
3336
MC/DC100%1/1
$accept{$state} || 0
$accept{$state}
Truth table100%2/2
A
A= $accept{$state}
Aresult
11
00
299 entry_fn => $entry_fn,
300 entry_name => $entry_name,
301 exit_fn => $exit_fn,
302 exit_name => $exit_name,
303 rule => [ [$rule_sub, $next, $rule] ],
304 start => 0,
305 };
306 }
307  
308 124 $last = $state;
309 }
310  
311 33 $state = $self -> start;
312  
313 33 ▶ if ($stt{$state})
Branch: 1 branch
BranchTrueFalseTotal
if ($stt{$state}) { } 33 0 33
314 {
315 33 $stt{$state}{start} = 1;
316 }
317 else
318 {
319 0 $self -> log(error => "Start state '$state' is not defined in the transition table");
320 }
321  
322 33 for $state (@accepting)
323 {
324 33 ▶ if (! $stt{$state})
Branch: 1 branch
BranchTrueFalseTotal
unless ($stt{$state}) 0 33 33
325 {
326 0 $self -> log(error => "Accepting state '$state' is not defined in the transition table");
327 }
328 }
329  
330 33 $self -> stt(\%stt);
331  
332 } # End of build_stt.
333  
334 # -----------------------------------------------
335  
336 sub final
337 117 ▶{
Subroutine final: called CC=2 SCAR=6.9
Pod documented
338 117 my($self, $state) = @_;
339  
340 117 $self -> log(debug => 'Entered final()');
341  
342 117 my($stt) = $self -> stt;
343  
344 117 ▶ return defined($state) ? $$stt{$state}{accept} : $$stt{$self -> current}{accept};
Branch: 1 branch
BranchTrueFalseTotal
defined $state ? : 36 81 117
345  
346 } # End of final.
347  
348 # --------------------------------------------------
349  
350 sub log
351 1413 ▶{
Subroutine log: called CC=2 SCAR=7.2
Pod documented
352 1413 my($self, $level, $s) = @_;
353  
354 1413 ▶ $self -> logger -> log($level => $s) if ($self -> logger);
Branch: 1 branch
BranchTrueFalseTotal
if $self->logger 1413 0 1413
355  
356 } # End of log.
357  
358 # -----------------------------------------------
359  
360 sub report
361 1 ▶{
Subroutine report: called CC=7 SCAR=19.7
Pod documented
362 1 my($self) = @_;
363  
364 1 $self -> log(debug => 'Entered report()');
365 1 $self -> log(info => 'State Transition Table');
366  
367 1 my($stt) = $self -> stt;
368  
369 1 my($rule);
370 my($s);
371  
372 1 for my $state (sort keys %$stt)
373 {
374 3 $s = "State: $state";
375  
376 3 ▶ if ($$stt{$state}{start})
Branch: 1 branch
BranchTrueFalseTotal
if ($stt->{$state}{"start"}) 1 2 3
377 {
378 1 $s .= '. This is the start state';
379 }
380  
381 3 ▶ if ($$stt{$state}{accept})
Branch: 1 branch
BranchTrueFalseTotal
if ($stt->{$state}{"accept"}) 1 2 3
382 {
383 1 $s .= '. This is an accepting state';
384 }
385  
386 3 ▶ if ($$stt{$state}{entry_fn})
Branch: 1 branch
BranchTrueFalseTotal
if ($stt->{$state}{"entry_fn"}) 0 3 3
387 {
388 0 $s .= ". Entry fn: $$stt{$state}{entry_name}";
389 }
390  
391 3 ▶ if ($$stt{$state}{exit_fn})
Branch: 1 branch
BranchTrueFalseTotal
if ($stt->{$state}{"exit_fn"}) 0 3 3
392 {
393 0 $s .= ". Exit fn: $$stt{$state}{exit_name}";
394 }
395  
396 3 $self -> log(info => $s);
397 3 $self -> log(info => 'Rule => Next state');
398  
399 3 for $rule (@{$$stt{$state}{rule} })
400 {
401 6 $self -> log(info => "/$$rule[2]/ => $$rule[1]");
402 }
403 }
404  
405 } # End of report.
406  
407 # -----------------------------------------------
408  
409 sub reset
410 31 ▶{
Subroutine reset: called CC=1 SCAR=0.0
Pod documented
411 31 my($self) = @_;
412  
413 31 $self -> log(debug => 'Entered reset()');
414 31 $self -> current($self -> start);
415  
416 31 return $self -> current;
417  
418 } # End of reset.
419  
420 # -----------------------------------------------
421  
422 sub state
423 129 ▶{
Subroutine state: called CC=3 SCAR=11.0
Pod documented
424 129 my($self, $state) = @_;
425  
426 129 $self -> log(debug => 'Entered state()');
427  
428 129 ▶ return defined($state) ? (${$self -> stt}{$state} ? 1 : 0) : $self -> current;
Branch: 2 branches
BranchTrueFalseTotal
defined $state ? : 2 127 129
do { $self->stt }->{$state} ? : 1 1 2
429  
430 } # End of state.
431  
432 # -----------------------------------------------
433  
434 sub step
435 460 ▶{
Subroutine step: called CC=3 SCAR=11.0
Pod documented
436 460 my($self, $input) = @_;
437  
438 460 $self -> log(debug => 'Entered step()');
439  
440 460 my($current) = $self -> current;
441 460 my($stt) = $self -> stt;
442  
443 460 my($match);
444 my($next);
445 460 my($output);
446 460 my($rule_sub, $rule);
447  
448 460 for my $item (@{$$stt{$current}{rule} })
449 {
450 722 ($rule_sub, $next, $rule) = @$item;
451 722 ($match, $output) = $rule_sub -> ($self, $input);
452  
453 722 ▶ if (defined $match)
Branch: 1 branch
BranchTrueFalseTotal
if (defined $match) 460 262 722
454 {
455 460 $self -> match($match);
456 460 $self -> step_state($next, $rule, $match);
457  
458 460 return $output;
459 }
460 }
461  
462 0 return $input;
463  
464 } # End of step.
465  
466 # -----------------------------------------------
467  
468 sub step_state
469 460 ▶{
Subroutine step_state: called CC=4 SCAR=13.9
Pod documented
470 460 my($self, $next, $rule, $match) = @_;
471  
472 460 $self -> log(debug => 'Entered step_state()');
473  
474 460 my($current) = $self -> current;
475  
476 460 ▶ return 0 if ($next eq $current);
Branch: 1 branch
BranchTrueFalseTotal
if $next eq $current 330 130 460
477  
478 130 my($stt) = $self -> stt;
479  
480 130 ▶ if ($$stt{$current}{exit_fn})
Branch: 1 branch
BranchTrueFalseTotal
if ($stt->{$current}{"exit_fn"}) 9 121 130
481 {
482 9 $$stt{$current}{exit_fn} -> ($self);
483 }
484  
485 130 $self -> current($next);
486  
487 130 ▶ if ($$stt{$next}{entry_fn})
Branch: 1 branch
BranchTrueFalseTotal
if ($stt->{$next}{"entry_fn"}) 9 121 130
488 {
489 9 $$stt{$next}{entry_fn} -> ($self);
490 }
491  
492 130 $self -> log(info => "Stepped from state '$current' to '$next' using rule /$rule/ to match '$match'");
493  
494 130 return 1;
495  
496 } # End of step_state;
497  
498 # -----------------------------------------------
499  
500 sub validate_params
501 33 ▶{
Subroutine validate_params: called CC=6 SCAR=22.9
Pod undocumented
502 33 my($self) = @_;
503  
504 33 ▶ if ( (ref $self -> accepting ne 'ARRAY') || ($#{$self -> accepting} < 0) )
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->accepting ne "ARRAY" or $#{$self->accepting;} < 0) 0 33 33
Condition33%1/3
ref $self->accepting ne "ARRAY" or $#{$self->accepting;} < 0
l!l&&r!l&&!r
0033
MC/DC0%0/2
ref $self->accepting ne "ARRAY" or $#{$self->accepting;} < 0
ref $self->accepting ne "ARRAY" $#{$self->accepting;} < 0
Truth table33%1/3
A or B
A= ref $self->accepting ne "ARRAY"B= $#{$self->accepting;} < 0
ABresult
1X1
011
000
505 {
506 0 $self -> log(error => 'No accepting states specified. Use accepting');
507 }
508  
509 33 ▶ if (! $self -> start)
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->start) 0 33 33
510 {
511 0 $self -> log(error => 'No start state specified. Use start');
512 }
513  
514 33 ▶ if ( (ref $self -> transitions ne 'ARRAY') || ($#{$self -> transitions} < 0) )
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->transitions ne "ARRAY" or $#{$self->transitions;} < 0) 0 33 33
Condition33%1/3
ref $self->transitions ne "ARRAY" or $#{$self->transitions;} < 0
l!l&&r!l&&!r
0033
MC/DC0%0/2
ref $self->transitions ne "ARRAY" or $#{$self->transitions;} < 0
ref $self->transitions ne "ARRAY" $#{$self->transitions;} < 0
Truth table33%1/3
A or B
A= ref $self->transitions ne "ARRAY"B= $#{$self->transitions;} < 0
ABresult
1X1
011
000
515 {
516 0 $self -> log(error => 'No state transition table specified. Use transitions');
517 }
518  
519 } # End of validate_params;
520  
521 # -----------------------------------------------
522  
523 4 1;
524  
525 =pod
526  
527 =head1 NAME
528  
529 L<Set::FA::Element> - Discrete Finite Automaton
530  
531 =head1 Synopsis
532  
533 This is scripts/synopsis.2.pl (a test-free version of t/report.t):
534  
535 #!/usr/bin/env perl
536  
537 use strict;
538 use warnings;
539  
540 use Set::FA::Element;
541  
542 # --------------------------
543  
544 my($dfa) = Set::FA::Element -> new
545 (
546 accepting => ['baz'],
547 maxlevel => 'debug',
548 start => 'foo',
549 transitions =>
550 [
551 ['foo', 'b', 'bar'],
552 ['foo', '.', 'foo'],
553 ['bar', 'a', 'foo'],
554 ['bar', 'b', 'bar'],
555 ['bar', 'c', 'baz'],
556 ['baz', '.', 'baz'],
557 ],
558 );
559  
560 print "Got: \n";
561 $dfa -> report;
562  
563 print "Expected: \n", <<EOS;
564 Entered report()
565 State Transition Table
566 State: bar
567 Rule => Next state
568 /a/ => foo
569 /b/ => bar
570 /c/ => baz
571 State: baz. This is an accepting state
572 Rule => Next state
573 /./ => baz
574 State: foo. This is the start state
575 Rule => Next state
576 /b/ => bar
577 /./ => foo
578 EOS
579  
580 Or make use of:
581  
582 my($boolean) = $dfa -> accept($input);
583 my($current) = $dfa -> advance($input);
584 my($state) = $dfa -> current;
585 my($boolean) = $dfa -> final;
586 my($acceptor) = $dfa -> final($state);
587 my($string) = $dfa -> match;
588 my($current) = $dfa -> reset;
589 my($current) = $dfa -> state;
590 my($boolean) = $dfa -> state($state);
591 my($string) = $dfa -> step($input);
592 my($boolean) = $dfa -> step_state($next);
593  
594 =head1 Description
595  
596 L<Set::FA::Element> provides a mechanism to define and run a DFA.
597  
598 =head1 Installation
599  
600 Install L<Set::FA> as you would for any C<Perl> module:
601  
602 Run:
603  
604 cpanm Set::FA
605  
606 or run:
607  
608 sudo cpan Set::FA
609  
610 or unpack the distro, and then either:
611  
612 perl Build.PL
613 ./Build
614 ./Build test
615 sudo ./Build install
616  
617 or:
618  
619 perl Makefile.PL
620 make (or dmake or nmake)
621 make test
622 make install
623  
624 =head1 Constructor and Initialization
625  
626 =head2 Parentage
627  
628 You can easily subclass L<Set::FA::Element> by having your subclass use exactly the same logic as
629 in the code, after declaring your Moo-based getters and setters.
630  
631 =head2 Using new()
632  
633 C<new()> is called as C<< my($dfa) = Set::FA::Element -> new(k1 => v1, k2 => v2, ...) >>.
634  
635 It returns a new object of type C<Set::FA::Element>.
636  
637 Key-value pairs accepted in the parameter list are as follows. Also, each is also a method,
638 so you can retrieve the value and update it at any time.
639  
640 Naturally, after the internal state transition table has been constructed (during the call to
641 C<new()>), updates to some of these fields will be ignored. Methods which I<are> effective later
642 are documented.
643  
644 =over 4
645  
646 =item o accepting => []
647  
648 Provides an arrayref of accepting state names.
649  
650 This key is optional.
651  
652 The default is [].
653  
654 =item o actions => {}
655  
656 Provides a hashref of entry/exit functions keyed by state name.
657  
658 This means you can have only 1 entry function and 1 exit function per state.
659  
660 For a module which gives you the power to have a different entry and exit function
661 for each different regexp which matches the input, see the (as yet unwritten) Set::FA::Manifold.
662  
663 For a given state name key, the value is a hashref with 1 or 2 of these keys:
664  
665 =over 4
666  
667 =item o entry => \&function or => [\&function, 'function_name']
668  
669 The 'entry' key points to a reference to a function to be called upon entry to a state.
670  
671 Alternately, you can pass in an arrayref, with the function reference as the first element,
672 and a string, e.g. the function name, as the second element.
673  
674 The point of the [\&fn, 'fn'] version is when you call report(), and the 'fn' string is output.
675  
676 =item o exit => \&function or => [\&function, 'function_name']
677  
678 The 'exit' key points to a reference to a function to be called upon exit from a state.
679  
680 Alternately, you can pass in an arrayref, with the function reference as the first element,
681 and a string, e.g. the function name, as the second element.
682  
683 The point of the [\&fn, 'fn'] version is when you call report(), and the 'fn' string is output.
684  
685 =back
686  
687 Each of these functions is called (in method step_state() ) with the DFA object as the only
688 parameter. You use that object to call the methods listed in these docs. See L</Synopsis> for
689 a list.
690  
691 This key is optional.
692  
693 The default is {}.
694  
695 =item o die_on_loop => $boolean
696  
697 Provides a way for the code to keep running, or die, when the advance() method determines that
698 input is not being consumed.
699  
700 Setting die_on_loop to 0 means keep running.
701  
702 Setting die_on_loop to 1 means the code dies, after outputting an error message.
703  
704 Retrieve and update the value with the die_on_loop() method.
705  
706 This key is optional.
707  
708 The default is 0.
709  
710 =item o id => $string
711  
712 Provides a place to store some sort of identifier per DFA object.
713  
714 Retrieve and update the value with the id() method.
715  
716 This key is optional.
717  
718 The default is ''.
719  
720 =item o logger => $aLoggerObject
721  
722 Specify a logger compatible with L<Log::Handler>, for the lexer and parser to use.
723  
724 Default: A logger of type L<Log::Handler> which writes to the screen.
725  
726 To disable logging, just set 'logger' to the empty string (not undef).
727  
728 =item o maxlevel => $logOption1
729  
730 This option affects L<Log::Handler>.
731  
732 See the L<Log::Handler::Levels> docs.
733  
734 By default nothing is printed.
735  
736 Typical values are: 'error', 'notice', 'info' and 'debug'.
737  
738 The default produces no output.
739  
740 Default: 'notice'.
741  
742 =item o minlevel => $logOption2
743  
744 This option affects L<Log::Handler>.
745  
746 See the L<Log::Handler::Levels> docs.
747  
748 Default: 'error'.
749  
750 No lower levels are used.
751  
752 =item o start => $name_of_start_state
753  
754 Provides the name of the start state.
755  
756 Retrieve and update the value with the start() method.
757  
758 This key is mandatory.
759  
760 There is no default.
761  
762 =item o transitions => []
763  
764 Provides a complex arrayref of state names and regexps which control the transitions between
765 states.
766  
767 Each element of this arrayref is itself an arrayref of 3 elements:
768  
769 =over 4
770  
771 =item o [0] ($state)
772  
773 The name of the state, which has to match the 'current' state, before other elements of this
774 arrayref are utilized.
775  
776 =item o [1] ($regexp)
777  
778 The regexp, as a string, against which the input is tested, to determine whether or not to
779 move to the next state.
780  
781 This string may be a coderef. As such, it should contain 2 pairs of parentheses. The first
782 must capture the matched portion of the input, and the second must capture the unmatched portion
783 of the input.
784  
785 If it is not a coderef, it is wrapped in qr/($regexp)/ and turned into a coderef which returns
786 the 2 portions of the input as described in the previous sentence.
787  
788 The code supplies the extra parentheses in the qr// above so that the matched portion of the input
789 can be retrieved with the match() method.
790  
791 If the regexp does not match, (undef, undef) must be returned by the coderef.
792  
793 =item o [2] ($next)
794  
795 The name of the state to which the DFA will move when the regexp matches the input.
796  
797 The string which matched, if any, can be retrieved with the match() method.
798  
799 The name of the new state can be retrieved with the current() method.
800  
801 =back
802  
803 This key is mandatory.
804  
805 There is no default.
806  
807 =back
808  
809 =head1 Methods
810  
811 =head2 accept($input)
812  
813 Calls L</advance($input)>.
814  
815 Returns 1 if the 'current' state - after processing the input - is an accepting state.
816  
817 Returns 0 otherwise.
818  
819 =head2 accepting($arrayref_of_states)
820  
821 See L</Using new()> for details.
822  
823 C<accepting> is a parameter to L</new([%args])>.
824  
825 =head2 actions($arrayref_of_states)
826  
827 See L</Using new()> for details.
828  
829 C<actions> is a parameter to L</new([%args])>.
830  
831 =head2 advance($input)
832  
833 Calls L</step($input)> repeatedly on the unconsumed portion of the input.
834  
835 Returns the 'current' state at the end of that process.
836  
837 Since L</step($input)> calls L</match($consumed_input)> upon every match, and L</step_state($next)>
838 too, you necessarily lose access to the individual portions of the input matched by successive
839 runs of the coderef per transition table entry.
840  
841 At the end of this process, then, L</match($consumed_input)> can only return the last portion
842 matched.
843  
844 See L</step($input)> for advancing the DFA by a single transition.
845  
846 Logging note:
847  
848 =over 4
849  
850 =item o When die_on_loop is 0
851  
852 Then, advance() calls $your_logger -> log(warning => $message) when input is not consumed.
853  
854 =item o When die_on_loop is 1
855  
856 Calls die($message).
857  
858 =back
859  
860 =head2 build_stt()
861  
862 Use these parameters to new() to construct a state transition table:
863  
864 =over 4
865  
866 =item o accepting
867  
868 =item o actions
869  
870 =item o start
871  
872 =item o transitions
873  
874 =back
875  
876 Note: The private method _init() calls validate_params() I<before> calling build_stt(), so if
877 you call accepting($new_accepting), actions($new_actions), start($new_start) and
878 transtions($new_transitions), for some reason, and then call build_stt(), you will miss out on the
879 benefit of calling validate_params(). So don't do that!
880  
881 =head2 current([$state])
882  
883 Here, the [] indicate an optional parameter.
884  
885 =over 4
886  
887 =item o When $state is not provided
888  
889 Returns the 'current' state of the DFA.
890  
891 =item o When $state is provided
892  
893 Sets the 'current' state of the DFA.
894  
895 =back
896  
897 =head2 die_on_loop([$Boolean])
898  
899 See L</Using new()> for details. See also L</advance($input)> for a discussion of C<die_on_loop>.
900  
901 C<die_on_loop> is a parameter to L</new([%args])>.
902  
903 =head2 final([$state])
904  
905 Here, the [] indicate an optional parameter.
906  
907 =over 4
908  
909 =item o When $state is not provided
910  
911 Returns 1 if the 'current' state is an accepting state.
912  
913 Returns 0 otherwise.
914  
915 =item o When $state is provided
916  
917 Returns 1 if $state is an accepting state.
918  
919 Returns 0 otherwise.
920  
921 =back
922  
923 =head2 id([$id])
924  
925 Here, the [] indicate an optional parameter.
926  
927 See L</Using new()> for details.
928  
929 C<id> is a parameter to L</new([%args])>.
930  
931 =head2 log($level, $message)
932  
933 Calls log($level, $message) on the logger object if that object is defined.
934  
935 To stop this, set the logger to '' in the call to L</new([%args])>.
936  
937 =head2 logger($arrayref_of_states)
938  
939 See L</Using new()> for details.
940  
941 C<logger> is a parameter to L</new([%args])>.
942  
943 =head2 maxlevel([$string])
944  
945 Here, the [] indicate an optional parameter.
946  
947 See L</Using new()> for details.
948  
949 Get or set the value used by the logger object.
950  
951 This option is only used if an object of type L<Log::Handler> is ceated, and such an object is
952 created by default. To stop this, set the logger to '' in the call to L</new([%args])>.
953  
954 See L<Log::Handler::Levels>.
955  
956 Typical values are: 'notice', 'info' and 'debug'. The default, 'notice', produces no output.
957  
958 C<maxlevel> is a parameter to L</new([%args])>.
959  
960 =head2 minlevel([$string])
961  
962 Here, the [] indicate an optional parameter.
963  
964 See L</Using new()> for details.
965  
966 Get or set the value used by the logger object.
967  
968 This option is only used if an object of type L<Log::Handler> is ceated, and such an object is
969 created by default. To stop this, set the logger to '' in the call to L</new([%args])>.
970  
971 See L<Log::Handler::Levels>.
972  
973 C<minlevel> is a parameter to L</new([%args])>.
974  
975 =head2 new([%args])
976  
977 The constructor. See L</Constructor and Initialization>.
978  
979 =head2 match([$consumed_input])
980  
981 Here, the [] indicate an optional parameter.
982  
983 =over 4
984  
985 =item o When $consumed_input is not provided
986  
987 Returns the portion of the input matched by the most recent step of the DFA.
988  
989 =item o When $consumed_input is provided
990  
991 Sets the internal string which will be returned by calling match().
992  
993 =back
994  
995 =head2 report()
996  
997 Log the state transition table, at log level 'info'.
998  
999 =head2 reset()
1000  
1001 Resets the DFA object to the start state.
1002  
1003 Returns the 'current' state, which will be the start state.
1004  
1005 Does not reset the id or anything else associated with the object.
1006  
1007 =head2 start([$start])
1008  
1009 Here, the [] indicate an optional parameter.
1010  
1011 See L</Using new()> for details.
1012  
1013 C<start> is a parameter to L</new([%args])>.
1014  
1015 =head2 state([$state])
1016  
1017 Here, the [] indicate an optional parameter.
1018  
1019 =over 4
1020  
1021 =item o When $state is not provided
1022  
1023 Returns the 'current' state.
1024  
1025 =item o When $state is provided
1026  
1027 Returns 1 if $state was defined in the transitions arrayref supplied to new().
1028  
1029 Returns 0 otherwise.
1030  
1031 =back
1032  
1033 =head2 step($input)
1034  
1035 Advances the DFA by a single transition, if possible.
1036  
1037 The code checks each entry in the transitions arrayref supplied to new(), in order,
1038 looking for entries whose 1st element ($state) matches the 'current' state.
1039  
1040 Upon the first match found (if any), the code runs the coderef in the 2nd element ($rule_sub) of
1041 that entry.
1042  
1043 If there is a match:
1044  
1045 =over 4
1046  
1047 =item o Calls L</match($consumed_input)> so you can retrieve that value with the match() method
1048  
1049 =item o Calls L</step_state($next)>, passing in the 3rd element ($next) in that entry
1050 as the only parameter
1051  
1052 =back
1053  
1054 Returns the unconsumed portion of the input.
1055  
1056 =head2 step_state($next)
1057  
1058 Performs these steps:
1059  
1060 =over 4
1061  
1062 =item o Compares the 'current' state to $next
1063  
1064 If they match, returns 0 immediately.
1065  
1066 =item o Calls the exit function, if any, of the 'current' state
1067  
1068 =item o Set the 'current' state to $next
1069  
1070 =item o Calls the entry function, if any, of the new 'current' state
1071  
1072 =item o Returns 1.
1073  
1074 =back
1075  
1076 =head2 transitions($arrayref_of_states)
1077  
1078 See L</Using new()> for details.
1079  
1080 C<transitions> is a parameter to L</new([%args])>.
1081  
1082 =head2 validate()
1083  
1084 Perform validation checks on these parameters to new():
1085  
1086 =over 4
1087  
1088 =item o accepting
1089  
1090 =item o start
1091  
1092 =item o transitions
1093  
1094 =back
1095  
1096 =head1 FAQ
1097  
1098 =head2 How do I protect the code from dying?
1099  
1100 Use L<Capture::Tiny>. See t/report.t for a simple example.
1101  
1102 =head2 What's changed in V 2.00 of C<Set::FA::Element>?
1103  
1104 =over 4
1105  
1106 =item o Put the distro on github
1107  
1108 See L</Repository> below.
1109  
1110 =item o Switch to Moo
1111  
1112 =item o This means method chaining is no longer supported
1113  
1114 =item o Explicitly default the logger to an instance of L<Log::Handler>
1115  
1116 =item o Add maxlevel() and minlevel() for controlling the logger
1117  
1118 =item o Rewrite log so messages do not have the prefix of "$level: "
1119  
1120 =item o Make the synopses in both modules into stand-alone scripts
1121  
1122 See scripts/synopsis.*.pl.
1123  
1124 =item o Add 'use strict' and 'use warnings' to t/*.t
1125  
1126 =item o Move t/pod.t to xt/author/
1127  
1128 =item o Switch from Test::More to Test::Stream
1129  
1130 =item o Remove verbose()
1131  
1132 =back
1133  
1134 =head2 What's changed in V 1.00 of C<Set::FA::Element>?
1135  
1136 Note: I have switched to Moo and Log::Handler.
1137  
1138 =over 4
1139  
1140 =item o Use Moo for getters and setters
1141  
1142 Originally, L<Set::FA::Element> used direct hash access to implement the logic.
1143 I did not want to do that. At the same time, I did not want users to incur the overhead
1144 of L<Moose>.
1145  
1146 So, I've adopted my standard policy of using L<Moo>.
1147  
1148 =item o Rename the new() parameter from accept to accepting
1149  
1150 While direct hash access allowed the author of L<Set::FA::Element> to have a hash key and a method
1151 with the same name, accept, I can't do that now.
1152  
1153 So, the parameter to new() (in L<Set::FA::Element>) is called accepting, and the method is still
1154 called accept().
1155  
1156 =item o Add a parameter to new(), die_on_loop
1157  
1158 This makes it easy to stop a run-away program during development.
1159  
1160 =item o Add a parameter to new(), logger
1161  
1162 See below for details.
1163  
1164 =item o Add a parameter to new(), start
1165  
1166 This must be used to name the start state.
1167  
1168 =item o Chop the states parameter to new()
1169  
1170 The state names are taken from the transitions parameter to new().
1171  
1172 =item o Add a parameter to new(), verbose
1173  
1174 This makes it easy to change the quantity of progress reports.
1175  
1176 =item o Add a method, build_stt() to convert new()'s parameters into a state transition table
1177  
1178 =item o Add a method, current() to set/get the current state
1179  
1180 =item o Add a method, die_on_loop() to set/get the like-named option
1181  
1182 =item o Add a method, id() to set/get the id per object
1183  
1184 =item o Add a method, log() to call the logger object
1185  
1186 =item o Add a method, logger() to set/get the logger object
1187  
1188 =item o Add a method, match(), to retrieve exactly what matched at each transition
1189  
1190 =item o Add a method, report(), to print the state transition table
1191  
1192 =item o Add a method, start() to set/get the start state per object
1193  
1194 =item o Add a method, validate() to validate new()'s parameters
1195  
1196 =item o Add a method, verbose() to set/get the like-named option
1197  
1198 =back
1199  
1200 =head2 Why such a different approach to logging?
1201  
1202 Firstly, L<Set::FA::Element> used L<Log::Agent>. I always use L<Log::Handler> these days.
1203  
1204 By default (i.e. without a logger object), L<Set::FA::Element> prints messages to STDOUT, and dies
1205 upon errors.
1206  
1207 However, by supplying a log object, you can capture these events.
1208  
1209 Not only that, you can change the behaviour of your log object at any time, by calling
1210 L</logger($logger_object)>.
1211  
1212 Specifically, $logger_object -> log(debug => 'Entered x()') is called at the start of each public
1213 method.
1214  
1215 Setting your log level to 'debug' will cause these messages to appear.
1216  
1217 Setting your log level to anything below 'debug', e.g. 'info, 'notice', 'warning' or 'error', will
1218 suppress them.
1219  
1220 Also, L</step_state($next)> calls:
1221  
1222 $self -> log(info => "Stepped from state '$current' to '$next' using rule /$rule/ to match
1223 '$match'");
1224  
1225 just before it returns.
1226  
1227 Setting your log level to anything below 'info', e.g. 'notice', 'warning' or 'error', will suppress
1228 this message.
1229  
1230 Hence, by setting the log level to 'info', you can log just 1 line per state transition, and no other
1231 messages, to minimize output.
1232  
1233 Lastly, although this logging mechanism may seem complex, it has distinct advantages:
1234  
1235 =over 4
1236  
1237 =item o A design fault in L<Log::Agent> (used by the previous author):
1238  
1239 This method uses a global variable to control the level of logging. This means the code using
1240 L<Set::FA::Element> can (also) use L<Log::Agent> and call logconfig(...),
1241 which in turn affects the behaviour of the logging calls inside those other modules.
1242 I assume this design is deliberate, but I certainly don't like it, because (I suspect) it means any
1243 running Perl program which changes the configuration affects all other running programs using
1244 L<Log::Agent>.
1245  
1246 =item o Log levels
1247  
1248 You can configure your logger object, either before calling new(), or at any later time, by
1249 changing L</minlevel([$string])> or L</maxlevel([$string])>.
1250  
1251 That allows you complete control over the logging activity.
1252  
1253 =back
1254  
1255 The only log levels output by this code are (from high to low): debug, info, warning and error.
1256  
1257 Error messages are self-documenting, in that when you trigger them, you get to read them...
1258  
1259 =head1 Machine-Readable Change Log
1260  
1261 The file Changes was converted into Changelog.ini by L<Module::Metadata::Changes>.
1262  
1263 =head1 Version Numbers
1264  
1265 Version numbers < 1.00 represent development versions. From 1.00 up, they are production versions.
1266  
1267 =head1 Credit
1268  
1269 See L<Set::FA/Credit>.
1270  
1271 =head1 See Also
1272  
1273 See L<Set::FA/See Also>.
1274  
1275 =head1 Repository
1276  
1277 L<https://github.com/ronsavage/Set-FA>
1278  
1279 =head1 Support
1280  
1281 Email the author, or log a bug on RT:
1282  
1283 L<https://rt.cpan.org/Public/Dist/Display.html?Name=Set::FA>
1284  
1285 =head1 Author
1286  
1287 L<Set::FA::Element> was written by Mark Rogaski and Ron Savage I<E<lt>ron@savage.net.auE<gt>> in
1288 2011.
1289  
1290 My homepage: L<http://savage.net.au/index.html>
1291  
1292 =head1 Copyright
1293  
1294 Australian copyright (c) 2011, Ron Savage.
1295  
1296 All Programs of mine are 'OSI Certified Open Source Software';
1297 you can redistribute them and/or modify them under the terms of
1298 The Perl License, a copy of which is available at:
1299 http://www.opensource.org/licenses/index.html
1300  
1301 =cut
↑ Summary FA.pm »