File Coverage

blib/lib/Text/Perlate.pm
Criterion Covered Total %
statement 9 165 5.4
branch 0 114 0.0
condition 0 36 0.0
subroutine 3 8 37.5
pod 0 5 0.0
total 12 328 3.6


line stmt bran cond sub pod time code
1             package Text::Perlate;
2              
3 1     1   5895 use 5.006;
  1         3  
  1         43  
4 1     1   5 use strict;
  1         3  
  1         30  
5 1     1   5 use warnings;
  1         5  
  1         2556  
6              
7             our $VERSION = '0.94';
8              
9             =pod
10              
11             =head1 NAME
12              
13             Text::Perlate - Template module using Perl as the langauge.
14              
15             =head1 SYNOPSIS
16              
17             use Text::Perlate;
18              
19             $Text::Perlate::defaults->{...} = ...;
20              
21             print Text::Perlate::main($options);
22              
23             To catch errors, wrap calls to this module in eval{} and check $@.
24              
25             =head1 DESCRIPTION
26              
27             This module provides a simple translation system for writing files that are
28             mostly text, TeX, HTML, XML, an email message, etc with some Perl code
29             interspersed. The input files use [[ and ]] to mark the beginning and end of
30             Perl code. Text outside of these tags is returned without modification (except
31             for the effects of conditional statements or loops contained in surrounding
32             tags of course). PHP users will notice the similarity to the tags used
33             by PHP to separate code from literal text.
34              
35             A template written in this style is called a "perlate". In contrast, "Perlate"
36             is the name of this module.
37              
38             This approach provides the simplicity of using a language you're accustomed to
39             (Perl) for logic, rather than inventing a trimmed-down language. Admittedly
40             that means you must exercise restraint in separating logic and text. However,
41             this approach is faster (in execution) and less bug-prone since it uses a
42             well-developed compiler and language you already know well. Many argue that an
43             unrestrained programmer will find a way to shoot themselves despite the best
44             efforts of the language to prevent it. If you agree, Perlate is for you.
45              
46             =head1 WRITING PERLATES
47              
48             As HTML is a common use for Perlate, the following examples show HTML code
49             outside the tags. The Perl code is surrounded in [[ ]] tags. There is no
50             preamble or postscript; the file is otherwise indistinguishable from its
51             output. For example, the following is a valid perlate:
52              
53            
54             [[ if($_params->{enabled}) { ]]
55             Enabled = [[ _get "enabled"; ]]
56             [[ } ]]
57            
58              
59             Note that statements that normally end in a semicolon must include the
60             semicolon as shown.
61              
62             Perlate declares some variables and functions for you in the setup code. All
63             symbol names prefixed with an underline are reserved. So far, the following
64             are available for your use:
65              
66             =over
67              
68             =item * _echo() emits the expressions passed to it.
69              
70             =item * _get() emits the parameters named by the arguments. _get("foo") is the
71             same as _echo($params->{foo}) and _echo($_options->{params}{foo}).
72              
73             =item * _echoifdef() and _getifdef() are the same as _echo() and _get() except
74             they prevent warnings about undefined values.
75              
76             =item * $_options is a copy of the same hash passed by the caller, with any
77             default settings (from the global variable $defaults) added to it. Options
78             tell Perlate.pm what to do (what source file to load, what to do with the
79             output, etc).
80              
81             =item * $_params is a convenient alias of $_options->{params}. This contains
82             input parameters to your perlate.
83              
84             =back
85              
86             A more interesting example of using Perlate follows. The following is an
87             example Perl program that calls a perlate:
88              
89             #!/usr/bin/perl
90             use strict;
91             use warnings;
92             use Text::Perlate;
93             eval {
94             print Text::Perlate::main({
95             input_file => "my.html.perlate",
96             params => {
97             enabled => 1,
98             times => 6,
99             message => "Display this 6 times.",
100             },
101             });
102             };
103             if($@) {
104             print STDERR "An error occurred: $@\n";
105             }
106              
107             The file my.html.perlate might contain:
108              
109            
110             [[- if($_params->{enabled}) { ]]
111             Enabled.
112             [[- for(my $count = 0; $count < $_params->{times}; $count++) { ]]
113             [[ _get "message"; ]]
114             [[- } ]]
115             [[- } ]]
116             [[ _echo "This was repeated $_params->{times} times."; ]]
117            
118              
119             Some of the tags in the example have a leading hyphen. This signals Perlate to
120             remove one line of whitespace in the source before the tag. One trailing
121             hyphen means to remove one line of whitespace after the tag. N hyphens removes
122             up to N lines, and a plus removes all blank lines. Removal always stops at the
123             first nonblank line. Next, there may be an octothorpe (#), which indicates
124             that the entire tag is a comment. Regular Perl comments within a tag are valid
125             and terminate at the end of the tag or the first newline, as might be expected.
126             To summarize, the tags have the following syntax (note the position of the
127             required whitespace):
128              
129             \[\[(\-*|\+)#?\s.*\s(\-*|\+)\]\]
130              
131             The strange indentation in the example above is designed to maintain the
132             indentation levels of the output. Flow control statements strip one line of
133             leading whitespace and are indented independently of the HTML code and output
134             statements. This is simply a suggested style. Feel free to invent your own.
135              
136             While you don't need to know the internals to use Perlate, it may be useful to
137             understand the basic approach. It translates the perlate into a single string
138             containing Perl code, surrounds it with a bit of setup and tear-down code, then
139             eval's the string to create a new package, then calls the package's _main()
140             function. The setup code includes a "package" statement and
141             "sub _main {". The text between the tags is quoted and rewritten as a call to
142             the _echo function. This way the user can open a lexical scope in one tag and
143             close it in a later one, for example, to conditionally emit certain text or to
144             repeat a block of text in a loop. A perlate is only eval'd once. Subsequent
145             calls to it simply call _main() again. (This is the reason it is wrapped in a
146             function declaration.) Perl allows function declarations inside of functions,
147             so it's valid to define a function in a perlate that's called by other parts of
148             the same perlate. This can be useful on a web page, for example, if there is a
149             bit of HTML code that needs to be repeated in several places. (If this doesn't
150             quite make sense, try executing the code above with the I
151             flag.)
152              
153             =head1 OPTIONS
154              
155             There are some options available in $options. Defaults for these options can
156             be specified as a hash in the global variable $defaults. For options where it
157             makes sense, the default is combined with the passed options. For example, a
158             default perlate input file can be specified instead of passing an explicit
159             filename with every call. When used with Apache and mod_perl, for example,
160             setting defaults can be useful in a PerlRequire script.
161              
162             Several options are available:
163              
164             =over
165              
166             =item * $options->{input_file} specifies a filename to read the perlate from.
167             Overrides both the input_file and input_string defaults. If the filename is
168             absolute (begins with a slash), the path and correct directory are not
169             searched. See also $options->{path}.
170              
171             =item * $options->{input_string} specifies the source for a perlate as a
172             literal string. Overrides both the input_file and input_string defaults. See
173             also $options->{cache_id}.
174              
175             =item * $options->{cache_id} specifies a unique ID for this perlate. If the
176             cache_id already exists, the perlate is not parsed again and the existing
177             package name is reused. See also CAVEATS with regard to memory usage. (This
178             is ignored when specifying $options->{input_file}.)
179              
180             =item * $options->{params} contains the input parameters to the perlate itself.
181             These can be emitted into the perlate's output by calling _get("param name") or
182             they can be accessed through the $_params hash. Default parameters are added
183             to this hash, but do not override values set in $options->{params}.
184              
185             =item * $options->{path} may be set to an array of directory names to search.
186             $defaults->{path} is always searched after that. When you add paths to
187             $defaults->{path}, your code may work better with future code of yours if you
188             unshift them onto the array rather than using direct assignment. The search
189             order is always: current directory, $options->{path}, $defaults->{path}, @INC.
190             The path option as seen from inside the perlate (called $_options->{path})
191             includes all of these directories. See also $options->{skip_path}.
192              
193             =item * $options->{skip_path} specifies to interpret filenames literally rather
194             than searching $options->{path}, @INC, etc. (Ignored without
195             $options->{input_file}.)
196              
197             =item * $options->{raw} may be set to true to indicate that the whole file is
198             Perl code without [[ ]] tags. This is useful for using parameter passing and
199             searching $options->{path}. This is probably not going to be useful very
200             often, except perhaps for debugging, however it is officially supported.
201              
202             =item * $options->{preprocess_only} may be set to true to return the
203             preprocessed file without executing (or caching) anything. This is probably
204             only useful for debugging, unless you want to rely on the existence of _main(),
205             which is subject to change. At times, this can explain why Perl is reporting a
206             syntax error.
207              
208             =back
209              
210             =head1 OTHER FEATURES & NOTES
211              
212             The @INC list of directories is automatically appended to the search path.
213             This means you can put perlates in your lib directory beside any modules that
214             call them. After all, a perlate represents a module (in a loose sense). One
215             common approach in large web applications uses a small index.pl file to call a
216             module containing all the real logic. Searching @INC fits in nicely with that
217             design.
218              
219             Assign an integer to $Text::Perlate::debug to see some debugging information.
220             0 is none. 1 or more enables basic debugging. 10 or more dumps the code as
221             it is eval'd. Changes to this knob are not considered relevent to the API.
222              
223             =head1 CAVEATS
224              
225             As described above, perlates may be specified by name, or the contents of an
226             unnamed perlate may be passed directly. Naming a file or cache_id is
227             preferable because Perlate will then compile each perlate only once. For files, the device number,
228             inode number, and modification time are used to uniquely identify the specified
229             file. Without caching, the memory usage will grow slightly with each
230             execution, since there is no way to unload a module from memory, and each
231             perlate is loaded more or less like any regular Perl module. Please email the
232             author if you know of a reasonable way to free that memory.
233              
234             Of course, general programming wisdom holds that global variables are usually a
235             bad approach. In a perlate, they require unusual care for several reasons.
236             First, you must take care to free their content to avoid wasting memory, even
237             if the perlate aborts via die(). Second, you must take care to initialize it
238             to the value you expect every time the perlate executes, even if you need it
239             initialized to undef; this is necessary because a perlate's namespace (package)
240             is reused when possible, which means that a global variable's value will
241             usually (but not always) persist between repeated executions. Third, recursive
242             templates need to save and restore the values of global variables. If you
243             really need a global variable, always use the "local" keyword because it
244             addresses all of these issues. If you need a variable to keep a persistent
245             value, give it an explicit package name that you control, such as the package
246             name of the caller, so it doesn't break if Perlate changes the name of the
247             execution's namespace. (Perlate tries to reuse the same namespace, but never
248             guarantees it. The logic for deciding whether to reuse it will probably change
249             between versions.) A concise way to declare such variables looks like this:
250              
251             local our $foo;
252              
253             Errors and warnings usually report the line number they occur on. However,
254             Perl seems easily confused over line numbers in an eval. Often line 1 or the
255             last line will be erroneously reported as the error point. Perlate is careful
256             to keep the line numbers as seen by Perl consistent with the perlate, but as
257             Perl sometimes gets confused this isn't always helpful.
258              
259             The "use strict;" and "use warnings;" pragmas are applied to all perlates.
260             This is not optional. If you insist on writing bad code, you can write "no
261             strict; no warnings;" to explicitly turn those off.
262              
263             This has NOT been tested with threading, which probably means it might not work
264             with Apache 2. However, I'd be happy to fix any problems with threading, if
265             you send me a bug report. Also send me a message if you can verify that this
266             works under Apache 2 and/or threading so I can remove this paragraph.
267              
268             Recursive perlates are supported and have no known caveats.
269              
270             =head1 INSTALLATION
271              
272             This module has no dependencies besides Perl itself. Follow your favorite
273             standard installation procedure.
274              
275             =head1 VERSION AND HISTORY
276              
277             =over
278              
279             Version 0.94 is likely to be identical to version 1.0. Version 1.0 may contain
280             incompatible changes, but this is unlikely unless anyone suggests a really good
281             reason.
282              
283             =item * Version 0.94, released 2007-12-04. Fixed botched release.
284              
285             =item * Version 0.92, released 2007-12-03. Added options skip_path and
286             cache_id. Moved repository to Git. Added Text::Perlate::Apache.
287              
288             =item * Version 0.91, released 2007-05-23. Renamed the rawperl option to raw.
289             Renamed the module from Template::Perlate to Text::Perlate. Fixed problem
290             preventing comments and code from sharing one tag.
291              
292             =item * Version 0.90, released 2007-03-02.
293              
294             =back
295              
296             =head1 SEE ALSO
297              
298             The source repository is at git://git.devpit.org/Text-Perlate/
299              
300             Text::Perlate::Apache provides a direct Apache handler.
301              
302             =head1 AUTHOR
303              
304             Leif Pedersen, Ebilbo@hobbiton.orgE
305              
306             Please send suggestions and bugfixes to this address. Even if you have nothing
307             to contribute, please send a quick message. I'd like to get an idea of how
308             many people use this software. Thanks!
309              
310             =head1 COPYRIGHT AND LICENSE
311              
312             This may be distributed under the terms below (BSD'ish) or under the GPL.
313            
314             Copyright (C) 2006-2007 by Leif Pedersen. All rights reserved.
315            
316             Redistribution and use in source and binary forms, with or without
317             modification, are permitted provided that the following conditions are
318             met:
319            
320             1. Redistributions of source code must retain the above copyright
321             notice, this list of conditions and the following disclaimer.
322            
323             2. Redistributions in binary form must reproduce the above copyright
324             notice, this list of conditions and the following disclaimer in the
325             documentation and/or other materials provided with the
326             distribution.
327            
328             THIS SOFTWARE IS PROVIDED BY AUTHORS AND CONTRIBUTORS "AS IS" AND ANY
329             EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
330             IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
331             PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTHORS OR CONTRIBUTORS BE
332             LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
333             CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
334             SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
335             BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
336             WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
337             OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
338             ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
339              
340             =cut
341              
342              
343             our $debug;
344              
345             sub main {
346 0     0 0   my ($options) = @_;
347              
348             # Copy input data for modification
349 0           $options = {%$options};
350 0 0         $options->{params} = {%{$options->{params} or {}}};
  0            
351 0 0         $options->{path} = ['.', @{$options->{path} or []}];
  0            
352              
353 0           our $defaults;
354 0           foreach my $default (keys %$defaults) {
355 0 0 0       if($default eq 'params') {
    0          
    0          
356             # Override default params with specified params.
357 0           %{$options->{$default}} = (
  0            
358 0           %{$defaults->{$default}},
359 0           %{$options->{$default}},
360             );
361             } elsif($default eq 'path') {
362             # Search specified path before default path.
363 0           push @{$options->{$default}}, @{$defaults->{$default}};
  0            
  0            
364             } elsif($default eq 'input_file' or $default eq 'input_string') {
365             # input_file and input_string are both overridden by specifying either in $options.
366 0 0 0       $options->{$default} = $defaults->{$default} unless exists $options->{input_file} or exists $options->{input_string};
367             } else {
368 0 0         $options->{$default} = $defaults->{$default} unless exists $options->{$default};
369             }
370             }
371              
372             # Add @INC to search path.
373 0           push @{$options->{path}}, @INC;
  0            
374              
375             # $package_name is unique for each compilation. This prevents sub names from
376             # conflicting; since all subs are public and named globally in the current
377             # package (not in the current lexical scope), if the code declares a sub named
378             # main() in a simple eval with no package statement, it will replace this
379             # module's main() on the next execution! Also, declaring a package allows us
380             # to cache compilations of a module; after eval'ing to compile the perlate, it
381             # can be executed multiple times by calling ${package_name}::_main() multiple
382             # times.
383             #
384             # The unfortunate side-effect is that these packages are never destroyed, so
385             # they are a memory leak because global variables in the namespace and Perl's
386             # infrastructure for the namespace itself are never freed, even if they are not
387             # used again. (I think all modules that do this have that problem though.)
388             # The silver lining is that it would be terrible style to declare globals
389             # inside perlates anyway, and reused compilations don't leak.
390             #
391             # Caching is done by simply reusing the package created during the first run.
392             # Each package is uniquely identified, if possible. (If not, it can't be
393             # reused.)
394              
395 0           my $input;
396             my $reported_filename; # The filename we tell Perl that the eval'd code is from.
397 0           my $package_name;
398 0           my $compiled; # True if cached package found
399 0 0         if(defined $options->{input_string}) {
    0          
400             # input from a string
401 0           $input = $options->{input_string};
402 0 0         warn "input_string specified without a cache_id (use explicit undef to quiet this warning)" unless exists $options->{cache_id};
403 0 0         if(defined $options->{cache_id}) {
404 0           $reported_filename = $options->{cache_id};
405 0           $package_name = __PACKAGE__ . "::ExplicitCacheId::" . $options->{cache_id};
406 0 0         print STDERR __PACKAGE__ . ": Using package name ${package_name}.\n" if $debug;
407 0           $compiled = eval "\$${package_name}::_compiled";
408             }
409             } elsif(defined $options->{input_file}) {
410             # input from a filename
411 0           my $filename = $options->{input_file};
412 0           $reported_filename = $filename;
413              
414 0           my $fh;
415 0 0 0       if($options->{skip_path} or $filename =~ qr~^/~s) {
416             # Use absolute path.
417 0 0         print STDERR __PACKAGE__ . ": Using absolute path: ${filename}.\n" if $debug;
418 0 0         open($fh, "<", $filename) or die "${filename}: $!\n";
419             } else {
420             # Search path for relative name.
421 0 0         print STDERR __PACKAGE__ . ": Search path is:\n\t", join("\n\t", @{$options->{path}}), "\n" if $debug;
  0            
422 0           foreach my $path (@{$options->{path}}) {
  0            
423 0 0         print STDERR __PACKAGE__ . ": Searching path: ${path}/${filename}..." if $debug;
424 0 0         if(-e "${path}/${filename}") {
425 0 0         print STDERR __PACKAGE__ . ": found\n" if $debug;
426 0 0         open($fh, "<", "${path}/${filename}") or die "${path}/${filename}: $!\n";
427 0           last;
428             }
429 0 0         print STDERR __PACKAGE__ . ": not found\n" if $debug;
430             }
431 0 0         unless($fh) {
432 0           die "$filename: not found in search path\n";
433             }
434             }
435              
436             # Use the device number, inode number, and mod time to uniquely identify this file in our cache.
437 0           my @stat = stat($fh);
438 0 0         die "$filename: successful open() but stat() failed: $!\n" unless @stat;
439 0           $package_name = __PACKAGE__ . "::CachedFile::" . $stat[0] . '_' . $stat[1] . '_' . $stat[9];
440 0 0         print STDERR __PACKAGE__ . ": Using package name ${package_name}.\n" if $debug;
441 0           $compiled = eval "\$${package_name}::_compiled";
442              
443 0 0 0       if(not $compiled or $options->{preprocess_only}) {
444 0           local $/ = undef;
445 0           $input = <$fh>;
446             }
447             }
448 0 0 0       print STDERR __PACKAGE__ . ": Already compiled.\n" if $debug and $compiled;
449 0 0 0       die "No input specified\n" unless $compiled or defined $input;
450              
451             # Use a temp package name unless one was assigned above.
452 0 0         unless(defined $package_name) {
453 0           our $run_count;
454 0 0         if(defined $run_count) { $run_count++; } else { $run_count = 0; }
  0            
  0            
455 0           $package_name = __PACKAGE__ . "::Uncached::${run_count}";
456             }
457              
458             # Untaint input. If it was read from a file, it'll be tainted. It seems
459             # reasonable to simply trust that the caller won't pass untrusted input as a
460             # perlate. $input could be undef if $compiled.
461 0 0         if(defined $input) {
462 0 0         $input =~ qr/^(.*)$/s or die "Can't happen!";
463 0           $input = $1;
464             }
465              
466 0 0         if($options->{preprocess_only}) {
467 0 0         print STDERR __PACKAGE__ . ": preprocess_only selected.\n" if $debug;
468 0           return preprocess($input);
469             }
470 0 0         unless($compiled) {
471 0 0         print STDERR __PACKAGE__ . ": Preprocessing.\n" if $debug;
472 0 0         $input = preprocess($input) unless $options->{raw};
473 0 0         print STDERR __PACKAGE__ . ": Compiling.\n" if $debug;
474 0           compile($package_name, $reported_filename, $input);
475             }
476 0 0         print STDERR __PACKAGE__ . ": Running.\n" if $debug;
477 0           return run($package_name, $options);
478             }
479              
480             # This translates $input into eval'able code, but does not add any supporting
481             # code.
482             sub preprocess {
483 0     0 0   my ($input) = @_;
484              
485             # Push all the chunks of code onto an array, then join it at the end. This is
486             # more efficient that concatenating as we go. Track line numbers in $linenum
487             # because we have to add a newline after every tag in case it contained a
488             # comment, then tell Perl to restart the line numbering with "#line 10".
489              
490 0           my @code_chunks = ();
491 0           my $linenum = 0;
492              
493 0           until($input eq '') {
494 0 0 0       unless($input =~ s/^(.*?)\[\[(\-*|\+)(#?)(\s.*?\s)(\-*|\+)\]\]//s or $input =~ s/^(.*)$//s) {
495 0           die "Can't happen: didn't match a regex";
496             }
497 0           my $text = $1;
498 0           my $strip_pre = $2;
499 0           my $comment_flag = $3;
500 0           my $code = $4;
501 0           my $strip_post = $5;
502              
503             # Some checking to help find typos
504              
505 0 0         if($text =~ qr/(\[\[.*)/s) {
506             # $text contains [[
507 0           my $tag = $1;
508 0 0         if(not $tag =~ qr/^\[\[(\-*|\+)#?\s/s) {
    0          
    0          
509             # [[ would've matched the RE at the top of this loop if it were in this format.
510 0           die "Invalid tag after line ${linenum}, missing space after [[ near $tag\n";
511             } elsif($tag =~ qr/\]\]/s) {
512             # ]] would've matched the RE at the top of this loop if there were a space
513             # before it.
514 0           die "Invalid tag after line ${linenum}, missing space before ]] near $tag\n";
515             } elsif(not $tag =~ qr/\]\]/s) {
516 0           die "Invalid tag after line ${linenum}, missing ending ]] near $tag\n";
517             }
518 0           die "Invalid tag near after ${linenum}, near $tag (but I can't tell why it's invalid)"; # shouldn't happen
519             }
520              
521 0 0         if($text =~ qr/(.*?\]\])/s) {
522             # $text contains ]].
523 0           die "Invalid tag after line ${linenum}, extraneous ]] near $1\n";
524             }
525              
526 0 0 0       if(defined $code and $code =~ qr/^(.*?\]\])/s) {
527             # $code contains ]]. This wouldn't slip through unless it didn't match the RE
528             # at the top of this loop.
529 0           my $tag = '[[' . $strip_pre . $1;
530 0           die "Invalid tag after line ${linenum}, missing space before ]] near $tag\n";
531             }
532              
533 0 0 0       if(defined $code and $code =~ qr/\[\[/s) {
534             # $code contains [[. There would only be another [[ if there's a missing ]].
535 0           my $tag = '[[' . $strip_pre . $code;
536 0           die "Invalid tag after line ${linenum}, missing ending ]] near $tag\n";
537             }
538              
539             # Strip space as specified by the tag modifiers
540 0           my $stripped;
541              
542 0           $stripped = '';
543 0 0         if(defined $strip_pre) {
544             # $strip_pre contains indications from the beginning of the tag about whether
545             # to strip newlines from the text before the tag. Text generated by the tag is
546             # never stripped.
547 0 0         if($strip_pre eq '+') {
548             # A plus behaves just like an infinite number of minuses
549 0           $text =~ s/((\r?\n[ \t]*)*)$//s;
550 0           $stripped = $1;
551             } else {
552             # A minus means strip one newline and the whitespace after it. Multiple
553             # minuses strip multiple newlines. More minuses than newlines is not an error.
554 0           my $num = length($strip_pre);
555 0           $text =~ s/((\r?\n[ \t]*){0,$num})$//s;
556 0           $stripped = $1;
557             }
558             }
559              
560             # Change $text into eval'able code and append to eval string.
561 0 0 0       if(defined $text and $text ne '') {
562 0           $text =~ s/'/'."'".'/sg;
563 0           $text =~ s/\\/'."\\\\".'/sg;
564 0           $text = "_echo('$text');";
565 0           push @code_chunks, $text;
566              
567             # Count newlines.
568 0           $text =~ s/[^\n]+//sg;
569 0           $linenum += length($text);
570             }
571              
572             # Hide stripped newlines between statements to keep line numbers consistent.
573 0           $stripped =~ s/[^\n]+//sg;
574 0           push @code_chunks, $stripped;
575 0           $linenum += length($stripped);
576              
577 0           $stripped = '';
578 0 0         if(defined $strip_post) {
579             # $strip_post contains indications from the end of the tag about whether to
580             # strip newlines from the text after the tag. Text generated by the tag is
581             # never stripped.
582 0 0         if($strip_post eq '+') {
583             # A plus behaves just like an infinite number of minuses
584 0           $input =~ s/^(([ \t]*\r?\n)*)//s;
585 0           $stripped = $1;
586             } else {
587 0           my $num = length($strip_post);
588 0           $input =~ s/^(([ \t]*\r?\n){0,$num})//s;
589 0           $stripped = $1;
590             }
591             }
592              
593             # Interpret $code
594 0 0 0       if(defined $code and $code ne '') {
595             # $code might end in a comment without a trailing newline, so add a newline and
596             # reset Perl's line numbering.
597 0 0         push @code_chunks, $code unless $comment_flag;
598 0           $code =~ s/[^\n]//sg;
599 0           $linenum += length($code);
600 0           push @code_chunks, "\n#line ${linenum}\n";
601             }
602              
603             # Hide stripped newlines between statements to keep line numbers consistent.
604 0           $stripped =~ s/[^\n]+//sg;
605 0           push @code_chunks, $stripped;
606 0           $linenum += length($stripped);
607             }
608              
609             # Join with spaces between statements.
610 0           return "@code_chunks";
611             }
612              
613             sub compile {
614 0     0 0   my ($package_name, $reported_filename, @code_chunks) = @_;
615              
616             # Add the setup and tear-down cruft. This can't happen in preprocess() because
617             # raw perlates need it too.
618 0           @code_chunks = (
619             'use strict; use warnings;',
620              
621             # These variables interface with external code.
622             'our (@_out, $_options, $_params);',
623              
624             # Calling _echo() is the only way code emits output.
625             'sub _echo { push @_out, @_; }',
626              
627             # Extra convenience functions.
628             'sub _echoifdef { foreach (@_) { _echo $_ if defined $_; } }',
629             'sub _get { foreach (@_) { _echo $_params->{$_}; } }',
630             'sub _getifdef { foreach (@_) { _echo $_params->{$_} if defined $_ and defined $_params->{$_}; } }',
631              
632             # Encapsulate the execution in a function so we can call it multiple times (to
633             # support caching).
634             'sub _main {',
635              
636             # Localize @_out to ensure it frees the memory before returning. This is also
637             # important to ensure reentrancy for recursion.
638             'local @_out = ();',
639              
640             @code_chunks,
641              
642             'return join("", @_out); }',
643             );
644              
645             # Compile the code, but don't run it. Run it later by calling
646             # ${package_name}::_main().
647              
648 0 0         if(defined $reported_filename) {
649 0           $reported_filename = "#line 1 ${reported_filename}\n";
650             } else {
651 0           $reported_filename = "";
652             }
653              
654 0           clean_eval("${reported_filename}package ${package_name}; @code_chunks our \$_compiled = 1;");
655              
656 0           return ();
657             }
658              
659             sub run {
660 0     0 0   my ($package_name, $options) = @_;
661              
662 0           my $out;
663              
664             # Insert shared variables. Localize them to ensure it frees the memory before
665             # returning. This is also important to ensure reentrancy for recursion.
666 0           eval "
667             local \$${package_name}::_options = \$options;
668             local \$${package_name}::_params = \$options->{params};
669              
670             # RUN THE CODE
671             (\$out) = clean_eval(\"\${package_name}::_main();\");
672             ";
673 0 0         die $@ if $@;
674              
675             # XXX: We should mitigate the memory leak problem by undef'ing globals at the
676             # end by looping through %{$package_name::} rather than just these. Can we use
677             # a trick like that to also delete the namespace itself? Of course, this
678             # should only be done on uncached perlates.
679              
680 0           return $out;
681             }
682              
683             # This is a separate sub because all its local variables become shared with the
684             # eval'd code.
685             sub clean_eval {
686 0 0 0 0 0   print STDERR "--------------------------------\n@_\n--------------------------------\n" if $debug and $debug >= 10;
687 0           @_ = eval "@_";
688 0 0         die $@ if $@;
689 0           return @_;
690             }
691              
692             1