Perform/DigestPer.pm untested

filter: Statementstmt 0.0% 0 / 724 Branchbran 0.0% 0 / 320 Conditioncond 0.0% 0 / 140 MC/DCmcdc 0.0% 0 / 83 Subroutinesub 0.0% 0 / 39 Podpod 0.0% 0 / 31 totaltotal 0.0% 0 / 1337 CC 161 SCAR 70.9
CC
161
Cov
0%
read_instructions
3782.0
lookup_attributes_post
182.0
read_screen
132.0
CRAP 1203.6
1 =head1 NAME
2  
3 DBIx::Perform::DigestPer - "Perform" screen file digester
4  
5 Digests an Informixoid .per file and make a string suitable for
6 writing to a file or just eval'ing.
7  
8 The manual used as reference for the Perform scripting language is:
9  
10 INFORMIX-SQL Reference, INFORMIX-SQL Version 6.0, April 1994,
11 Part No. 000-7607
12  
13 =head1 MODULE VERSION
14  
15 0.04
16  
17 =head1 SYNOPSIS
18  
19 use DBIx::Perform::DigestPer;
20 $desc = digest(*INFILE_HANDLE);
21 # now do the right thing with $desc
22  
23 shell> perl -MDBIx::Perform::DigestPer -e'digest_file("foo.per")'
24 # writes file foo.pps or named in 2nd argument.
25 # now read and do the right thing with foo.pps
26  
27 =head1 REQUIREMENTS
28  
29 Data::Dumper
30  
31 =head1 DESCRIPTION
32  
33 Digests an Informix "Perform" screen descriptor file into a form usable by
34 the Perform emulator B<Perform.pm>. May be used inline or to write a file.
35  
36 Among other things, it digests the screen layout into a series of Curses
37 widget specs, as either Label or TextField types.
38  
39 The output string/file is evaluable Perl source code, which
40 sets four variables:
41  
42 $db: name of database
43  
44 $screen: screen descriptor, a hash including a Curses::Forms spec.
45 Form fields' widgets are named as labelled (e.g. 'f000').
46  
47 $tables: array of table names.
48  
49 $attrs: hash of field names to [table column attributes] .
50 The 'attributes' string is unparsed.
51  
52  
53  
54 CHANGES from version 0.05:
55 Total rewrite of the parsing of the "attribute" section,
56 greatly expanded parsing of the "instructions" section.
57  
58 User creates an intermediate file in YAML with "convert_per_to_yml" sub.
59  
60 User runs DBIx::Perform on the .yml file.
61  
62 Brenton Chapin, Martin Baer, et. al...
63 Valtech (www.valtech.com)
64 =cut
65  
66 package DBIx::Perform::DigestPer;
67 use strict;
68 use base 'Exporter';
69  
70 use vars qw(@EXPORT_OK $VERSION %HEADING_WORDS);
71  
72 BEGIN {
73 @EXPORT_OK = qw(digest digest_file convert_per_to_xml convert_per_to_yml );
74 $VERSION = '0.695';
75  
76 %HEADING_WORDS =
77 map { ( $_, 1 ) } qw(screen tables attributes instructions end);
78  
79 }
80  
81 # debug: set (unset) in runtime env
82 $::TRACE = $ENV{TRACE};
83 $::TRACE_DATA = $ENV{TRACE_DATA};
84  
85 #use DBIxPerformCFuncs;
86 #use XML::Dumper;
87 use YAML;
88 use Data::Dumper;
89 use DBIx::Perform::FieldList;
90  
91 =head2 digest
92  
93 digest (IOHandle_Ref)
94  
95 Digests an Informix .per file into a string that evaluates to a Perform
96 descriptor.
97  
98 =cut
99  
100 our $VER_DATE = '2007-10-17';
101  
102 our $TABLES;
103 our $FieldList;
104 our $DB;
105  
106 sub digest {
107 shift if ( $_[0] eq __PACKAGE__ );
108 my $ioh = shift;
109  
110 warn "TRACE: entering digest\n" if $::TRACE;
111  
112 my $parser = new DBIx::Perform::DigestPer::Parser($ioh);
113 my $word;
114 my ( $db, $tables, $atts, $instrs );
115 my $screens = [];
116 local $TABLES; # for attributes parser to check
117 my $connected = 0;
118 while ( $word = $parser->read_token('true') ) {
119 if ( $word eq 'database' && !$connected ) {
120 $connected = 1;
121 $db = read_database($parser);
122 }
123 elsif ( $word eq 'screen' ) {
124 push( @$screens, read_screen($parser) ); # might return many
125 }
126 elsif ( $word eq 'tables' ) {
127 $TABLES = $tables = read_tables($parser);
128 }
129 elsif ( $word eq 'attributes' ) {
130 read_attributes($parser); # fills global $FieldList
131 $FieldList->print_list if $::TRACE_DATA;
132 }
133 elsif ( $word eq 'instructions' ) {
134 $instrs = read_instructions($parser);
135 }
136 }
137 my $str = output_string( $db, $screens, $tables, $instrs, $VER_DATE );
138 my @ret = ( $str, $FieldList );
139  
140 # need to close the database?
141  
142 return \@ret;
143 }
144  
145 sub read_database {
146 my $parser = shift;
147  
148 warn "TRACE: entering read_database \n" if $::TRACE;
149  
150 my $db_name = $parser->read_token(); # just the name.
151 $DB = DBIx::Perform::DButils::open_db($db_name);
152  
153 warn "TRACE: leaving read_database \n" if $::TRACE;
154  
155 return $db_name;
156 }
157  
158 sub read_screen {
159 warn "TRACE: entering read_screen\n" if $::TRACE;
160 my @screens;
161 my $parser = shift;
162  
163 my $result = {};
164 my $word;
165  
166 #default height,width. Page 2-10 of the manual
167 my $height = 20;
168 my $width = 80;
169 while ( $word = $parser->read_token() ) {
170 if ( $word eq 'size' ) {
171  
172 # read size...
173 $height = 0 + $parser->read_token();
174 $height = 20 if $height > 20;
175 my $by = $parser->read_token();
176 $width = 0 + $parser->read_token();
177 die "Expected 'by' but got '$by'"
178 if ( $by ne 'by' );
179 $result->{'MINSIZE'} = [ $width, $height ];
180 }
181 elsif ( $word eq '{' ) {
182  
183 # read screen format
184 my $widgets = {};
185 my $line;
186 my $lineno = 0;
187 my $labelno = '000';
188 my @fields = ();
189 my $more = 1;
190 while ($more) {
191 $line = $parser->read_line();
192 if ( $line =~ /(^|[^\\]|(\\\\)+)\}/ ) {
193 $line = $1;
194 $more = 0;
195 last if $line eq '';
196 }
197 if ( $lineno >= $height ) {
198 push(
199 @screens,
200 {
201 WIDGETS => $widgets,
202 FIELDS => [@fields],
203 LINES => $lineno,
204 }
205 );
206 $widgets = {};
207 @fields = ();
208 $lineno = 0;
209 }
210 my $x = 0;
211 while ( $line =~ s/\t/' ' x (8-pos($line)%8)/e ) { }
212 $line =~ s/\\(.)/$1/;
213 while ( $line =~ /(\s*)(\[\s*(\w+)\s*\]|[^\s[][^[]*)/g ) {
214 my $pre = $1;
215 my $match = $2;
216 my $id = $3;
217 $x += length($pre);
218 my $cols = length($match);
219 if ($id) {
220  
221 # it\'s a field
222 # Note, the OnEnter/OnExit subs must be supplied
223 # by the Perform emulator.
224 $widgets->{$id} = {
225 TYPE => 'TextField',
226 COLUMNS => $cols - 2,
227 Y => $lineno,
228 X => $x + 1,
229 BORDER => 0
230 };
231 push( @fields, $id );
232 }
233 else {
234  
235 # it\'s a label
236 $match =~ s/\s$//; # ignore trailing whitespace
237 $widgets->{"label_$labelno"} = {
238 TYPE => 'Label',
239 COLUMNS => $cols,
240 Y => $lineno,
241 X => $x,
242 VALUE => $match
243 };
244 $labelno++;
245 }
246 $x += $cols;
247 }
248 $lineno++;
249 }
250 push(
251 @screens,
252 {
253 WIDGETS => $widgets,
254 FIELDS => [@fields],
255 LINES => $lineno
256 }
257 );
258 }
259 elsif ( lc($word) eq 'end' ) {
260 return @screens;
261 }
262 else {
263 die "Unknown screen section directive '$word'";
264 }
265 }
266 return @screens;
267 }
268  
269 sub read_tables {
270 my $parser = shift;
271  
272 warn "TRACE: entering read_tables\n" if $::TRACE;
273  
274 my $line;
275 my @tables;
276 my $in_comment = undef;
277 my $builder = undef;
278  
279 while ( $line = $parser->read_line() ) {
280 chomp $line;
281 undef $builder;
282  
283 # scrub the line for comments
284 my @line = split //, $line;
285 for ( my $i = 0 ; $i <= $#line ; $i++ ) {
286 my $c = $line[$i];
287 if ( $c eq '{' ) {
288 $in_comment = 1;
289 $i++; # skipt it
290 $builder .= ' ' if $i != $#line;
291 }
292 if ( $c eq '}' ) {
293 undef $in_comment;
294 $i++; # skipt it
295 }
296 $builder .= $line[$i] if !defined $in_comment;
297 }
298 push( @tables, $builder =~ /(\w+)/g );
299 }
300 warn "TRACE: leaving read_tables\n" if $::TRACE;
301 return [@tables];
302 }
303  
304 # POST PROCESSING
305  
306 # There are a few "post" files below.
307 # The basic idea is that the attribute parsing
308 # gathers up the information for each line (ends with ";")
309 # and the post processing, handles issues that span lines
310 # or generate new field list elements ( like lookup field objects).
311 # Botton line: post processing occurs in "post" subroutines
312  
313 # Displayonly post processing
314 sub displayonly_post_processing {
315 my $field = shift;
316  
317 # displayonly fields are "virtual" (they don't exist in the DB)
318 # the column name has the value of the field tag
319 if ( defined( $field->{displayonly} ) ) {
320 $field->{column_name} = $field->{field_tag};
321 $field->{table_name} = "displaytable";
322 }
323 return $field;
324 }
325  
326 # Tables post processing ( not related to read_tables )
327 sub table_post_processing {
328 my $field = shift;
329  
330 my @tables = @{$TABLES};
331 my $previous_table;
332 if ( $#tables == 0 ) {
333 $previous_table = $tables[0];
334 }
335 if ( $field->{table_name} eq '' ) {
336  
337 # go to the db and get the table name
338 # look for the column in each table
339 # fails if there is a dup across tables
340  
341 my $column = $field->{column_name};
342 my $database = $DB;
343 my $driver = $database->{'Driver'}->{'Name'};
344  
345 if ( $driver eq "Informix" ) {
346 foreach my $table (@tables) {
347 my $cname;
348 my $type;
349  
350 my $query = "SELECT * FROM $table";
351 my $sth = $database->prepare($query);
352 if ($sth) {
353 my @db_cols = @{ $sth->{NAME} }; # Column names
354 my @res = grep( /$column/, @db_cols );
355 if ( defined(@res) ) {
356 $field->{table_name} = $table;
357 last;
358 }
359 }
360 }
361 }
362 else { # put Oracle solution here
363 die
364 "subroutine \"table_post_processing\" for $driver is not implemented.";
365 }
366 }
367 if ( uc $field->{table_name} eq uc $field->{column_name} ) {
368 $field->{table_name} = $previous_table;
369 }
370  
371 return $field;
372 }
373  
374 # Field tag joins postprocessing
375 sub field_tag_joins_post {
376 my $field = shift;
377 my $previous_field = shift;
378  
379 return $field
380 if defined( $field->{display_only} );
381  
382 # here are the primary examples of these joins:
383 # 1: field_tag = tab1.col = tab2.col, attributes;
384 # 2: = tab1.col, attributes;
385  
386 my $previous_tag = '';
387 my $previous_table = '';
388 my $previous_col = '';
389  
390 if ( defined($previous_field) ) {
391 ( $previous_tag, $previous_table, $previous_col ) =
392 $previous_field->get_names;
393 }
394  
395 # this takes care of #2
396 if ( uc( $field->{field_tag} ) eq "EMPTY_FIELD_TAG" ) {
397 $field->{field_tag} = $previous_tag;
398 }
399 {
400 my $tbl = $field->{table_name};
401 my $col = $field->{column_name};
402 $field->{verify} = 1 if
403 $field->{line} =~ /\*\s*$tbl\.$col(\W|$)/;
404 }
405  
406 # adding the top-level field object for this itteration
407 $FieldList->add_field($field);
408  
409 # this takes care of #1 - new field for each tab.col
410 if ( defined( $field->{field_tag_join_hash} ) ) {
411 my %join = %{ $field->{field_tag_join_hash} };
412  
413 my $size = 0;
414 my $index = 0;
415 $size += keys %join;
416  
417 while ( $index < $size ) {
418  
419 my $join_table = $join{$index}->{join_table};
420 my $join_column = $join{$index}->{join_column};
421  
422 my $new_field = $field->duplicate;
423 delete $new_field->{verify};
424 delete $new_field->{line};
425 # $new_field->{field_tag_join_hash} = undef;
426 $new_field->{table_name} = $join_table;
427 $new_field->{column_name} = $join_column;
428 $new_field->{verify} = 1 if
429 ($field->{line} =~ /\*\s*$join_table\.$join_column(\W|$)/);
430  
431 # expand lookup attributes (if any) for the new field
432 lookup_attributes_post($new_field);
433  
434 # add new field
435 $FieldList->add_field($new_field);
436  
437 $index++;
438 }
439 }
440 warn Data::Dumper->Dump( [$field], ['field in digest'] ) if $::TRACE_DATA;
441  
442 return $field;
443 }
444  
445 # Lookup attribute postprocessing
446 sub lookup_attributes_post {
447 my $field = shift;
448  
449 # if field contains a lookup statement, expand the
450 # embedded field_tags into new objects & add to FieldList
451 # new fields can (currently always do) have the attribute
452 # of the parent. Currently ordered as they appear in the
453 # .per file
454  
455 my %instances = %{ $field->{lookup_hash} }
456 if defined( $field->{lookup_hash} );
457  
458 if ( defined(%instances) ) {
459 my ( $size, $index, $join_table, $join_column, $verify );
460 my $index = 0;
461 my $size = 0;
462 $size += keys %instances;
463  
464 while ( $index < $size ) {
465  
466 #warn Data::Dumper->Dump([%instances], ['instances in digest']);
467  
468 my %lookup = %{ $instances{$index} };
469  
470 # capture the join table and column
471 $join_table = $join_column = $verify = undef;
472  
473 foreach my $k ( keys(%lookup) ) {
474 my %h = %{ $lookup{$k} };
475 my $t = lc $h{join_table};
476 my $c = lc $h{join_column};
477 my $v = $h{verify};
478  
479 $t = undef if $t eq '';
480 $c = undef if $c eq '';
481 $v = undef if $v eq '';
482  
483 $join_table = $t if defined($t);
484 $join_column = $c if defined($c);
485 $verify = $v if defined($v);
486 }
487  
488 my @join_order;
489 $#join_order = 1000;
490 foreach my $k ( keys(%lookup) ) {
491 warn Data::Dumper->Dump( [%lookup], ['lookup in digest'] )
492 if $::TRACE_DATA;
493  
494 my $new_field = new DBIx::Perform::Field;
495  
496 # $new_field->{lookup_hash} = undef;
497 # $new_field->{field_tag_join_hash} = undef;
498  
499 $new_field->{field_tag} = lc $k;
500 # $new_field->{line} = "Lookup Field";
501  
502 my %h = %{ $lookup{$k} };
503 foreach my $l ( keys(%h) ) {
504 $new_field->{$l} = lc $h{$l};
505 }
506 $new_field->{join_table} = $join_table;
507 $new_field->{join_column} = $join_column;
508 $new_field->{verify} = $verify if $verify;
509  
510 # lookups only "display" field values
511 # and only on a match between them
512  
513 ## not sure that the above comment is true at runtime
514 # $new_field->{noentry} = 1;
515 # $new_field->{noupdate} = 1;
516  
517 if ( uc $new_field->{table_name} eq "EMPTY_TABLE_NAME" ) {
518 # $new_field->{table_name} = $field->{table_name};
519 $new_field->{table_name} = $join_table;
520 }
521  
522 $new_field->{active_tabcol} =
523 $field->{table_name} . "." . $field->{column_name};
524  
525 # add the new field
526 # FIX: currently lookup fields in the same instance
527 # are unordered. This will affect taborder - may not matter
528 # so this is now an attempt to order these guys....
529 my $jindex = $new_field->{join_index};
530 @join_order[$jindex] = $new_field;
531 }
532  
533 # add new fields in the order they were parsed
534 foreach my $new_field (@join_order) {
535 $FieldList->add_field($new_field) if defined $new_field;
536 }
537  
538 $index++;
539 }
540 }
541 return $field;
542 }
543  
544 # Include attribute post processing
545 sub include_post_processing {
546 my $field = shift;
547  
548 $field->{include} = 1
549 if defined( $field->{range} );
550 $field->{include} = 1
551 if defined( $field->{include_values} );
552  
553 return $field;
554 }
555  
556 # Creates field objects after compling a line of the parse
557 # to hold the line information returned from the parser
558 sub make_field_obj {
559 my $line = shift;
560 my $previous_field = shift;
561 my $gparser = shift;
562  
563 # strip out comments { ... } FIX: needs regex for "xxx { {...} } yyy;"
564 my @text = split( /\{.*\}/, $line );
565 my $parsable = $#text > 0 ? @text[$#text] : $text[0];
566  
567 my $field = new DBIx::Perform::Field;
568  
569 if ( $field->parse_line($parsable, $gparser) ) {
570 $field = table_post_processing($field);
571 $field = field_tag_joins_post( $field, $previous_field );
572 $field = lookup_attributes_post($field);
573 $field = displayonly_post_processing($field);
574 $field = include_post_processing($field);
575 }
576 delete $field->{line};
577 return $field;
578 }
579  
580 # Reads and processes the attributes section of a "per" file
581 sub read_attributes {
582 my $parser = shift;
583  
584 warn "TRACE: entering read_attributes\n" if $::TRACE;
585  
586 my $line;
587 my $lines = '';
588  
589 my $previous_field = undef;
590 $FieldList = new DBIx::Perform::FieldList;
591  
592 my $in_comment = undef;
593 my $builder = undef;
594  
595 my $grammar = DBIx::Perform::AttributeGrammar::get_grammar;
596 my $gparser = Parse::RecDescent->new($grammar);
597  
598 while ( $line = $parser->read_line() ) {
599 chomp $line;
600 undef $builder;
601  
602 # scrub the line for comments
603 my @line = split //, $line;
604 for ( my $i = 0 ; $i <= $#line ; $i++ ) {
605 my $c = $line[$i];
606 if ( $c eq '{' ) {
607 $in_comment = 1;
608 $i++; # skipt it
609 $builder .= ' ' if $i != $#line;
610 }
611 if ( $c eq '}' ) {
612 undef $in_comment;
613 $i++; # skipt it
614 }
615 $builder .= $line[$i] if !defined $in_comment;
616 }
617 $lines .= ' ' . $builder;
618  
619 return if $builder =~ /^\s*end\s*$/i;
620 next unless $builder =~ /;/;
621  
622 my $tmp_line = $lines;
623 my $field = make_field_obj( $tmp_line, $previous_field, $gparser );
624  
625 $previous_field = $field;
626 $lines = '';
627 }
628 warn "TRACE: leaving read_attributes\n" if $::TRACE;
629 warn "done parsing attributes" if $::TRACE;
630 }
631  
632 sub read_instructions {
633 my $parser = shift;
634  
635 my $line;
636 my $instrs = {};
637 my $got_a_line = 0;
638 my $lcomment = 0;
639 my $csm = 0;
640 my @cjcols;
641 my $cjverify = 0;
642 my %current_cj;
643  
644 while ( $got_a_line ? 1 : { $line = $parser->read_line() } ) {
645 $got_a_line = 0;
646 last if !defined $line;
647  
648 # warn "instruction = :$line:\n";
649 if ($lcomment) {
650 $line =~ s/[^}]*//;
651 if ( $line =~ s/}// ) {
652 $lcomment = 0;
653 }
654 }
655 $line =~ s/^\s*{[^}]*}//;
656 if ( $line =~ s/^\s*{.*?// ) {
657 $lcomment = 1;
658 next;
659 }
660 next if $line =~ /^\s*$/;
661 last if $line =~ /^\s*end\s*$/i;
662 if ( $line =~ /^\s*(\w+)\s+master\s+of\s+(\w+)/i ) {
663 push( @{ $$instrs{MASTERS} }, [ $1, $2 ] );
664 }
665 elsif ( $line =~ s/composites//i || $csm ) {
666  
667 #The "composites" instruction seems to be useless.
668 #If 2 or more columns of 2 tables are joined, they must be
669 # a) joined in the attributes section
670 # b) and listed in a "composites" instruction.
671 #From page 2-57:
672 # "Each column included in a composite join must also be individually
673 # joined in the ATTRIBUTES section of the form specification."
674 #and
675 # "There can be no additional joins between columns of the two tables
676 # that are not included in the composite join"
677 #In other words, having a "composites" instruction to
678 #join 2+ columns of 2 tables without joining them in the attributes
679 #section is, according to the manual, not allowed.
680 #However, sformbld only generates a warning in this case.
681 #In the other way around, having 2+ columns of 2 tables joined in
682 #the attributes section without a "composites" instruction,
683 #sformbld will produce an error.
684 #So, checking for joins in the "attributes" section and treating any
685 #joins after the first one between two tables as part of a composite join
686 #should cover this situation, without needing to check for a "composites"
687 #instruction. So all we will do here is parse the instruction.
688 #We won't bother issuing an error if it doesn't match what was already
689 #completely specified in the "attributes" section.
690 #During execution, this instruction is used for
691 #verification of composite joins.
692 if ( $csm == 0 ) {
693 %current_cj = ();
694 $csm = 1;
695 }
696 $cjverify = 1 if $line =~ s/^\s*\*// && $csm == 11;
697 $csm++ if ( $line =~ s/^\s*\<// && ( $csm == 1 || $csm == 11 ) );
698  
699 do {
700 do {
701 if (
702 $line =~ s/^\s*([A-Za-z]\w*)//
703 && ( $csm == 2
704 || $csm == 12
705 || $csm == 3
706 || $csm == 13 )
707 )
708 {
709 if ( $csm == 2 ) {
710 $current_cj{TBL1} = $1;
711 $csm++;
712 }
713 if ( $csm == 12 ) {
714 $current_cj{TBL2} = $1;
715 $current_cj{VFY2} = $cjverify ? '*' : '';
716 $cjverify = 0;
717 $csm++;
718 }
719 $csm++;
720 }
721 $csm++
722 if $line =~ s/^\s*\.// && ( $csm == 4 || $csm == 14 );
723 if ( $line =~ s/^\s*([A-Za-z]\w*)//
724 && ( $csm == 5 || $csm == 15 ) )
725 {
726 push @cjcols, $1;
727 $csm++;
728 }
729 $csm -= 3 if $line =~ s/^\s*\,//;
730 next if ( $line =~ /^\s*$/ );
731 } while ( $csm == 3 || $csm == 13 );
732  
733 $csm++ if $line =~ s/^\s*\>// && ( $csm == 6 || $csm == 16 );
734 if ( $csm == 7 ) {
735 push @{ $current_cj{COLS1} }, @cjcols;
736 @cjcols = ();
737 $csm = 11;
738 }
739 if ( $csm == 17 ) {
740 push @{ $current_cj{COLS2} }, @cjcols;
741 push( @{ $$instrs{COMPOSITES} }, \%current_cj );
742 @cjcols = ();
743 $csm = 0;
744 }
745 next if ( $line =~ /^\s*$/ );
746 } while ($csm);
747 }
748 elsif ( $line =~ /delimiters/i ) {
749 warn "'delimiters' instruction not implemented\n";
750 }
751 elsif ( $line =~
752 /(before|after)\s+(((editadd|editupdate|remove|add|update|query|display)\s+)+)of\s+(([\w.]+)(\s*,\s*[\w.]+)*)\s*/gi
753 )
754 {
755  
756 #my $action = substr($line,pos($line));
757 # control block
758 my $when = $1;
759 my $ops = $2;
760 my $col = $5;
761 $line =~ /\G(.*)/;
762 my $action = $1;
763 if ( !$action || $action =~ /^\s*$/ ) {
764 $action = $parser->read_line();
765 }
766 my $ifsm = 0; #holds state machine value for "if" statements
767 my @ifstk; #stack for state machine for "if" statements
768  
769 # states are: 0 if 1 then 2 begin 4 end 5 else 6 begin 8 end 0
770 my @ifact; #stack for actions within "if" statements
771 my $comment = 0;
772 do {
773 my @action;
774 my $actionref;
775  
776 #FIX: don't want the reserved words acted on if in a string literal
777 $action =~ /\A\s*(.*?)\s*\z/;
778 $action = $1;
779 my ( $updateif, $newif ) = ( 0, 0 );
780  
781 # warn " action = :$ifsm:$action:\n";
782 if ( length $action > 0 && !$comment ) {
783 if ( $action =~ s/^nextfield\s*=\s*(\w+)//i ) {
784 $actionref = [ "nextfield", $1 ];
785 $updateif = 1;
786 }
787 elsif ( $action =~ s/^abort//i ) {
788 $actionref = ["abort"];
789 $updateif = 1;
790 }
791 elsif ( $action =~ s/^let\s+(\w+)\s*=\s*//i ) {
792 my $perfname = $1;
793  
794 #my $perfexpr = $action =~ /\G(.*)/;
795 $action =~ s/;\s*$//;
796 $action = convert_perform_logic_to_perl($action);
797 $actionref = [ "let", $perfname, $action ];
798 $action = "";
799 $updateif = 1;
800 }
801 elsif ( $action =~
802 s/^call\s+(\w+)\s*\((([^"\)]*|"([^\\"]|\\.)*")*)\)//i )
803 {
804  
805 #call_extern_C_func($1, $2);
806 my $parms = convert_perform_logic_to_perl($2);
807 $actionref = [ "call", $1, $parms ];
808 $updateif = 1;
809 }
810 elsif ( $action =~
811 s/^comments\s+((bell\s+|reverse\s+){0,2})//i )
812 {
813 my $bellrev = $1;
814 $action =~ s/^\s*"(.*?)"\s*$/$1/;
815 $actionref = [ "comments", $bellrev, $action ];
816 $action = "";
817 }
818 elsif ( $action =~ s/^if[\s(]//i ) {
819 if ( $ifsm == 1 ) {
820 warn "ERROR: if if (shouldn't reach this msg)\n";
821 }
822 elsif ( $ifsm == 2 ) {
823 $ifsm = 5;
824 }
825 elsif ( $ifsm == 5 ) {
826 $ifsm = pop @ifstk;
827 pop @ifact;
828 }
829 push @ifstk, $ifsm;
830 my $condition;
831 ( $condition, $ifsm, $action ) =
832 get_if_condition( $parser, $action );
833 $actionref = [ "if", $condition, [], [] ];
834 $newif = 1;
835 push @ifact, $actionref;
836  
837 # warn "if :$condition:\nrest :$action:\n";
838 }
839 elsif ( $action =~ s/^else(\s|$)//i ) {
840 if ( $ifsm == 5 ) {
841 $ifsm = 6;
842 }
843 else {
844 warn "ERROR: illegal 'else'\n";
845 }
846 }
847 elsif ( $action =~ s/^begin(\s|;|$)//i ) {
848 if ( $ifsm == 2 || $ifsm == 6 ) {
849 $ifsm += 2;
850 }
851 else {
852 warn "ERROR: illegal 'begin'\n";
853 }
854 }
855 elsif (
856 $action =~ /^end(\s|;|$)/i
857  
858 # && ($ifsm == 4 || $ifsm == 8)) {
859 && ( @ifstk > 0 )
860 )
861 {
862 $action =~ s/^end//;
863  
864 # foreach my $ist (@ifstk) { warn "$ist\n"; }
865 while ( $ifsm != 4 && $ifsm != 8 && @ifstk > 0 ) {
866 $ifsm = pop @ifstk;
867 pop @ifact;
868 }
869 if ( @ifstk == 0 ) {
870 $got_a_line = 1;
871 $line = "end";
872 next;
873 }
874 if ( $ifsm == 4 ) {
875 $ifsm = 5;
876 }
877 else {
878 $ifsm = pop @ifstk;
879 pop @ifact;
880 }
881 }
882 elsif ( $action =~ s/{// ) {
883 $comment = 1;
884 }
885 else {
886 if ( $action =~
887 /^(before|after|on beginning|on ending|\w+\s+master of|composites|delimiters|end)/i
888 )
889 {
890 if ( $ifsm == 4 || $ifsm == 8 ) {
891 warn "ERROR: instruction inside block $1\n";
892 }
893 $got_a_line = 1;
894 $line = $action;
895 next;
896 }
897 elsif ( $action =~
898 s/(\w+)\s*\((([^"\)]*|"([^\\"]|\\.)*")*)\)//i )
899 {
900  
901 #else it should be a call to a C function
902 $actionref = [ "call", $1, $2 ];
903 $updateif = 1;
904 }
905 else {
906 warn "ERROR: no such action $action\n";
907 $action = "";
908 }
909 }
910 if ( ( $updateif || $ifsm ) && length $actionref > 0 ) {
911 my $stacktop =
912 $newif ? $ifact[ $#ifact - 1 ] : $ifact[$#ifact];
913 my $prvst = $ifsm;
914 $prvst = $ifstk[$#ifstk] if $newif;
915 $newif = 0;
916  
917 # warn "state: $prvst,$ifsm\n";
918 if ( $prvst == 2 || $prvst == 4 ) {
919 push @{ $$stacktop[2] }, $actionref;
920 $actionref = "";
921 }
922 elsif ( $prvst == 6 || $prvst == 8 ) {
923 push @{ $$stacktop[3] }, $actionref;
924 $actionref = "";
925 }
926 }
927 if ($updateif) {
928 $updateif = 0;
929 if ( $ifsm == 2 ) {
930 $ifsm = 5;
931 }
932 elsif ( $ifsm == 5 || $ifsm == 6 ) {
933 $ifsm = pop @ifstk;
934 pop @ifact;
935 }
936 }
937 if ( length $actionref > 0 ) {
938 while ( $ops =~ /(\w+)/g ) {
939 my $op = $1;
940 push(
941 @{ $$instrs{CONTROLS}{$col}{$op}{$when} },
942 $actionref
943 );
944 }
945 }
946 }
947 if ($comment) {
948 $action =~ s/[^}]*//;
949 if ( $action =~ s/}// ) {
950 $comment = 0;
951 }
952 }
953 $action =~ /\A\s*(.*?)\s*\z/;
954 $action = $1;
955 $action =~ s/^;$//;
956 if ( length $action == 0 ) {
957 $action = $parser->read_line();
958 }
959  
960 # Perl squirreliness: "last", "next" ignore "do while" blocks
961 } while ($action);
962 }
963 else {
964 warn "Unrecognized instruction line:\n$line\n";
965 }
966 }
967 return $instrs;
968 }
969  
970 sub get_if_condition {
971 my $parser = shift;
972 my $action = shift;
973  
974 # $action =~ s/^if//;
975 my $condition = "";
976 my $q = 0;
977  
978 while (1) {
979 my $actunstrung = $action;
980 $actunstrung =~ s/\\./xx/g; #remove \" by removing all \.
981 $actunstrung = ' ' . $actunstrung . ' ';
982 my $i = 0;
983 my $j = length $actunstrung;
984 while ( $i < $j ) {
985 while ( !$q && $i < $j ) {
986 if ( substr( $actunstrung, $i, 6 ) =~ /[\s)](then|else)\s/i ) {
987 my $which = $1;
988 my $acttrim = substr( $action, 0, $i );
989 $acttrim =~ s/^\s+/ /;
990 $condition .= $acttrim;
991 $condition = convert_perform_logic_to_perl($condition);
992 return (
993 $condition,
994 $which =~ /then/i ? 2 : 6,
995 substr( $action, $i + 5 )
996 );
997 }
998 if ( substr( $actunstrung, $i, 7 ) =~ /[\s)](if|begin|end)\s/i )
999 {
1000 warn "ERROR: 'if' cannot be followed by $1\n";
1001 }
1002 $q = 1 if substr( $actunstrung, $i, 1 ) eq '"';
1003 $i++;
1004 }
1005 if ( $i >= $j ) {
1006 last;
1007 }
1008 while ( $q && $i < $j ) {
1009 $q = 0 if substr( $actunstrung, $i, 1 ) eq '"';
1010 $i++;
1011 }
1012 }
1013 $action =~ s/^\s+/ /; #need to do much more than trim space
1014 $condition .= $action;
1015 if ( $action = $parser->read_line() ) { }
1016 else {
1017 warn "ERROR: premature end of file\n";
1018 return ( "", "", "" );
1019 }
1020 }
1021 }
1022  
1023 #removes all string literals to an array, and remove all comments.
1024 # leaves " in place of each string
1025 sub pull_strings {
1026 my $strung = shift;
1027 my @strs;
1028 my $unstrung = $strung;
1029  
1030 #remove \" by removing all \.
1031 $unstrung =~ s/\\./xx/g;
1032  
1033 my $e = length $strung;
1034  
1035 # $i is index into the string, $q = 1 (q for "quote") if inside
1036 # a string literal, and $r = 1 (r for "remark") if inside a comment
1037 my ( $i, $j, $q, $r ) = ( 0, 0, 0, 0 );
1038 my @so = split //, $strung;
1039 my @su = split //, $unstrung;
1040 my @cb;
1041 my ( $co, $c );
1042 my $strb;
1043 for ( $i = 0 ; $i < $e ; $i++ ) {
1044 $co = $so[$i];
1045 $c = $su[$i];
1046 $r = 1 if ( $c eq '{' && !$q );
1047 if ( $c eq '"' && !$r ) {
1048  
1049 #entering or leaving a string literal (and not inside a comment)
1050 $q ^= 1;
1051 if ($q) {
1052 $strb = $i + 1;
1053 $cb[ $j++ ] = '"';
1054 }
1055 else {
1056 $su[$i] = 'x';
1057 push @strs, substr( $strung, $strb, $i - $strb );
1058 }
1059 }
1060 else {
1061 if ( $q || $r ) {
1062 $su[$i] = 'x';
1063 }
1064 else {
1065 $cb[ $j++ ] = $co;
1066 }
1067 }
1068 $r = 0 if ( $c eq '}' && $r );
1069 }
1070 if ($q) {
1071 warn "ERROR: no ending \" for string literal\n";
1072 }
1073 $unstrung = join '', @cb;
1074 return ( $unstrung, @strs );
1075 }
1076  
1077 #pull all field tags and replace them with 'v' (v is for variable)
1078 #return the string with all field tags removed, and an array of field_tags
1079 #Expects input that has already had string literals and comments removed
1080 #as done by the subroutine "pull_strings"
1081 sub pull_field_tags {
1082 my $tagged = shift;
1083 my @field_tags;
1084  
1085 #manual, page 2-12: First character (of a field-tag) must be a letter;
1086 #the rest of the tag can include letters, numbers, and underscores.
1087 while ( $tagged =~ s/([A-Za-z]\w*)/\#/ ) {
1088 push @field_tags, $1;
1089 }
1090 $tagged =~ s/#\s*\(/c\(/g; #distinguish function names from field-tags
1091 $tagged =~ tr/#/v/;
1092 return ( $tagged, @field_tags );
1093 }
1094  
1095 #convert regexs for SQL sytle "matches" to Perl style =~
1096 sub convert_SQL_matches_to_perl {
1097 my $m = shift;
1098  
1099 $m =~ s/\./\\./g; #escape . (prob: what if . already escaped?)
1100 $m =~ s/\?/./g; #change ? to .
1101 $m =~ s/\*/.*?/g; #change * to .*?
1102  
1103 #another prob: what if ? . * are inside [ ] ?
1104 $m = '^\s*' . $m . '\s*$';
1105 return $m;
1106 }
1107  
1108 sub convert_perform_logic_to_perl {
1109 my $cond = shift;
1110 warn "logic :$cond:\n" if $::TRACE_DATA;
1111 my ( $condunstrung, @strs ) = pull_strings($cond);
1112  
1113 #Now that all "and"s etc. in strings and comments are gone, can convert.
1114 #Pad with spaces at the ends
1115 # $condunstrung = ' ' . $condunstrung . ' ';
1116  
1117 #Perl understands "and", "or", "not" as well as &&, ||, !, so may not need
1118 $condunstrung =~ s/([\s)"])and([\s("])/$1&& $2/gi;
1119 $condunstrung =~ s/([\s)"])or([\s("])/$1||$2/gi;
1120  
1121 $condunstrung =~ s/<>/!=/g;
1122  
1123 #want to go from "is null" to "eq ''", but don't want letters (such as "eq")
1124 #so go to a made up intermediate form, which is '$' in front of the operator
1125 $condunstrung =~ s/\sis\s+not\s+null(([\s)])|$)/ \$!= ''$2/gi;
1126 $condunstrung =~ s/\sis\s+null(([\s)])|$)/ \$== ''$2/gi;
1127 $condunstrung =~ s/((\W)|^)null(([\s)])|$)/$2''$4/gi;
1128  
1129 $condunstrung =~ s/([\s(])not([\s("])/$1 ! $2/gi;
1130 $condunstrung =~ s/([^=!><])=([^=])/$1==$2/g;
1131  
1132 #convert "matches" to Perl style =~
1133 #FIX: should we also handle ANSI "like"?
1134 my @ca = split /"/, $condunstrung, -1;
1135 my $i = 0;
1136 for ( $i = 0 ; $i < $#ca ; $i++ ) {
1137 if ( $ca[$i] =~ s/\smatches\s+$/ =~ / ) {
1138 $strs[$i] = '/' . convert_SQL_matches_to_perl( $strs[$i] ) . '/';
1139 }
1140 else {
1141 $strs[$i] = "'" . $strs[$i] . "'" unless is_number( $strs[$i] );
1142 }
1143 }
1144 $condunstrung = join '"', @ca;
1145  
1146 #"not matches" will have been changed to ! =~ at this point. Make it into !~
1147 $condunstrung =~ s/!\s*=~/!~/g;
1148  
1149 #now all remaining letters should be field-tags
1150 my @field_tags;
1151 ( $condunstrung, @field_tags ) = pull_field_tags($condunstrung);
1152  
1153 #go from intermediate form to Perl syntax
1154 $condunstrung =~ s/\$!=/ne/g;
1155 $condunstrung =~ s/\$==/eq/g;
1156  
1157 #for string comparisons, use eq,ne, etc. instead of ==, !=
1158 $condunstrung =~ s/==(\s*)"/eq$1"/g;
1159 $condunstrung =~ s/"(\s*)==/"$1eq/g;
1160 $condunstrung =~ s/!=(\s*)"/ne$1"/g;
1161 $condunstrung =~ s/"(\s*)!=/"$1ne/g;
1162 $condunstrung =~ s/>=(\s*)"/ge$1"/g;
1163 $condunstrung =~ s/"(\s*)>=/"$1ge/g;
1164 $condunstrung =~ s/<=(\s*)"/le$1"/g;
1165 $condunstrung =~ s/"(\s*)<=/"$1le/g;
1166  
1167 $condunstrung =~ s/>\s*"/gt "/g;
1168 $condunstrung =~ s/"\s*>/" gt/g;
1169 $condunstrung =~ s/<\s*"/lt "/g;
1170 $condunstrung =~ s/"\s*</" lt/g;
1171  
1172 return [ $condunstrung, [@strs], [@field_tags] ];
1173 }
1174  
1175 sub is_number {
1176 my $val = shift;
1177 return $val =~ /^(\+|-)?(\d+\.?\d*|\d*\.?\d+)((e|E)\d+)?$/;
1178 }
1179  
1180 sub output_string {
1181 my $db = shift;
1182 my $screens = shift;
1183 my $tables = shift;
1184  
1185 # my $attrs = shift;
1186 my $instrs = shift;
1187 my $ver = shift;
1188  
1189 my $form = {
1190 db => $db,
1191 screens => $screens,
1192 tables => $tables,
1193  
1194 # attrs => $attrs,
1195 instrs => $instrs,
1196 ver => $ver
1197 };
1198 my @strs = Data::Dumper->Dump( [$form], ['form'] );
1199 return join( $/, 'our $form;', @strs );
1200 }
1201  
1202 =head2 digest_file
1203  
1204 digest_file input_filename [output_filename]
1205  
1206 Reads the perform spec file, and writes a Perl Perform Spec file
1207 with the same basename but extension .pps unless an output filename
1208 is explicitly provided. Calls "digest" in this package to do the
1209 work.
1210  
1211 It\'s a little clumsy, but one can do a command-line "digestion" by:
1212 perl -MDBIx::Perform::DigestPer -e'digest_file "foo.per"' .
1213 Maybe a top-level Perl or shell script should be made for this purpose.
1214  
1215 =cut
1216  
1217 sub digest_file {
1218 my $infile = shift;
1219 my $outfile = shift;
1220  
1221 unless ($outfile) {
1222 $outfile = $infile;
1223 $outfile .= ".pps"
1224 unless $outfile =~ s/\..*$/.pps/;
1225 }
1226  
1227 open( IN, "< $infile" )
1228 or die "Couldn't open '$infile' for reading: $!";
1229 open( OUT, "> $outfile" )
1230 or die "Couldn't open '$outfile' for writing: $!";
1231  
1232 my ($str) = digest(*IN);
1233 print OUT $str;
1234 print OUT "\n1;\n"; # let it be require'd
1235 close(OUT);
1236 }
1237  
1238 sub convert_per_to_xml {
1239 warn "TRACE: entering convert_perl_to_xml\n" if $::TRACE;
1240 shift if ( $_[0] eq __PACKAGE__ );
1241  
1242 my $filename = shift;
1243  
1244 if ( !( $filename =~ /\.per$/ ) ) {
1245 die "Unknown file name extension on '$filename'";
1246 }
1247 open( PER_IN, "< $filename" )
1248 || die "Unable to open '$filename' for reading: $!";
1249 require "DBIx/Perform/DigestPer.pm";
1250  
1251 my @ret = digest( \*PER_IN );
1252  
1253 my @test = @{ $ret[0] };
1254  
1255 #die "File did not digest to a Perl Perform Spec"
1256 # unless @test =~ /\$form\s*=/;
1257  
1258 my ($outfile) = split( /\.per/, $filename );
1259 $outfile .= ".xml";
1260 dump_to_xml_file( \@ret, $outfile );
1261 }
1262  
1263 sub convert_per_to_yml {
1264 warn "TRACE: entering convert_perl_to_yml\n" if $::TRACE;
1265 shift if ( $_[0] eq __PACKAGE__ );
1266  
1267 my $filename = shift;
1268  
1269 $filename .= '.per' if !( $filename =~ /\.per$/i );
1270  
1271 open( PER_IN, "< $filename" )
1272 || die "Unable to open '$filename' for reading: $!";
1273 require "DBIx/Perform/DigestPer.pm";
1274  
1275 my @ret = digest( \*PER_IN );
1276  
1277 my @test = @{ $ret[0] };
1278  
1279 #die "File did not digest to a Perl Perform Spec"
1280 # unless @test =~ /\$form\s*=/;
1281  
1282 my ($outfile) = split( /\.per/, $filename );
1283 $outfile .= ".yml";
1284 dump_to_yml_file( \@ret, $outfile );
1285 }
1286  
1287 sub digest_xml_file {
1288 shift if ( $_[0] eq __PACKAGE__ );
1289  
1290 my $filename = shift;
1291 my $dump = new XML::Dumper;
1292  
1293 return $dump->xml2pl($filename);
1294  
1295 # open (FILE, "< $filename") or die "can't open $filename\n";
1296 # my $yamldata = join('', <FILE>);
1297 # close FILE;
1298 # return YAML::Load( $yamldata );
1299 }
1300  
1301 sub digest_yml_file {
1302 shift if ( $_[0] eq __PACKAGE__ );
1303  
1304 my $filename = shift;
1305  
1306 open( FILE, "< $filename" ) or die "can't open $filename\n";
1307 my $yamldata = join( '', <FILE> );
1308 close FILE;
1309 return YAML::Load($yamldata);
1310 }
1311  
1312 sub dump_to_xml_file {
1313 shift if ( $_[0] eq __PACKAGE__ );
1314  
1315 my @out_string = shift;
1316 my $filename = shift;
1317  
1318 my $dump = new XML::Dumper;
1319  
1320 return $dump->pl2xml( @out_string, $filename );
1321 }
1322  
1323 sub dump_to_yml_file {
1324 shift if ( $_[0] eq __PACKAGE__ );
1325  
1326 my @out_string = shift;
1327 my $filename = shift;
1328  
1329 # my $dump = new XML::Dumper;
1330  
1331 # return $dump->pl2xml( @out_string, $filename );
1332 open( FILE, "> $filename" ) or die "can't open $filename\n";
1333 print FILE YAML::Dump(@out_string);
1334 close FILE;
1335 }
1336  
1337 # Our little word muncher...
1338 package DBIx::Perform::DigestPer::Parser;
1339  
1340 sub new {
1341 my $class = shift;
1342 my $ioh = shift;
1343  
1344 my $self = bless {}, $class;
1345 $self->{'ioh'} = $ioh;
1346 $self->{'tail'} = '';
1347 return $self;
1348 }
1349  
1350 sub read_token {
1351 my $self = shift;
1352 my $accept_header_word = shift;
1353  
1354 my ( $ioh, $tail ) = @$self{ 'ioh', 'tail' };
1355  
1356 do {
1357 my ($word) = $tail =~ /(\w+|[^\w\s]+)/;
1358 if ($word) {
1359 return undef
1360 if $DBIx::Perform::DigestPer::HEADING_WORDS{ lc($word) }
1361 && lc($word) ne 'end'
1362 && !$accept_header_word;
1363 $self->{'tail'} = $'; #'
1364 return $word;
1365 }
1366 $tail = <$ioh>;
1367 chomp $tail;
1368 $self->{'tail'} = $tail;
1369 } while ( defined($tail) );
1370 return undef;
1371 }
1372  
1373 sub unread_token {
1374 my $self = shift;
1375 my $word = shift;
1376  
1377 $self->{'tail'} = $word . $self->{'tail'};
1378 }
1379  
1380 sub read_line {
1381 my $self = shift;
1382 my $accept_heading_word = shift;
1383  
1384 my $tail = $self->{'tail'};
1385 return undef
1386 if $tail =~ /^\s*(\w+)\s*$/
1387 && $DBIx::Perform::DigestPer::HEADING_WORDS{ lc($1) }
1388 && lc($1) ne 'end'
1389 && !$accept_heading_word;
1390 $self->{'tail'} = '';
1391 return $tail if ( $tail =~ /\S/ );
1392 my $ioh = $self->{'ioh'};
1393 my $line = <$ioh>;
1394 return undef unless defined($line);
1395 chomp $line;
1396 return ( ( $self->{'tail'} = $line ) && undef )
1397 if $line =~ /^\s*(\w+)\s*$/
1398 && $DBIx::Perform::DigestPer::HEADING_WORDS{ lc($1) }
1399 && lc($1) ne 'end'
1400 && !$accept_heading_word;
1401 return $line eq '' ? ' ' : $line;
1402 }
1403  
1404 1;
1405