XSBuilder/ParseSource.pm untested

filter: Statementstmt 0.0% 0 / 218 Branchbran 0.0% 0 / 48 Conditioncond 0.0% 0 / 53 MC/DCmcdc 0.0% 0 / 30 Subroutinesub 0.0% 0 / 42 Podpod 0.0% 0 / 31 totaltotal 0.0% 0 / 422 CC 25 SCAR 25.1
CC
25
Cov
0%
find_includes
42.0
get_constants
30.0
write_pm
30.0
CRAP 12.4
1 package ExtUtils::XSBuilder::ParseSource;
2
3 use strict;
4 use vars qw{$VERSION $verbose} ;
5
6 use Config ();
7 use Data::Dumper ;
8 use Carp;
9 use Parse::RecDescent;
10 use File::Path qw(mkpath);
11
12 use ExtUtils::XSBuilder::C::grammar ;
13
14 $VERSION = '0.03';
15
16 $verbose = 1 ;
17
18
19 =pod
20
21 =head1 NAME
22
23 ExtUtils::XSBuilder::ParseSource - parse C source files
24
25 =head2 DESCRIPTION
26
27 For more information, see L<ExtUtils::XSBuilder>
28
29 =cut
30
31 # ============================================================================
32
33 sub new {
34 my $class = shift;
35
36 my $self = bless {
37 @_,
38 }, $class;
39
40
41 $self;
42 }
43
44 # ============================================================================
45
46 =pod
47
48 =head2 extent_parser (o)
49
50 Allows the user to call the Extent or Replace method of the parser to add
51 new syntax rules. This is mainly useful to include expansions for
52 preprocessor macros.
53
54 =cut
55
56 sub extent_parser {
57 }
58
59 # ============================================================================
60 =pod
61
62 =head2 preprocess (o)
63
64 Allows the user to preprocess the source before it is given to the parser.
65 You may modify the source, which is given as first argument in place.
66
67 =cut
68
69 sub preprocess {
70 }
71
72
73 # ============================================================================
74
75 sub parse {
76 my $self = shift;
77
78 $self -> find_includes ;
79 my $c = $self -> {c} = {} ;
80
81 print "Initialize parser\n" if ($verbose) ;
82 my $grammar = ExtUtils::XSBuilder::C::grammar::grammar() or croak "Can't find C grammar\n";
83
84 $::RD_HINT++;
85
86 my $parser = $self -> {parser} = Parse::RecDescent->new($grammar);
87
88 $parser -> {data} = $c ;
89 $parser -> {srcobj} = $self ;
90
91 $self -> extent_parser ($parser) ;
92
93 foreach my $inc (@{$self->{includes}})
94 {
95 print "scan $inc ...\n" if ($verbose) ;
96 $self->scan ($inc) ;
97 }
98
99 }
100
101
102 # ============================================================================
103
104 sub scan {
105
106 my ($self, $filename) = @_ ;
107
108 my $txt ;
109 {
110 local $/ = undef ;
111 open FH, $filename or die "Cannot open $filename ($!)" ;
112 $txt = <FH> ;
113 close FH ;
114 }
115 local $SIG{__DIE__} = \&Carp::confess;
116
117 $self -> {parser} -> {srcfilename} = $filename ;
118
119 $self -> preprocess ($txt) ;
120
121 return $self -> {parser}->code($txt) or die "Cannot parse $filename" ;
122
123 }
124
125
126 # ============================================================================
127
128 sub DESTROY {
129 my $self = shift;
130 unlink $self->{scan_filename}
131 }
132
133
134 # ============================================================================
135 =pod
136
137 =head2 include_dirs (o)
138
139 Returns a reference to the list of directories that should be searched for
140 include files which contain the functions, structures, etc. to be extracted.
141
142 Default: C<'.'>
143
144 =cut
145
146 sub include_dirs {
147 my $self = shift;
148 ['.'],
149 }
150
151
152 # ============================================================================
153 =pod
154
155 =head2 include_paths (o)
156
157 Returns a reference to a list of directories that are given as include
158 directories to the C compiler. This is mainly used to strip these directories
159 from filenames to convert absolute paths to relative paths.
160
161 Default: empty list (C<[]>)
162
163 =cut
164
165 sub include_paths {
166 my $self = shift;
167 [],
168 }
169
170
171 # ============================================================================
172 =pod
173
174 =head2 unwanted_includes (o)
175
176 Returns a reference to a list of include files that should not be processed.
177
178 Default: empty list (C<[]>)
179
180 =cut
181
182 sub unwanted_includes { [] }
183
184
185
186 # ============================================================================
187 =pod
188
189 =head2 sort_includes (o, include_list)
190
191 Passed an array ref of include files, it allows the user to define the sort
192 order, so includes are processed correctly.
193
194 Default: return the passed array reference.
195
196 =cut
197
198 sub sort_includes {
199
200 return $_[1] ;
201 }
202
203
204
205 # ============================================================================
206 =pod
207
208 =head2 find_includes (o)
209
210 Returns a list of include files to be processed.
211
212 Default: search directories given by C<include_dirs> for all files and build a
213 list of include files. All files starting with a word matched by
214 C<unwanted_includes> are not included in the list.
215
216 =cut
217
218 sub find_includes {
219 my $self = shift;
220
221 return $self->{includes} if $self->{includes};
222
223 require File::Find;
224
225 my(@dirs) = $self->include_dirs;
226
227 unless (-d $dirs[0]) {
228 die "could not find include directory";
229 }
230
231 print "Will search @dirs for include files...\n" if ($verbose) ;
232
233 my @includes;
234 my $unwanted = join '|', @{$self -> unwanted_includes} ;
235
236 for my $dir (@dirs) {
237 File::Find::finddepth({
238 wanted => sub {
239 return unless /\.h$/;
240 return if ($unwanted && (/^($unwanted)/o));
241 my $dir = $File::Find::dir;
242 push @includes, "$dir/$_";
243 },
244 follow => $^O ne 'MSWin32',
245 }, $dir);
246 }
247
248 return $self->{includes} = $self -> sort_includes (\@includes) ;
249 }
250
251
252
253 # ============================================================================
254 =pod
255
256 =head2 handle_define (o)
257
258 Passed a hash ref with the definition of a define, may modify it.
259 Return false to discard it, return true to keep it.
260
261 Default: C<1>
262
263 =cut
264
265 sub handle_define { 1 } ;
266
267
268 # ============================================================================
269 =pod
270
271 =head2 handle_enum (o)
272
273 Passed a hash ref with the definition of a enum value, may modify it.
274 Return false to discard it, return true to keep it.
275
276 Default: C<1>
277
278 =cut
279
280 sub handle_enum { 1 } ;
281
282
283 # ============================================================================
284 =pod
285
286 =head2 handle_struct (o)
287
288 Passed a hash ref with the definition of a struct, may modify it.
289 Return false to discard it, return true to keep it.
290
291 Default: C<1>
292
293 =cut
294
295 sub handle_struct { 1 } ;
296
297
298
299 # ============================================================================
300 =pod
301
302 =head2 handle_function (o)
303
304 Passed a hash ref with the definition of a function, may modify it.
305 Return false to discard it, return true to keep it.
306
307 Default: C<1>
308
309 =cut
310
311 sub handle_function { 1 } ;
312
313
314
315 # ============================================================================
316 =pod
317
318 =head2 handle_callback (o)
319
320 Passed a hash ref with the definition of a callback, may modify it.
321 Return false to discard it, return true to keep it.
322
323 Default: C<1>
324
325 =cut
326
327 sub handle_callback { 1 } ;
328
329
330
331
332
333
334
335 # ============================================================================
336
337
338 sub get_constants {
339 my($self) = @_;
340
341 my $includes = $self->find_includes;
342 my(%constants, %seen);
343 my $defines_wanted_re = $self -> defines_wanted_re ;
344 my $defines_wanted = $self -> defines_wanted ;
345 my $defines_unwanted = $self -> defines_unwanted ;
346 my $enums_wanted = $self -> enums_wanted ;
347 my $enums_unwanted = $self -> enums_unwanted ;
348
349 for my $file (@$includes) {
350 open my $fh, $file or die "open $file: $!";
351 while (<$fh>) {
352 if (s/^\#define\s+(\w+)\s+.*/$1/) {
353 chomp;
354 next if /_H$/;
355 next if $seen{$_}++;
356 $self->handle_constant(\%constants, $defines_wanted_re, $defines_wanted, $defines_unwanted);
357 }
358 elsif (m/enum[^\{]+\{/) {
359 $self->handle_enum($fh, \%constants, $enums_wanted, $enums_unwanted);
360 }
361 }
362 close $fh;
363 }
364
365 return \%constants;
366 }
367
368 # ============================================================================
369
370 sub get_constants {
371 my $self = shift;
372
373 my $key = 'parsed_constants';
374 return $self->{$key} if $self->{$key};
375
376 my $c = $self->{$key} = $self->{c}{constants} ||= [] ;
377
378
379 # sort the constants by the 'name' attribute to ensure a
380 # consistent output on different systems.
381 $self->{$key} = [sort { $a->{name} cmp $b->{name} } @{$self->{$key}}];
382 }
383
384
385
386 # ============================================================================
387
388 sub get_functions {
389 my $self = shift;
390
391 my $key = 'parsed_fdecls';
392 return $self->{$key} if $self->{$key};
393
394 my $c = $self->{c}{functions} ||= [] ;
395
396
397 # sort the functions by the 'name' attribute to ensure a
398 # consistent output on different systems.
399 $self->{$key} = [sort { $a->{name} cmp $b->{name} } @$c];
400 }
401
402 # ============================================================================
403
404 sub get_structs {
405 my $self = shift;
406
407 my $key = 'typedef_structs';
408 return $self->{$key} if $self->{$key};
409
410 my $c = $self->{c}{structures} ||= [] ;
411
412 # sort the structs by the 'type' attribute to ensure a consistent
413 # output on different systems.
414
415 $self->{$key} = [sort { $a->{type} cmp $b->{type} } @$c];
416 }
417
418 # ============================================================================
419
420 sub get_callbacks {
421 my $self = shift;
422
423 my $key = 'typedef_callbacks';
424 return $self->{$key} if $self->{$key};
425
426 my $c = $self->{c}{callbacks} ||= [] ;
427
428 # sort the callbacks by the 'type' attribute to ensure a consistent
429 # output on different systems.
430 $self->{$key} = [sort { $a->{type} cmp $b->{type} } @$c];
431 }
432
433 # ============================================================================
434 =pod
435
436 =head2 package (o)
437
438 Return package name for tables
439
440 Default: C<'MY'>
441
442 =cut
443
444 sub package { 'MY' }
445
446 # ============================================================================
447 =pod
448
449 =head2 targetdir (o)
450
451 Return name of target directory where to write tables
452
453 Default: C<'./xsbuilder/tables'>
454
455 =cut
456
457 sub targetdir { './xsbuilder/tables' }
458
459
460
461 # ============================================================================
462
463 sub write_functions_pm {
464 my $self = shift;
465 my $file = shift || 'FunctionTable.pm';
466 my $name = shift || $self -> package . '::FunctionTable';
467
468 $self->write_pm($file, $name, $self->get_functions);
469 }
470
471 # ============================================================================
472
473 sub write_structs_pm {
474 my $self = shift;
475 my $file = shift || 'StructureTable.pm';
476 my $name = shift || $self -> package . '::StructureTable';
477
478 $self->write_pm($file, $name, $self->get_structs);
479 }
480
481 # ============================================================================
482
483 sub write_constants_pm {
484 my $self = shift;
485 my $file = shift || 'ConstantsTable.pm';
486 my $name = shift || $self -> package . '::ConstantsTable';
487
488 $self->write_pm($file, $name, $self->get_constants);
489 }
490
491 # ============================================================================
492
493 sub write_callbacks_pm {
494 my $self = shift;
495 my $file = shift || 'CallbackTable.pm';
496 my $name = shift || $self -> package . '::CallbackTable';
497
498 $self->write_pm($file, $name, $self->get_callbacks);
499 }
500
501 # ============================================================================
502
503 sub pm_path {
504 my($self, $file, $name, $create) = @_;
505
506 my @parts = split '::', ($name || $self -> package . '::X') ;
507 my($subdir) = join ('/', @parts[0..$#parts-1]) ;
508
509 my $tdir = $self -> targetdir ;
510 if (!-d "$tdir/$subdir") {
511 if ($create) {
512 mkpath ("$tdir/$subdir", 0, 0755) or die "Cannot create directory $tdir/$subdir ($!)" ;
513 }
514 else {
515 die "Missing directory $tdir/$subdir" ;
516 }
517 }
518
519 return "$tdir/$subdir/$file";
520 }
521
522 # ============================================================================
523
524 sub write_pm {
525 my($self, $file, $name, $data) = @_;
526
527 require Data::Dumper;
528 local $Data::Dumper::Indent = 1;
529
530 $data ||= [] ;
531
532 $file = $self -> pm_path ($file, $name, 1) ;
533
534 # sort the hashes (including nested ones) for a consistent dump
535 canonsort(\$data);
536
537 my $dump = Data::Dumper->new([$data],
538 [$name])->Dump;
539
540 my $package = ref($self) || $self;
541 my $version = $self->VERSION;
542 my $date = scalar localtime;
543
544 my $new_content = << "EOF";
545 package $name;
546
547 # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
548 # ! WARNING: generated by $package/$version
549 # ! $date
550 # ! do NOT edit, any changes will be lost !
551 # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
552
553 $dump
554
555 1;
556 EOF
557
558 my $old_content = '';
559 if (-e $file) {
560 open PM, "<$file" or die "open $file: $!";
561 local $/ = undef; # slurp the file
562 $old_content = <PM>;
563 close PM;
564 }
565
566 my $overwrite = 1;
567 if ($old_content) {
568 # strip the date line, which will never be the same before
569 # comparing
570 my $table_header = qr{^\#\s!.*};
571 (my $old = $old_content) =~ s/$table_header//mg;
572 (my $new = $new_content) =~ s/$table_header//mg;
573 $overwrite = 0 if $old eq $new;
574 }
575
576 if ($overwrite) {
577 open PM, ">$file" or die "open $file: $!";
578 print PM $new_content;
579 close PM;
580 }
581
582 }
583
584 # ============================================================================
585 #
586 # canonsort(\$data);
587 # sort nested hashes in the data structure.
588 # the data structure itself gets modified
589 #
590
591 sub canonsort {
592 my $ref = shift;
593 my $type = ref $$ref;
594
595 return unless $type;
596
597 require Tie::IxHash;
598
599 my $data = $$ref;
600
601 if ($type eq 'ARRAY') {
602 for my $d (@$data) {
603 canonsort(\$d);
604 }
605 }
606 elsif ($type eq 'HASH') {
607 for my $d (keys %$data) {
608 canonsort(\$data->{$d});
609 }
610
611 tie my %ixhash, 'Tie::IxHash';
612
613 # reverse sort so we get the order of:
614 # return_type, name, args { type, name } for functions
615 # type, elts { type, name } for structures
616
617 for (sort { $b cmp $a } keys %$data) {
618 $ixhash{$_} = $data->{$_};
619 }
620
621 $$ref = \%ixhash;
622 }
623 }
624
625
626 # ============================================================================
627 =pod
628
629 =head2 run
630
631 Call this class method to parse your source. Before you can do so you must
632 provide a class that overrides the defaults in
633 L<ExtUtils::XSBuilder::ParseSource>. After that you scan the source files with
634
635 MyClass -> run ;
636
637 =cut
638
639 sub run
640
641 {
642 my ($class) = @_ ;
643
644 my $p = $class -> new() ;
645
646 $p -> parse ;
647
648 $p -> write_constants_pm ;
649
650 $p -> write_functions_pm ;
651
652 $p -> write_structs_pm ;
653
654 $p -> write_callbacks_pm ;
655 }
656
657
658
659
660 1;
661 __END__