blib/lib/Inline/BC.pm untested

filter: Statementstmt 0.0% 0 / 158 Branchbran 0.0% 0 / 44 Conditioncond 0.0% 0 / 20 MC/DCmcdc 0.0% 0 / 11 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 264 CC 23 SCAR 40.9
CC
23
Cov
0%
validate
182.0
add_list
20.0
info
20.0
CRAP 59.5
1 package Inline::BC;
2 use strict;
3 use Carp;
4 require Inline;
5 require DynaLoader;
6 require Exporter;
7 use vars qw(@ISA $VERSION @EXPORT_OK $RUN_ONCE);
8 use vars qw($RE_balanced_brackets $RE_balanced_parens);
9 use vars qw($use_math_lib);
10  
11 $use_math_lib = 0; # assume BC's math library is not required
12 $VERSION = '0.08';
13 @ISA = qw(Inline DynaLoader Exporter);
14  
15 use Cwd qw(abs_path);
16  
17 use Data::Dumper;
18  
19 my @export_ok = qw(bc_init bc_parse bc_run);
20  
21 #==============================================================================
22 # lots of this code has been shamelessly stolen from Inline::Ruby :-)
23 #==============================================================================
24  
25 sub dl_load_flags { 0x01 }
26 eval_support_code();
27  
28  
29 #==============================================================================
30 # Prep the BC interpreter
31 #==============================================================================
32 sub eval_support_code{
33 return if $RUN_ONCE;
34 Inline::BC->bootstrap($VERSION);
35 }
36  
37  
38  
39 #==============================================================================
40 # Register BC.pm as a valid Inline language
41 #==============================================================================
42 sub register {
43 return {
44 language => 'BC',
45 aliases => ['bc', 'Bc'],
46 type => 'interpreted',
47 suffix => 'bc',
48 };
49 }
50  
51 #==============================================================================
52 # Validate the BC config options
53 #==============================================================================
54 sub validate {
55 my $o = shift;
56  
57 $o->{ILSM} ||= {};
58 $o->{ILSM}{FILTERS} ||= [];
59 $o->{ILSM}{built} ||= 0;
60 $o->{ILSM}{loaded} ||= 0;
61
62 $o->{ILSM}{bindto} = [qw(functions)];
63  
64 while (@_) {
65 my ($key, $value) = (shift, shift);
66  
67 if ($key eq 'FILTERS') {
68 next if $value eq '1' or $value eq '0'; # ignore ENABLE, DISABLE
69 $value = [$value] unless ref($value) eq 'ARRAY';
70 my %filters;
71 for my $val (@$value) {
72 if (ref($val) eq 'CODE') {
73 $o->add_list($o->{ILSM}, $key, $val, []);
74 }
75 else {
76 eval { require Inline::Filters };
77 croak "'FILTERS' option requires Inline::Filters to be installed."
78 if $@;
79 %filters = Inline::Filters::get_filters($o->{API}{language})
80 unless keys %filters;
81 if (defined $filters{$val}) {
82 my $filter = Inline::Filters->new($val,
83 $filters{$val});
84 $o->add_list($o->{ILSM},
85 $key,
86 [ $filter ],
87 [ ]);
88 }
89 else {
90 croak "Invalid filter $val specified.";
91 }
92 }
93 }
94 }
95 elsif ($key eq 'MATH_LIB') {
96 croak "Invalid value specified for config option 'MATH_LIB'"
97 if ($value ne '1' and $value ne '0');
98  
99 if ($RUN_ONCE) {
100 if ($value ne $use_math_lib) {
101 warn("The BC interpreter was initialised with option ",
102 "MATH_LIB => $use_math_lib.\n",
103 "Any subsequent use of option 'MATH_LIB' will ",
104 "have no effect.\n");
105 }
106 }
107 else {
108 $use_math_lib = $value;
109 }
110 }
111 else {
112 croak "$key is not a valid config option for BC";
113 }
114 }
115  
116 # Ensure the BC interpreter is initialised only once!
117 unless ($RUN_ONCE) {
118 bc_init( $use_math_lib );
119 $RUN_ONCE = 1;
120 }
121 }
122  
123  
124 sub usage_validate {
125 return "Invalid value for config option $_[0]";
126 }
127  
128  
129 sub add_list {
130 my $o = shift;
131 my ($ref, $key, $value, $default) = @_;
132 $value = [$value] unless ref $value;
133 croak usage_validate($key) unless ref($value) eq 'ARRAY';
134 for (@$value) {
135 if (defined $_) {
136 push @{$ref->{$key}}, $_;
137 }
138 else {
139 $ref->{$key} = $default;
140 }
141 }
142 }
143  
144  
145 #==========================================================================
146 # Print a short information section if PRINT_INFO is enabled.
147 #==========================================================================
148 sub info {
149 my $o = shift;
150 my $info = "";
151  
152 $o->build unless $o->{ILSM}{built};
153  
154 my @functions = @{$o->{ILSM}{namespace}{functions}||[]};
155 $info .= "The following BC functions have been bound to Perl:\n"
156 if @functions;
157 for my $function (sort @functions) {
158 $info .= "\tdefine $function()\n";
159 }
160  
161 $info .= "\nThe BC math library has been loaded.\n" if ($use_math_lib);
162  
163 return $info;
164 }
165  
166  
167 #==========================================================================
168 # Run the code, study the main namespace, and cache the results.
169 #==========================================================================
170 sub build {
171 my $o = shift;
172 return if $o->{ILSM}{built};
173  
174 # Filter the code
175 $o->{ILSM}{code} = $o->filter(@{$o->{ILSM}{FILTERS}});
176  
177 my $code = $o->{ILSM}{code};
178  
179 # get the function signatures
180 # These regular expressions were derived from Regexp::Common v0.01.
181 my $RE_comment_C = q{(?:(?:\/\*)(?:(?:(?!\*\/)[\s\S])*)(?:\*\/))};
182 my $RE_comment_Cpp = q{(?:\/\*(?:(?!\*\/)[\s\S])*\*\/|\/\/[^\n]*\n)};
183 my $RE_quoted = (q{(?:(?:\")(?:[^\\\"]*(?:\\.[^\\\"]*)*)(?:\")}
184 .q{|(?:\')(?:[^\\\']*(?:\\.[^\\\']*)*)(?:\'))});
185 $RE_balanced_brackets =
186 qr'(?:[{]((?:(?>[^{}]+)|(??{$RE_balanced_brackets}))*)[}])';
187 $RE_balanced_parens =
188 qr'(?:[(]((?:(?>[^()]+)|(??{$RE_balanced_parens}))*)[)])';
189  
190 # First, we crush out anything potentially confusing.
191 # The order of these _does_ matter.
192 $code =~ s/$RE_comment_C/ /go;
193 $code =~ s/$RE_comment_Cpp/ /go;
194 $code =~ s/^\#.*(\\\n.*)*//mgo;
195 $code =~ s/^[\n\s]+//s;
196 $code =~ s/[\s\n]+$//s;
197 $code =~ s/\n(\s*)?\n/\n/sg;
198 $code =~ s/$RE_balanced_brackets/{ }/go;
199 $code =~ s/\n//sg;
200 my %functions = ();
201 while ( $code =~ /define\s+(\w+)\s*?\((.*?)\)\s*?\{.*?\}/gs ){
202 $functions{$1} = [ split(/,\s*?/, $2) ];
203 }
204 my $bytecode = bc_parse($o->{ILSM}{code});
205  
206 my $binding = "";
207 foreach my $func ( keys %functions ){
208 my $bcfunc = $func." ( ";
209 $bcfunc .= join(", ", map { "\$".$_ }(@{$functions{$func}}));
210 $bcfunc .= " )";
211 $binding .= <<END;
212 sub $func {
213 # my \$self = shift;
214 END
215 $binding .= join("", map { " my \$".$_." = shift;\n" }(@{$functions{$func}}));
216 $binding .= <<END;
217 return &Inline::BC::bc_run( &Inline::BC::bc_parse("$bcfunc\\n") );
218 }
219 END
220 }
221  
222 # Cache the results
223 require Inline::denter;
224 my $namespace = Inline::denter->new->indent(
225 *functions => \%functions,
226 *filtered => $o->{ILSM}{code},
227 *bytecode => $bytecode,
228 *binding => "package ".$o->{API}{pkg}.";\n".$binding,
229 );
230  
231 $o->mkpath("$o->{API}{install_lib}/auto/$o->{API}{modpname}");
232  
233 open BCDAT, "> $o->{API}{location}" or
234 croak "Inline::BC couldn't write parse information!";
235 print BCDAT $namespace;
236 close BCDAT;
237  
238 $o->{ILSM}{namespace} = \%functions;
239 $o->{ILSM}{built}++;
240  
241 }
242  
243  
244 #==============================================================================
245 # Load the code, run it, and bind everything to Perl
246 #==============================================================================
247 sub load {
248 my $o = shift;
249 return if $o->{ILSM}{loaded};
250  
251 # Load the code
252 open BCDAT, $o->{API}{location} or
253 croak "Couldn't open parse info!";
254 my $bcdat = join '', <BCDAT>;
255 close BCDAT;
256  
257 require Inline::denter;
258 my %bcdat = Inline::denter->new->undent($bcdat);
259 $o->{ILSM}{namespace} = $bcdat{functions};
260 $o->{ILSM}{code} = $bcdat{filtered};
261 $o->{ILSM}{binding} = $bcdat{binding};
262 $o->{ILSM}{loaded}++;
263  
264 # Run it
265 bc_run(bc_parse($o->{ILSM}{code}));
266  
267 eval $o->{ILSM}{binding};
268 croak $@ if $@;
269 }
270  
271 #==============================================================================
272  
273  
274  
275 =head1 NAME
276  
277 Inline::BC - Inline ILSM for bc the arbitrary precision math Language
278  
279 =head1 SYNOPSIS
280  
281 use Inline BC;
282 print x(int(rand(time())));
283 __DATA__
284 __BC__
285 define x(a){
286 scale = 20;
287 return (a*3.456789);
288 }
289
290  
291 =head1 DESCRIPTION
292  
293 Inline::BC is an ILSM (Inline Support Language Module ) for Gnu bc, the arbitrary
294 precision numeric processing language. Inline::BC - like other ILSMs - allows you
295 to compile (well - render to byte code ), and run Gnu bc code within your Perl
296 program.
297  
298 From the Gnu BC README:
299  
300 bc is an arbitrary precision numeric processing language. Syntax is
301 similar to C, but differs in many substantial areas. It supports
302 interactive execution of statements. bc is a utility included in the
303 POSIX P1003.2/D11 draft standard.
304  
305 This version was written to be a POSIX compliant bc processor with
306 several extensions to the draft standard. Option flags are available
307 to cause warning or rejection of the extensions to the POSIX standard.
308 For those who want only POSIX bc with no extensions, a grammar is
309 provided for exactly the language described in the POSIX document.
310 The grammar (sbc.y) comes from the POSIX document. The Makefile
311 contains rules to make sbc. (for Standard BC)
312  
313 "end of quote"
314  
315 Further documentation about Gnu bc can be found at:
316 http://www.gnu.org/software/bc/bc.html
317 http://www.gnu.org/manual/bc/html_mono/bc.html
318  
319  
320 one thing to note is that you should be careful with setting the global
321 bc parameters like ibase, obase, scale etc. You should not set these in
322 the global code - instead, set them in each function, to avoid the chaos
323 that would follow.
324  
325 Looking at the test suite - there are examples of several different ways of
326 invoking Inline::BC:
327  
328 (1) code in the DATA statement
329 use Inline BC;
330 print x(4) == 5.3 ? "ok 2\n" : "not ok 2\n";
331 __DATA__
332 __BC__
333 define x (a) {
334 scale = 20
335 return (a * 1.5);
336 }
337  
338 (2) inline code with here document
339 use Inline BC => <<'END_BC';
340 define z (a, b) {
341 scale = 6
342 t = a * .357;
343 t = b / t;
344 return ( t );
345 }
346 END_BC
347 print z(4, 7) > 4 ? "ok 3\n" : "not ok 3\n";
348  
349 (3) code in an external file
350 use Inline BC => './tools/test.dat';
351 print aa() =~ /[0\n]/s ? "ok 4\n" : "not ok 4\n";
352  
353  
354 =head1 CONFIG OPTIONS
355  
356 Inline::BC provides the following config options.
357  
358 B<MATH_LIB =E<gt> 0|1>
359  
360 When Inline::BC is invoked with the config option 'MATH_LIB => 1',
361 then the GNU bc processor is initialised with its builtin math
362 library.
363 The math library offers the following builtin functions:
364  
365 =over 4
366  
367 =item s(x)
368  
369 The sine of x, x is in radians.
370  
371 =item c(x)
372  
373 The cosine of x, x is in radians.
374  
375 =item a(x)
376  
377 The arctangent of x, arctangent returns radians.
378  
379 =item l(x)
380  
381 The natural logarithm of x.
382  
383 =item e(x)
384  
385 The exponential function, raising e to the value x.
386  
387 =item j(n,x)
388  
389 The Bessel function of integer order n of x.
390  
391 =back
392  
393 Example: Calculating the hyperbolic sine of a value.
394  
395 use Inline BC => "DATA", MATH_LIB => 1;
396  
397 my $r = bc_sinh(4.712);
398  
399 __END__