Once again syncing after too long an absence
[p5sagit/p5-mst-13.2.git] / ext / Filter / Util / Call / Call.pm
1 package Filter::Util::Call ;
2
3 require 5.002 ;
4 require DynaLoader;
5 require Exporter;
6 use Carp ;
7 use strict;
8 use vars qw($VERSION @ISA @EXPORT) ;
9
10 @ISA = qw(Exporter DynaLoader);
11 @EXPORT = qw( filter_add filter_del filter_read filter_read_exact) ;
12 $VERSION = "1.04" ;
13
14 sub filter_read_exact($)
15 {
16     my ($size)   = @_ ;
17     my ($left)   = $size ;
18     my ($status) ;
19
20     croak ("filter_read_exact: size parameter must be > 0")
21         unless $size > 0 ;
22
23     # try to read a block which is exactly $size bytes long
24     while ($left and ($status = filter_read($left)) > 0) {
25         $left = $size - length $_ ;
26     }
27
28     # EOF with pending data is a special case
29     return 1 if $status == 0 and length $_ ;
30
31     return $status ;
32 }
33
34 sub filter_add($)
35 {
36     my($obj) = @_ ;
37
38     # Did we get a code reference?
39     my $coderef = (ref $obj eq 'CODE') ;
40
41     # If the parameter isn't already a reference, make it one.
42     $obj = \$obj unless ref $obj ;
43
44     $obj = bless ($obj, (caller)[0]) unless $coderef ;
45
46     # finish off the installation of the filter in C.
47     Filter::Util::Call::real_import($obj, (caller)[0], $coderef) ;
48 }
49
50 bootstrap Filter::Util::Call ;
51
52 1;
53 __END__
54
55 =head1 NAME
56
57 Filter::Util::Call - Perl Source Filter Utility Module
58
59 =head1 SYNOPSIS
60  
61     use Filter::Util::Call ;
62
63 =head1 DESCRIPTION
64
65 This module provides you with the framework to write I<Source Filters>
66 in Perl.
67
68 A I<Perl Source Filter> is implemented as a Perl module. The structure
69 of the module can take one of two broadly similar formats. To
70 distinguish between them, the first will be referred to as I<method
71 filter> and the second as I<closure filter>.
72
73 Here is a skeleton for the I<method filter>:
74
75     package MyFilter ;
76     
77     use Filter::Util::Call ;
78
79     sub import
80     {
81         my($type, @arguments) = @_ ;
82         filter_add([]) ;
83     }
84     
85     sub filter
86     {
87         my($self) = @_ ;
88         my($status) ;
89     
90         $status = filter_read() ;
91         $status ;
92     }
93     
94     1 ;
95
96 and this is the equivalent skeleton for the I<closure filter>:
97
98     package MyFilter ;
99     
100     use Filter::Util::Call ;
101
102     sub import
103     {
104         my($type, @arguments) = @_ ;
105     
106         filter_add(
107             sub 
108             {
109                 my($status) ;
110                 $status = filter_read() ;
111                 $status ;
112             } )
113     }
114     
115     1 ;
116
117 To make use of either of the two filter modules above, place the line
118 below in a Perl source file.
119
120     use MyFilter; 
121
122 In fact, the skeleton modules shown above are fully functional I<Source
123 Filters>, albeit fairly useless ones. All they does is filter the
124 source stream without modifying it at all.
125
126 As you can see both modules have a broadly similar structure. They both
127 make use of the C<Filter::Util::Call> module and both have an C<import>
128 method. The difference between them is that the I<method filter>
129 requires a I<filter> method, whereas the I<closure filter> gets the
130 equivalent of a I<filter> method with the anonymous sub passed to
131 I<filter_add>.
132
133 To make proper use of the I<closure filter> shown above you need to
134 have a good understanding of the concept of a I<closure>. See
135 L<perlref> for more details on the mechanics of I<closures>.
136
137 =head2 B<use Filter::Util::Call>
138
139 The following functions are exported by C<Filter::Util::Call>:
140
141     filter_add()
142     filter_read()
143     filter_read_exact()
144     filter_del()
145
146 =head2 B<import()>
147
148 The C<import> method is used to create an instance of the filter. It is
149 called indirectly by Perl when it encounters the C<use MyFilter> line
150 in a source file (See L<perlfunc/import> for more details on
151 C<import>).
152
153 It will always have at least one parameter automatically passed by Perl
154 - this corresponds to the name of the package. In the example above it
155 will be C<"MyFilter">.
156
157 Apart from the first parameter, import can accept an optional list of
158 parameters. These can be used to pass parameters to the filter. For
159 example:
160
161     use MyFilter qw(a b c) ;
162
163 will result in the C<@_> array having the following values:
164
165     @_ [0] => "MyFilter"
166     @_ [1] => "a"
167     @_ [2] => "b"
168     @_ [3] => "c"
169
170 Before terminating, the C<import> function must explicitly install the
171 filter by calling C<filter_add>.
172
173 B<filter_add()>
174
175 The function, C<filter_add>, actually installs the filter. It takes one
176 parameter which should be a reference. The kind of reference used will
177 dictate which of the two filter types will be used.
178
179 If a CODE reference is used then a I<closure filter> will be assumed.
180
181 If a CODE reference is not used, a I<method filter> will be assumed.
182 In a I<method filter>, the reference can be used to store context
183 information. The reference will be I<blessed> into the package by
184 C<filter_add>.
185
186 See the filters at the end of this documents for examples of using
187 context information using both I<method filters> and I<closure
188 filters>.
189
190 =head2 B<filter() and anonymous sub>
191
192 Both the C<filter> method used with a I<method filter> and the
193 anonymous sub used with a I<closure filter> is where the main
194 processing for the filter is done.
195
196 The big difference between the two types of filter is that the I<method
197 filter> uses the object passed to the method to store any context data,
198 whereas the I<closure filter> uses the lexical variables that are
199 maintained by the closure.
200
201 Note that the single parameter passed to the I<method filter>,
202 C<$self>, is the same reference that was passed to C<filter_add>
203 blessed into the filter's package. See the example filters later on for
204 details of using C<$self>.
205
206 Here is a list of the common features of the anonymous sub and the
207 C<filter()> method.
208
209 =over 5
210
211 =item B<$_>
212
213 Although C<$_> doesn't actually appear explicitly in the sample filters
214 above, it is implicitly used in a number of places.
215
216 Firstly, when either C<filter> or the anonymous sub are called, a local
217 copy of C<$_> will automatically be created. It will always contain the
218 empty string at this point.
219
220 Next, both C<filter_read> and C<filter_read_exact> will append any
221 source data that is read to the end of C<$_>.
222
223 Finally, when C<filter> or the anonymous sub are finished processing,
224 they are expected to return the filtered source using C<$_>.
225
226 This implicit use of C<$_> greatly simplifies the filter.
227
228 =item B<$status>
229
230 The status value that is returned by the user's C<filter> method or
231 anonymous sub and the C<filter_read> and C<read_exact> functions take
232 the same set of values, namely:
233
234     < 0  Error
235     = 0  EOF
236     > 0  OK
237
238 =item B<filter_read> and B<filter_read_exact>
239
240 These functions are used by the filter to obtain either a line or block
241 from the next filter in the chain or the actual source file if there
242 aren't any other filters.
243
244 The function C<filter_read> takes two forms:
245
246     $status = filter_read() ;
247     $status = filter_read($size) ;
248
249 The first form is used to request a I<line>, the second requests a
250 I<block>.
251
252 In line mode, C<filter_read> will append the next source line to the
253 end of the C<$_> scalar.
254
255 In block mode, C<filter_read> will append a block of data which is <=
256 C<$size> to the end of the C<$_> scalar. It is important to emphasise
257 the that C<filter_read> will not necessarily read a block which is
258 I<precisely> C<$size> bytes.
259
260 If you need to be able to read a block which has an exact size, you can
261 use the function C<filter_read_exact>. It works identically to
262 C<filter_read> in block mode, except it will try to read a block which
263 is exactly C<$size> bytes in length. The only circumstances when it
264 will not return a block which is C<$size> bytes long is on EOF or
265 error.
266
267 It is I<very> important to check the value of C<$status> after I<every>
268 call to C<filter_read> or C<filter_read_exact>.
269
270 =item B<filter_del>
271
272 The function, C<filter_del>, is used to disable the current filter. It
273 does not affect the running of the filter. All it does is tell Perl not
274 to call filter any more.
275
276 See L<Example 4: Using filter_del> for details.
277
278 =back
279
280 =head1 EXAMPLES
281
282 Here are a few examples which illustrate the key concepts - as such
283 most of them are of little practical use.
284
285 The C<examples> sub-directory has copies of all these filters
286 implemented both as I<method filters> and as I<closure filters>.
287
288 =head2 Example 1: A simple filter.
289
290 Below is a I<method filter> which is hard-wired to replace all
291 occurrences of the string C<"Joe"> to C<"Jim">. Not particularly
292 Useful, but it is the first example and I wanted to keep it simple.
293
294     package Joe2Jim ;
295     
296     use Filter::Util::Call ;
297
298     sub import
299     {
300         my($type) = @_ ;
301     
302         filter_add(bless []) ;
303     }
304     
305     sub filter
306     {
307         my($self) = @_ ;
308         my($status) ;
309     
310         s/Joe/Jim/g
311             if ($status = filter_read()) > 0 ;
312         $status ;
313     }
314     
315     1 ;
316
317 Here is an example of using the filter:
318
319     use Joe2Jim ;
320     print "Where is Joe?\n" ;
321
322 And this is what the script above will print:
323
324     Where is Jim?
325
326 =head2 Example 2: Using the context
327
328 The previous example was not particularly useful. To make it more
329 general purpose we will make use of the context data and allow any
330 arbitrary I<from> and I<to> strings to be used. This time we will use a
331 I<closure filter>. To reflect its enhanced role, the filter is called
332 C<Subst>.
333
334     package Subst ;
335  
336     use Filter::Util::Call ;
337     use Carp ;
338  
339     sub import
340     {
341         croak("usage: use Subst qw(from to)")
342             unless @_ == 3 ;
343         my ($self, $from, $to) = @_ ;
344         filter_add(
345             sub 
346             {
347                 my ($status) ;
348                 s/$from/$to/
349                     if ($status = filter_read()) > 0 ;
350                 $status ;
351             })
352     }
353     1 ;
354
355 and is used like this:
356
357     use Subst qw(Joe Jim) ;
358     print "Where is Joe?\n" ;
359
360
361 =head2 Example 3: Using the context within the filter
362
363 Here is a filter which a variation of the C<Joe2Jim> filter. As well as
364 substituting all occurrences of C<"Joe"> to C<"Jim"> it keeps a count
365 of the number of substitutions made in the context object.
366
367 Once EOF is detected (C<$status> is zero) the filter will insert an
368 extra line into the source stream. When this extra line is executed it
369 will print a count of the number of substitutions actually made.
370 Note that C<$status> is set to C<1> in this case.
371
372     package Count ;
373  
374     use Filter::Util::Call ;
375  
376     sub filter
377     {
378         my ($self) = @_ ;
379         my ($status) ;
380  
381         if (($status = filter_read()) > 0 ) {
382             s/Joe/Jim/g ;
383             ++ $$self ;
384         }
385         elsif ($$self >= 0) { # EOF
386             $_ = "print q[Made ${$self} substitutions\n]" ;
387             $status = 1 ;
388             $$self = -1 ;
389         }
390
391         $status ;
392     }
393  
394     sub import
395     {
396         my ($self) = @_ ;
397         my ($count) = 0 ;
398         filter_add(\$count) ;
399     }
400  
401     1 ;
402
403 Here is a script which uses it:
404
405     use Count ;
406     print "Hello Joe\n" ;
407     print "Where is Joe\n" ;
408
409 Outputs:
410
411     Hello Jim
412     Where is Jim
413     Made 2 substitutions
414
415 =head2 Example 4: Using filter_del
416
417 Another variation on a theme. This time we will modify the C<Subst>
418 filter to allow a starting and stopping pattern to be specified as well
419 as the I<from> and I<to> patterns. If you know the I<vi> editor, it is
420 the equivalent of this command:
421
422     :/start/,/stop/s/from/to/
423
424 When used as a filter we want to invoke it like this:
425
426     use NewSubst qw(start stop from to) ;
427
428 Here is the module.
429
430     package NewSubst ;
431  
432     use Filter::Util::Call ;
433     use Carp ;
434  
435     sub import
436     {
437         my ($self, $start, $stop, $from, $to) = @_ ;
438         my ($found) = 0 ;
439         croak("usage: use Subst qw(start stop from to)")
440             unless @_ == 5 ;
441  
442         filter_add( 
443             sub 
444             {
445                 my ($status) ;
446              
447                 if (($status = filter_read()) > 0) {
448              
449                     $found = 1
450                         if $found == 0 and /$start/ ;
451              
452                     if ($found) {
453                         s/$from/$to/ ;
454                         filter_del() if /$stop/ ;
455                     }
456              
457                 }
458                 $status ;
459             } )
460     
461     }
462      
463     1 ;
464
465 =head1 AUTHOR
466
467 Paul Marquess 
468
469 =head1 DATE
470
471 26th January 1996
472
473 =cut
474