blib/lib/Mason/Compilation.pm untested

filter: Statementstmt 0.0% 0 / 349 Branchbran 0.0% 0 / 134 Conditioncond 0.0% 0 / 99 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 5 Podpod n/a totaltotal 0.0% 0 / 587 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 # Copyright (c) 1998-2005 by Jonathan Swartz. All rights reserved.
2 # This program is free software; you can redistribute it and/or modify it
3 # under the same terms as Perl itself.
4  
5 package Mason::Compilation;
6 $Mason::Compilation::VERSION = '2.23';
7 use File::Basename qw(dirname);
8 use Guard;
9 use Mason::Component::ClassMeta;
10 use Mason::Util qw(dump_one_line json_encode read_file taint_is_on trim);
11 use Mason::Moose;
12  
13 # Passed attributes
14 has 'interp' => ( required => 1, weak_ref => 1 );
15 has 'path' => ( required => 1 );
16 has 'source_file' => ( required => 1 );
17  
18 # Derived attributes - most of these should be class attributes :(
19 has 'bad_attribute_hash' => ( lazy_build => 1, init_arg => undef );
20 has 'bad_method_hash' => ( lazy_build => 1, init_arg => undef );
21 has 'dir_path' => ( lazy_build => 1, init_arg => undef );
22 has 'named_block_regex' => ( lazy_build => 1, init_arg => undef );
23 has 'unnamed_block_regex' => ( lazy_build => 1, init_arg => undef );
24 has 'valid_flags_hash' => ( lazy_build => 1, init_arg => undef );
25  
26 # Valid Perl identifier
27 my $identifier = qr/[[:alpha:]_]\w*/;
28  
29 #
30 # BUILD
31 #
32  
33 method BUILD () {
34  
35 # Initialize state
36 $self->{blocks} = {};
37 $self->{blocks}->{class} = '';
38 $self->{source} = read_file( $self->source_file );
39 $self->{source} =~ s/\r\n?/\n/g;
40 $self->{line_number} = 1;
41 $self->{methods} = { main => $self->_new_method_hash( name => 'main' ) };
42 $self->{current_method} = $self->{methods}->{main};
43 $self->{is_pure_perl} = $self->interp->is_pure_perl_comp_path( $self->path );
44 }
45  
46 method _build_bad_attribute_hash () {
47 return { map { ( $_, 1 ) } @{ $self->bad_attribute_names } };
48 }
49  
50 method _build_bad_method_hash () {
51 return { map { ( $_, 1 ) } @{ $self->bad_method_names } };
52 }
53  
54 method _build_dir_path () {
55 return dirname( $self->path );
56 }
57  
58 method _build_named_block_regex () {
59 my $re = join '|', @{ $self->named_block_types };
60 return qr/$re/i;
61 }
62  
63 method _build_unnamed_block_regex () {
64 my $re = join '|', @{ $self->unnamed_block_types };
65 return qr/$re/i;
66 }
67  
68 method _build_valid_flags_hash () {
69 return { map { ( $_, 1 ) } @{ $self->valid_flags } };
70 }
71  
72 #
73 # MODIFIABLE METHODS
74 #
75  
76 method bad_attribute_names () {
77 return [qw(args m cmeta handle render wrap main)];
78 }
79  
80 method bad_method_names () {
81 return [qw(args m cmeta)];
82 }
83  
84 method compile () {
85 $self->parse();
86 return $self->_output_compiled_component();
87 }
88  
89 method named_block_types () {
90 return [qw(after augment around before filter method override)];
91 }
92  
93 method output_class_footer () {
94 return "";
95 }
96  
97 method output_class_header () {
98 return $self->interp->class_header;
99 }
100  
101 method parse () {
102  
103 # We need to untaint the component source or else the regexes may fail.
104 #
105 ( $self->{source} ) = ( ( delete $self->{source} ) =~ /(.*)/s )
106 if taint_is_on();
107  
108 if ( $self->{is_pure_perl} ) {
109 $self->{source} = "<%class> " . $self->{source} . " </%class>";
110 delete( $self->{methods}->{main} );
111 }
112  
113 my $lm = '';
114 my $iter = 0;
115 while (1) {
116 $self->_throw_syntax_error("parse loop iterated >1000 times - infinite loop?")
117 if ++$iter > 1000;
118 $self->{last_match} = $lm;
119 $self->_match_end && last;
120 $self->_match_apply_filter_end && last;
121 $self->_match_unnamed_block && ( $lm = 'unnamed_block' ) && next;
122 $self->_match_named_block && ( $lm = 'named_block' ) && next;
123 $self->_match_unknown_block && ( $lm = 'unknown_block' ) && next;
124 $self->_match_apply_filter && ( $lm = 'apply_filter' ) && next;
125 $self->_match_substitution && ( $lm = 'substitution' ) && next;
126 $self->_match_component_call && ( $lm = 'component_call' ) && next;
127 $self->_match_perl_line && ( $lm = 'perl_line' ) && next;
128 $self->_match_bad_close_tag && ( $lm = 'bad_close_tag' ) && next;
129 $self->_match_plain_text && ( $lm = 'plain_text' ) && next;
130  
131 $self->_throw_syntax_error(
132 "could not parse next element at position " . pos( $self->{source} ) );
133 }
134 }
135  
136 method process_perl_code ($coderef) {
137 return $coderef;
138 }
139  
140 method unnamed_block_types () {
141 return [qw(args class doc flags init perl shared text)];
142 }
143  
144 method valid_flags () {
145 return [qw(extends)];
146 }
147  
148 #
149 # PRIVATE METHODS
150 #
151  
152 method _add_to_class_block ($text) {
153  
154 # Don't add a line number comment when following a perl-line.
155 # We know a perl-line is always _one_ line, so we know that the
156 # line numbers are going to match up as long as the first line in
157 # a series has a line number comment before it. Adding a comment
158 # can break certain constructs like qw() list that spans multiple
159 # perl-lines.
160 if ( $self->{last_match} ne 'perl_line' ) {
161 $text = $self->_output_line_number_comment . $text;
162 }
163 $self->{blocks}->{class} .= $text;
164 }
165  
166 method _add_to_current_method ($text) {
167 if ( $self->{last_match} ne 'perl_line' ) {
168 $text = $self->_output_line_number_comment . $text;
169 }
170  
171 $self->{current_method}->{body} .= $text;
172 }
173  
174 method _assert_not_nested ($block_type) {
175 $self->_throw_syntax_error(
176 "Cannot nest <%$block_type> block inside <%$self->{in_recursive_parse}> block")
177 if $self->{in_recursive_parse};
178 }
179  
180 method _attribute_declaration ($name, $params, $line_number) {
181 $self->_throw_syntax_error("'$name' is reserved and cannot be used as an attribute name")
182 if $self->bad_attribute_hash->{$name};
183 return $self->_processed_perl_code(
184 sprintf(
185 "%shas '%s' => %s",
186 $self->_output_line_number_comment($line_number),
187 $name, $params
188 )
189 );
190 }
191  
192 method _handle_after_block () { $self->_handle_method_modifier_block( 'after', @_ ) }
193 method _handle_around_block () { $self->_handle_method_modifier_block( 'around', @_ ) }
194 method _handle_augment_block () { $self->_handle_method_modifier_block( 'augment', @_ ) }
195 method _handle_before_block () { $self->_handle_method_modifier_block( 'before', @_ ) }
196  
197 method _handle_override_block () {
198 $self->_handle_method_modifier_block( 'override', @_ );
199 }
200  
201 method _handle_method_modifier_block ($block_type, $contents, $name) {
202 my $modifier = $block_type;
203  
204 $self->_throw_syntax_error("Invalid method modifier name '$name'")
205 if $name !~ /^$identifier$/;
206  
207 $self->_assert_not_nested($block_type);
208  
209 my $method_key = "$block_type $name";
210  
211 $self->_throw_syntax_error("Duplicate definition of method modifier '$method_key'")
212 if exists $self->{methods}->{"$method_key"};
213  
214 my $method =
215 $self->_new_method_hash( name => $name, type => 'modifier', modifier => $modifier );
216 $self->{methods}->{"$method_key"} = $method;
217  
218 $self->_recursive_parse( $block_type, $contents, $method );
219 }
220  
221 method _handle_apply_filter ($filter_expr) {
222 my $rest = substr( $self->{source}, pos( $self->{source} ) );
223 my $method = $self->_new_method_hash( type => 'apply_filter' );
224 local $self->{end_parse} = undef;
225 $self->_recursive_parse( 'filter', $rest, $method );
226 if ( my $incr = $self->{end_parse} ) {
227 pos( $self->{source} ) += $incr;
228 }
229 else {
230 $self->_throw_syntax_error("'{{' without matching '}}'");
231 }
232 my $code = sprintf(
233 "\$self->m->_apply_filters_to_output(%s, %s);\n",
234 $self->_processed_perl_code($filter_expr),
235 $self->_output_method($method)
236 );
237 $self->_add_to_current_method($code);
238 }
239  
240 method _handle_args_block ($contents) {
241 $self->_handle_attributes_list( $contents, 'args' );
242 }
243  
244 method _handle_attributes_list ($contents, $attr_type) {
245 my @lines = split( "\n", $contents );
246 my @attributes;
247 my $line_number = $self->{line_number} - 1;
248 foreach my $line (@lines) {
249 $line_number++;
250 trim($line);
251 next if $line =~ /^\#/ || $line !~ /\S/;
252 if (
253 my ( $name, $rest ) = (
254 $line =~ /
255 ^
256 \s* # optional whitespace
257 (?: \$\.)? # optional $. prefix
258 ([^\W\d]\w*) # valid Perl variable name
259 (?:\s*=>\s*(.*))? # optional arrow then default or attribute params
260 /x
261 )
262 )
263 {
264 my ($params);
265 if ( defined($rest) && length($rest) ) {
266 if ( $rest =~ /^\s*\(/ ) {
267 $params = "$rest\n;";
268 }
269 else {
270 $params = sprintf( "(default => %s\n);", $rest );
271 }
272 }
273 else {
274 $params = '();';
275 }
276 if ( $attr_type eq 'shared' ) {
277 $params = '(' . 'init_arg => undef, ' . substr( $params, 1 );
278 }
279 push( @attributes, $self->_attribute_declaration( $name, $params, $line_number ) );
280 }
281 else {
282 $self->{line_number} = $line_number;
283 $self->_throw_syntax_error("Invalid attribute line '$line'");
284 }
285 }
286 $self->{blocks}->{attributes} .= join( "\n", @attributes ) . "\n";
287 }
288  
289 method _handle_class_block ($contents) {
290 $self->{blocks}->{class} .=
291 $self->_output_line_number_comment . $self->_processed_perl_code($contents);
292 }
293  
294 method _handle_component_call ($contents) {
295 my ( $prespace, $call, $postspace ) = ( $contents =~ /(\s*)(.*)(\s*)/s );
296 if ( $call =~ m,^[\w/.], ) {
297 my $comma = index( $call, ',' );
298 $comma = length $call if $comma == -1;
299 ( my $comp = substr( $call, 0, $comma ) ) =~ s/\s+$//;
300 $call = "'$comp'" . substr( $call, $comma );
301 }
302 $call = $self->_processed_perl_code($call);
303 my $code = "\$m->comp( $prespace $call $postspace \n); ";
304  
305 $self->_add_to_current_method($code);
306 }
307  
308 method _handle_doc_block () {
309  
310 # Don't do anything - just discard the comment.
311 }
312  
313 method _handle_filter_block ($contents, $name, $arglist) {
314 my $new_contents = join( '',
315 '<%perl>',
316 'return Mason::DynamicFilter->new(',
317 'filter => sub {',
318 'my $yield = shift;',
319 '$m->capture(sub {',
320 '</%perl>', $contents, '<%perl>}); });</%perl>',
321 );
322 $self->_handle_method_block( $new_contents, $name, $arglist );
323 }
324  
325 method _handle_flags_block ($contents) {
326 my $ending = qr, (?: \n | # newline or
327 (?= </%flags> ) ) # end of block (don't consume it)
328 ,ix;
329  
330 while (
331 $contents =~ /
332 \G
333 [ \t]*
334 ([\w_]+) # identifier
335 [ \t]*=>[ \t]* # separator
336 (\S[^\n]*?) # value ( must start with a non-space char)
337 $ending
338 |
339 \G\n # a plain empty line
340 |
341 \G
342 [ \t]* # an optional comment
343 \#
344 [^\n]*
345 $ending
346 |
347 \G[ \t]+?
348 $ending
349 /xgc
350 )
351 {
352 my ( $flag, $value ) = ( $1, $2 );
353 if ( defined $flag && defined $value && length $flag && length $value ) {
354 if ( $self->valid_flags_hash->{$flag} ) {
355 $self->{blocks}->{flags}->{$flag} = eval($value);
356 die $@ if $@;
357 }
358 else {
359 $self->_throw_syntax_error("Invalid flag '$flag'");
360 }
361 }
362 }
363 }
364  
365 method _handle_init_block ($contents) {
366 $self->{current_method}->{init} =
367 $self->_output_line_number_comment . $self->_processed_perl_code($contents);
368 }
369  
370 method _handle_method_block ($contents, $name, $arglist) {
371 $self->_throw_syntax_error("Invalid method name '$name'")
372 if $name !~ /^$identifier$/;
373  
374 $self->_throw_syntax_error("'$name' is reserved and cannot be used as a method name")
375 if $self->bad_method_hash->{$name};
376  
377 $self->_throw_syntax_error("Duplicate definition of method '$name'")
378 if exists $self->{methods}->{$name};
379  
380 $self->_assert_not_nested('method');
381  
382 my $method = $self->_new_method_hash( name => $name, arglist => $arglist );
383 $self->{methods}->{$name} = $method;
384  
385 $self->_recursive_parse( 'method', $contents, $method );
386 }
387  
388 method _handle_perl_block ($contents) {
389 $self->_add_to_current_method( $self->_processed_perl_code($contents) );
390 }
391  
392 method _handle_perl_line ($type, $contents) {
393 my $code = $self->_processed_perl_code( $contents . "\n" );
394  
395 if ( $type eq 'perl' ) {
396 $self->_add_to_current_method($code);
397 }
398 else {
399 $self->_add_to_class_block($code);
400 }
401 }
402  
403 method _handle_plain_text ($text) {
404  
405 # Escape single quotes and backslashes
406 #
407 $text =~ s,([\'\\]),\\$1,g;
408  
409 my $code = "\$\$_m_buffer .= '$text';\n";
410 $self->_add_to_current_method($code);
411 }
412  
413 method _handle_shared_block ($contents) {
414 $self->_handle_attributes_list( $contents, 'shared' );
415 }
416  
417 method _handle_substitution ($text, $filter_list) {
418  
419 # This is a comment tag if all lines of text contain only whitespace
420 # or start with whitespace and a comment marker, e.g.
421 #
422 # <%
423 # #
424 # # foo
425 # %>
426 #
427 my @lines = split( /\n/, $text );
428 unless ( grep { /^\s*[^\s\#]/ } @lines ) {
429 return;
430 }
431  
432 $text = $self->_processed_perl_code($text);
433  
434 if ($filter_list) {
435 if ( my @filters = grep { /\S/ } split( /\s*,\s*/, $filter_list ) ) {
436 my $filter_call_list = join( ", ", map { "\$self->$_()" } @filters );
437 $text =
438 sprintf( '$self->m->_apply_filters(%s, sub { local $_ = %s; defined($_) ? $_ : "" })',
439 $filter_call_list, $text );
440 }
441 }
442  
443 my $code = "for (scalar($text)) { \$\$_m_buffer .= \$_ if defined }\n";
444  
445 $self->_add_to_current_method($code);
446 }
447  
448 method _handle_text_block ($contents) {
449 $contents =~ s/^\n//;
450 $contents =~ s,([\'\\]),\\$1,g;
451  
452 $self->_add_to_current_method("\$\$_m_buffer .= '$contents';\n");
453 }
454  
455 method _match_apply_filter () {
456 my $pos = pos( $self->{source} );
457  
458 # Match % ... {{ at beginning of line
459 if ( $self->{source} =~ / \G (?<=^) % ([^\n]*) \{\{ [^\S\n]* (?:\#.*)? \n /gcmx ) {
460 my ($filter_expr) = ($1);
461 $self->_handle_apply_filter($filter_expr);
462 return 1;
463 }
464  
465 # Old syntax, for backward compatibility
466 # Match <% ... { %>
467 if ( $self->{source} =~ /\G(\n)? <% (.+?) (\s*\{\s*) %>(\n)?/xcgs ) {
468 my ( $preceding_newline, $filter_expr, $opening_brace, $following_newline ) =
469 ( $1, $2, $3, $4 );
470  
471 # and make sure we didn't go through a %>
472 if ( $filter_expr !~ /%>/ ) {
473 for ( $preceding_newline, $filter_expr, $following_newline ) {
474 $self->{line_number} += tr/\n// if defined($_);
475 }
476 $self->_handle_apply_filter($filter_expr);
477  
478 return 1;
479 }
480 else {
481 pos( $self->{source} ) = $pos;
482 }
483 }
484  
485 return 0;
486 }
487  
488 method _match_apply_filter_end () {
489 if ( $self->{source} =~ / \G (?<=^) % [ \t]+ \}\} [^\S\n]* (?:\#.*)? (?:\n\n?|\z) /gmcx ) {
490 if ( $self->{current_method}->{type} eq 'apply_filter' ) {
491 $self->{end_parse} = pos( $self->{source} );
492 return 1;
493 }
494 else {
495 $self->_throw_syntax_error("'}}' without matching '{{'");
496 }
497 }
498  
499 # Old syntax - <% } %> and </%> - for backward compatibility
500 if ( $self->{current_method}->{type} eq 'apply_filter'
501 && $self->{source} =~ /\G (?: (?: <% [ \t]* \} [ \t]* %> ) | (?: <\/%> ) ) (\n?\n?)/gcx )
502 {
503 $self->{end_parse} = pos( $self->{source} );
504 return 1;
505 }
506  
507 return 0;
508 }
509  
510 method _match_block ($block_regex, $named) {
511 my $regex = qr/
512 \G(\n?)
513 <% ($block_regex)
514 (?: \s+ ([^\s\(>]+) ([^>]*) )?
515 >
516 /x;
517 if ( $self->{source} =~ /$regex/gcs ) {
518 my ( $preceding_newline, $block_type, $name, $arglist ) = ( $1, $2, $3, $4 );
519  
520 $self->_throw_syntax_error("<%$block_type> block requires a name")
521 if ( $named && !defined($name) );
522  
523 $self->_throw_syntax_error("<%$block_type> block does not take a name")
524 if ( !$named && defined($name) );
525  
526 my $block_method = "_handle_${block_type}_block";
527  
528 $self->{line_number}++ if $preceding_newline;
529  
530 my ( $block_contents, $nl ) = $self->_match_block_end($block_type);
531  
532 $self->$block_method( $block_contents, $name, $arglist );
533  
534 $self->{line_number} += $block_contents =~ tr/\n//;
535 $self->{line_number} += length($nl) if $nl;
536  
537 return 1;
538 }
539 return 0;
540 }
541  
542 method _match_block_end ($block_type) {
543 my $re = qr,\G(.*?)</%\Q$block_type\E>(\n?\n?),is;
544 if ( $self->{source} =~ /$re/gc ) {
545 return ( $1, $2 );
546 }
547 else {
548 $self->_throw_syntax_error("<%$block_type> without matching </%$block_type>");
549 }
550 }
551  
552 method _match_component_call () {
553 if ( $self->{source} =~ /\G<&(?!\|)/gcs ) {
554 if ( $self->{source} =~ /\G(.*?)&>/gcs ) {
555 my $body = $1;
556 $self->_handle_component_call($body);
557 $self->{line_number} += $body =~ tr/\n//;
558  
559 return 1;
560 }
561 else {
562 $self->_throw_syntax_error("'<&' without matching '&>'");
563 }
564 }
565 }
566  
567 method _match_end () {
568 if ( $self->{source} =~ /(\G\z)/gcs ) {
569 $self->{line_number} += $1 =~ tr/\n//;
570 return defined $1 && length $1 ? $1 : 1;
571 }
572 return 0;
573 }
574  
575 method _match_named_block () {
576 $self->_match_block( $self->named_block_regex, 1 );
577 }
578  
579 method _match_perl_line () {
580 if ( $self->{source} =~ /\G(?<=^)(%%?)([^\n]*)(?:\n|\z)/gcm ) {
581 my ( $percents, $line ) = ( $1, $2 );
582 if ( length($line) && $line !~ /^\s/ ) {
583 $self->_throw_syntax_error("$percents must be followed by whitespace or EOL");
584 }
585 if ( $percents eq '%%' ) {
586 if ( $line =~ /\{\s*$/ && $self->{source} =~ /\G(?!%%)/gcm ) {
587 $self->_throw_syntax_error("%%-lines cannot be used to surround content");
588 }
589 }
590 $self->_handle_perl_line( ( $percents eq '%' ? 'perl' : 'class' ), $line );
591 $self->{line_number}++;
592  
593 return 1;
594 }
595 return 0;
596 }
597  
598 method _match_plain_text () {
599  
600 # Most of these terminator patterns actually belong to the next
601 # lexeme in the source, so we use a lookahead if we don't want to
602 # consume them. We use a lookbehind when we want to consume
603 # something in the matched text, like the newline before a '%'.
604  
605 if (
606 $self->{source} =~ m{
607 \G
608 (.*?) # anything, followed by:
609 (
610 (?<=\n)(?=%) # an eval line - consume the \n
611 |
612 (?=<%\s) # a substitution tag
613 |
614 (?=[%&]>) # an end substitution or component call
615 |
616 (?=</?[%&]) # a block or call start or end
617 # - don't consume
618 |
619 \\\n # an escaped newline - throw away
620 |
621 \z # end of string
622 )
623 }xcgs
624 )
625 {
626 my ( $orig_text, $swallowed ) = ( $1, $2 );
627 my $text = $orig_text;
628  
629 # Chomp newline before block start
630 #
631 if ( substr( $self->{source}, pos( $self->{source} ), 3 ) =~ /<%[a-z]/ ) {
632 chomp($text);
633 }
634 $self->_handle_plain_text($text) if length $text;
635  
636 # Not checking definedness seems to cause extra lines to be
637 # counted with Perl 5.00503. I'm not sure why - dave
638 $self->{line_number} += tr/\n// foreach grep defined, ( $orig_text, $swallowed );
639  
640 return 1;
641 }
642  
643 return 0;
644 }
645  
646 method _match_substitution () {
647  
648 return 0 unless $self->{source} =~ /\G<%/gcs;
649  
650 if (
651 $self->{source} =~ m{
652 \G
653 (\s*) # Initial whitespace
654 (.*?) # Substitution body ($1)
655 (
656 \s*
657 (?<!\|) # Not preceded by a '|'
658 \| # A '|'
659 \s*
660 ( # (Start $3)
661 $identifier # A filter name
662 (?:\s*,\s*$identifier)* # More filter names, with comma separators
663 )
664 )?
665 (\s*) # Final whitespace
666 %> # Closing tag
667 }xcigs
668 )
669 {
670 my ( $start_ws, $body, $after_body, $filters, $end_ws ) = ( $1, $2, $3, $4, $5 );
671 $self->_throw_syntax_error("found empty '<% %>' tag") unless $body =~ /\S/;
672 $self->_throw_syntax_error("whitespace required after '<%'") unless length($start_ws);
673 $self->{line_number} += tr/\n//
674 foreach grep defined, ( $start_ws, $body, $after_body, $end_ws );
675 $self->_throw_syntax_error("whitespace required before '%>'") unless length($end_ws);
676  
677 $self->_handle_substitution( $body, $filters );
678  
679 return 1;
680 }
681 else {
682 $self->_throw_syntax_error("'<%' without matching '%>'");
683 }
684 }
685  
686 method _match_unknown_block () {
687 if ( $self->{source} =~ /\G(?:\n?)<%([A-Za-z_]+)>/gc ) {
688 $self->_throw_syntax_error("unknown block '<%$1>'");
689 }
690 }
691  
692 method _match_unnamed_block () {
693 $self->_match_block( $self->unnamed_block_regex, 0 );
694 }
695  
696 method _match_bad_close_tag () {
697 if ( my ($end_tag) = ( $self->{source} =~ /\G\s*(%>|&>)/gc ) ) {
698 ( my $begin_tag = reverse($end_tag) ) =~ s/>/</;
699 $self->_throw_syntax_error("'$end_tag' without matching '$begin_tag'");
700 }
701 }
702  
703 method _new_method_hash () {
704 return { body => '', init => '', type => 'method', @_ };
705 }
706  
707 method _output_attributes () {
708 return $self->{blocks}->{attributes} || '';
709 }
710  
711 method _output_class_block () {
712 return $self->{blocks}->{class} || '';
713 }
714  
715 method _output_class_initialization () {
716 return join(
717 "\n",
718 "our (\$_class_cmeta, \$m, \$_m_buffer, \$_interp);",
719 "BEGIN { ",
720 "local \$_interp = Mason::Interp->current_load_interp;",
721 "\$_interp->component_moose_class->import;",
722 "\$_interp->component_import_class->import;",
723 "}",
724 "*m = \\\$Mason::Request::current_request;",
725 "*_m_buffer = \\\$Mason::Request::current_buffer;",
726  
727 # Must be defined here since inner relies on caller()
728 "sub _inner { inner() }"
729 );
730 }
731  
732 method _output_cmeta () {
733 my $q = sub { "'$_[0]'" };
734 my %cmeta_info = (
735 dir_path => $q->( $self->dir_path ),
736 is_top_level => $q->( $self->interp->is_top_level_comp_path( $self->path ) ),
737 path => $q->( $self->path ),
738 source_file => $q->( $self->source_file ),
739 object_file => '__FILE__',
740 class => 'CLASS',
741 interp => '$interp',
742 );
743 return join(
744 "\n",
745 "method _set_class_cmeta (\$interp) {",
746 "\$_class_cmeta = \$interp->component_class_meta_class->new(",
747 (
748 map { sprintf( "'%s' => %s,", $_, $cmeta_info{$_} ) }
749 sort( keys(%cmeta_info) )
750 ),
751 ');', '}',
752 'sub _unset_class_cmeta { undef $_class_cmeta }',
753 'sub _class_cmeta { $_class_cmeta }'
754 );
755 }
756  
757 method _output_compiled_component () {
758 return join(
759 "\n",
760 map { trim($_) } grep { defined($_) && length($_) } (
761 $self->_output_flag_comment, $self->_output_class_initialization,
762 $self->output_class_header, $self->_output_global_declarations,
763 $self->_output_cmeta, $self->_output_attributes,
764 $self->_output_class_block, $self->_output_methods,
765 $self->output_class_footer,
766 )
767 ) . "\n";
768 }
769  
770 method _output_flag_comment () {
771 if ( my $flags = $self->{blocks}->{flags} ) {
772 if (%$flags) {
773 ( my $json = json_encode($flags) ) =~ s/\n//g;
774 return "# FLAGS: $json\n\n";
775 }
776 }
777 }
778  
779 method _output_global_declaration ($spec) {
780 my ( $sigil, $name ) = $self->interp->_parse_global_spec($spec);
781 return sprintf( 'our %s%s; *%s = \%s%s::%s;' . "\n",
782 $sigil, $name, $name, $sigil, $self->interp->globals_package, $name );
783 }
784  
785 method _output_global_declarations () {
786 return
787 join( "\n", map { $self->_output_global_declaration($_) } @{ $self->interp->allow_globals } );
788 }
789  
790 method _output_line_number_comment ($line_number) {
791 if ( !$self->interp->no_source_line_numbers ) {
792 $line_number ||= $self->{line_number};
793 if ($line_number) {
794 my $comment = sprintf( qq{#line %s "%s"\n}, $line_number, $self->source_file );
795 return $comment;
796 }
797 }
798 return "";
799 }
800  
801 method _output_method ($method) {
802 my $path = $self->path;
803  
804 my $name = $method->{name};
805 my $type = $method->{type};
806 my $modifier = $method->{modifier} || '';
807 my $arglist = $method->{arglist} || '';
808 my $contents = join( "\n", grep { /\S/ } ( $method->{init}, $method->{body} ) );
809  
810 my $start =
811 $type eq 'apply_filter' ? "sub {"
812 : $modifier eq 'around' ? "around '$name' => sub {\nmy \$orig = shift; my \$self = shift;"
813 : $type eq 'modifier' ? "$modifier '$name' => sub {\nmy \$self = shift;"
814 : "method $name $arglist {";
815 my $end = $modifier ? "};" : "}";
816  
817 return join(
818 "\n",
819 $start,
820  
821 # do not add a block around this, it introduces
822 # a separate scope and might break cleanup
823 # blocks (or all sort of other things!)
824 $contents,
825  
826 # don't return values explicitly. semi before return will help catch
827 # syntax errors in component body.
828 ";return;",
829 $end,
830 );
831 }
832  
833 method _output_methods () {
834  
835 # Sort methods so that modifiers come after
836 #
837 my @sorted_methods_keys =
838 sort { ( index( $a, ' ' ) <=> index( $b, ' ' ) ) || $a cmp $b } keys( %{ $self->{methods} } );
839 return
840 join( "\n", map { $self->_output_method( $self->{methods}->{$_} ) } @sorted_methods_keys );
841 }
842  
843 method _processed_perl_code ($code) {
844 my $coderef = \$code;
845 $self->process_perl_code($coderef);
846 return $$coderef;
847 }
848  
849 method _recursive_parse ($block_type, $contents, $method) {
850  
851 # Save current regex position, then locally set source to the contents and
852 # recursively parse.
853 #
854 local $self->{in_recursive_parse} = $block_type;
855  
856 my $save_pos = pos( $self->{source} );
857 scope_guard { pos( $self->{source} ) = $save_pos };
858 {
859 local $self->{source} = $contents;
860 local $self->{current_method} = $method;
861 local $self->{line_number} = $self->{line_number};
862 $self->parse();
863 }
864 }
865  
866 method _throw_syntax_error ($msg) {
867 die sprintf( "%s at %s line %d\n", $msg, $self->source_file, $self->{line_number} );
868 }
869  
870 __PACKAGE__->meta->make_immutable();
871  
872 1;
873  
874 __END__
875  
876 =pod
877  
878 =head1 NAME
879  
880 Mason::Compilation - Performs compilation of a single component
881  
882 =head1 DESCRIPTION
883  
884 A new C<Mason::Compilation> object is created by L<Mason::Interp> to compile
885 each component.
886  
887 This class has no public API at this time.
888  
889 =head1 MODIFIABLE METHODS
890  
891 These methods are not intended to be called externally, but may be useful to
892 modify with method modifiers in L<plugins|Mason::Manual::Plugins> and
893 L<subclasses|Mason::Manual::Subclasses>. Their APIs will be kept as stable as
894 possible.
895  
896 =over
897  
898 =item bad_attribute_names ()
899  
900 A list of attribute names that should not be used because they are reserved for
901 built-in attributes or methods: C<args>, C<m>, C<cmeta>, C<render>, C<main>,
902 etc.
903  
904 =item bad_method_names ()
905  
906 A list of method names that should not be used because they are reserved for
907 built-in attributes: C<args>, C<m>, C<cmeta>, etc. Not as extensive as
908 bad_attribute_names above because methods like C<render> and C<main> can be
909 overridden but make no sense as attributes.
910  
911 =item compile ()
912  
913 The top-level method called to compile the component. Returns the generated
914 component class.
915  
916 =item named_block_types ()
917  
918 An arrayref of valid named block types: C<after>, C<filter>, C<method>, etc.
919 Add to this list if you want to create your own named blocks (i.e. blocks that
920 take a name argument).
921  
922 =item output_class_footer ()
923  
924 Perl code to be added at the bottom of the class. Empty by default.
925  
926 =item output_class_header ()
927  
928 Perl code to be added at the top of the class, just after initialization of
929 Moose, C<$m> and other required pieces. By default it consults the
930 L<class_header parameter|Mason::Interp/class_header>.
931  
932 # Add to the top of every component class:
933 # use Modern::Perl;
934 # use JSON::XS qw(encode_json decode_json);
935 #
936 override 'output_class_header' => sub {
937 return join( "\n",
938 super(),
939 'use Modern::Perl;',
940 'use JSON::XS qw(encode_json decode_json);' );
941 };
942  
943 =item process_perl_code ($coderef)
944  
945 This method is called on each distinct piece of Perl code in the component.
946 I<$coderef> is a reference to a string containing the code; the method can
947 modify the code as desired. See L<Mason::Plugin::DollarDot> for a sample usage.
948  
949 =item unnamed_block_types ()
950  
951 An arrayref of valid unnamed block types: C<args>, C<class>, C<init>, etc. Add
952 to this list if you want to create your own unnamed blocks.
953  
954 =item valid_flags ()
955  
956 An arrayref of valid flags: contains only C<extends> at time of writing. Add to
957 this list if you want to create your own flags.
958  
959 =back
960  
961 =head1 SEE ALSO
962  
963 L<Mason|Mason>
964  
965 =head1 AUTHOR
966  
967 Jonathan Swartz <swartz@pobox.com>
968  
969 =head1 COPYRIGHT AND LICENSE
970  
971 This software is copyright (c) 2012 by Jonathan Swartz.
972  
973 This is free software; you can redistribute it and/or modify it under
974 the same terms as the Perl 5 programming language system itself.
975  
976 =cut