6 use VerboseWarnings qw( pedantic_p error_normal warn_normal warn_pedantic );
9 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
11 ###############################################################################
15 TmplTokenizer.pm - Simple-minded tokenizer class for HTML::Template .tmpl files
19 Because .tmpl files contains HTML::Template directives
20 that tend to confuse real parsers (e.g., HTML::Parse),
21 it might be better to create a customized scanner
22 to scan the template files for tokens.
23 This module is a simple-minded attempt at such a scanner.
27 ###############################################################################
34 use vars qw( $pedantic_attribute_error_in_nonpedantic_mode_p );
35 use vars qw( $pedantic_tmpl_var_use_in_nonpedantic_mode_p );
37 ###############################################################################
40 use vars qw( $re_directive $re_tmpl_var $re_tmpl_var_escaped $re_tmpl_include );
41 use vars qw( $re_directive_control $re_tmpl_endif_endloop );
43 # $re_directive must not do any backreferences
44 $re_directive = q{<(?:(?i)(?:!--\s*)?\/?TMPL_(?:VAR|LOOP|INCLUDE|IF|ELSE|UNLESS)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
45 # TMPL_VAR or TMPL_INCLUDE
46 $re_tmpl_var = q{<(?:(?i)(?:!--\s*)?TMPL_(?:VAR)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
47 $re_tmpl_include = q{<(?:(?i)(?:!--\s*)?TMPL_(?:INCLUDE)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
48 # TMPL_VAR ESCAPE=1/HTML/URL
49 $re_tmpl_var_escaped = q{<(?:(?i)(?:!--\s*)?TMPL_(?:VAR|INCLUDE)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))\s+ESCAPE=(?:1|HTML|URL)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
50 # Any control flow directive
51 $re_directive_control = q{<(?:(?i)(?:!--\s*)?\/?TMPL_(?:LOOP|IF|ELSE|UNLESS)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
52 # /LOOP or /IF or /UNLESS
53 $re_tmpl_endif_endloop = q{<(?:(?i)(?:!--\s*)?\/TMPL_(?:LOOP|IF|UNLESS)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
56 # Hideous stuff from subst.pl, slightly modified to use the above hideous stuff
57 # Note: The $re_tag's set $1 (<tag), $2 (>), and $3 (rest of string)
58 use vars qw( $re_comment $re_entity_name $re_end_entity $re_etag );
59 use vars qw( $re_tag_strict $re_tag_compat @re_tag );
62 my $etag = $compat? '>': '<>\/';
63 # This is no longer similar to the original regexp in subst.pl :-(
64 # Note that we don't want <> in compat mode; Mozilla knows about <
65 q{(<\/?(?:|(?:"(?:} . $re_directive . q{|[^"])*"|'(?:} . $re_directive . q{|[^'])*'|--(?:[^-]|-[^-])*--|(?:}
67 . q{|(?!--)[^"'<>} . $etag . q{]))+))([} . $etag . q{]|(?=<))(.*)};
70 $re_comment = '(?:--(?:[^-]|-[^-])*--)';
71 $re_entity_name = '(?:[^&%#;<>\s]+)'; # NOTE: not really correct SGML
72 $re_end_entity = '(?:;|$|(?=\s))'; # semicolon or before-whitespace
73 $re_etag = q{(?:<\/?(?:"[^"]*"|'[^']*'|[^"'>\/])*[>\/])}; # end-tag
74 @re_tag = ($re_tag_strict, $re_tag_compat) = (re_tag(0), re_tag(1));
77 # End of the hideous stuff
79 use vars qw( $serial );
81 ###############################################################################
83 sub FATAL_P () {'fatal-p'}
84 sub SYNTAXERROR_P () {'syntaxerror-p'}
86 sub FILENAME () {'input'}
87 sub HANDLE () {'handle'}
89 sub READAHEAD () {'readahead'}
90 sub LINENUM_START () {'lc_0'}
92 sub CDATA_MODE_P () {'cdata-mode-p'}
93 sub CDATA_CLOSE () {'cdata-close'}
95 sub ALLOW_CFORMAT_P () {'allow-cformat-p'}
100 my $class = ref($this) || $this;
104 my $handle = sprintf('TMPLTOKENIZER%d', $serial);
108 open($handle, "<$input") || die "$input: $!\n";
110 $self->{+FILENAME} = $input;
111 $self->{+HANDLE} = $handle;
112 $self->{+READAHEAD} = [];
116 ###############################################################################
122 return $this->{+FILENAME};
127 return $this->{+HANDLE};
132 return $this->{+FATAL_P};
137 return $this->{+SYNTAXERROR_P};
140 sub has_readahead_p {
142 return @{$this->{+READAHEAD}};
145 sub _peek_readahead {
147 return $this->{+READAHEAD}->[$#{$this->{+READAHEAD}}];
150 sub line_number_start {
152 return $this->{+LINENUM_START};
157 return $this->{+LINENUM};
162 return $this->{+CDATA_MODE_P};
167 return $this->{+CDATA_CLOSE};
170 sub allow_cformat_p {
172 return $this->{+ALLOW_CFORMAT_P};
179 $this->{+FATAL_P} = $_[0];
183 sub _set_syntaxerror {
185 $this->{+SYNTAXERROR_P} = $_[0];
189 sub _push_readahead {
191 push @{$this->{+READAHEAD}}, $_[0];
197 return pop @{$this->{+READAHEAD}};
200 sub _append_readahead {
202 $this->{+READAHEAD}->[$#{$this->{+READAHEAD}}] .= $_[0];
208 $this->{+READAHEAD}->[$#{$this->{+READAHEAD}}] = $_[0];
212 sub _increment_line_number {
214 $this->{+LINENUM} += 1;
218 sub _set_line_number_start {
220 $this->{+LINENUM_START} = $_[0];
224 sub _set_cdata_mode {
226 $this->{+CDATA_MODE_P} = $_[0];
230 sub _set_cdata_close {
232 $this->{+CDATA_CLOSE} = $_[0];
236 sub set_allow_cformat {
238 $this->{+ALLOW_CFORMAT_P} = $_[0];
242 ###############################################################################
244 sub _extract_attributes ($;$) {
248 $s = $1 if $s =~ /^<\S+(.*)\/\S$/s # XML-style self-closing tags
249 || $s =~ /^<\S+(.*)\S$/s; # SGML-style tags
251 for (my $i = 0; $s =~ /^(?:$re_directive_control)?\s+(?:$re_directive_control)?(?:([a-zA-Z][-a-zA-Z0-9]*)\s*=\s*)?('((?:$re_directive|[^'])*)'|"((?:$re_directive|[^"])*)"|((?:$re_directive|[^\s<>])+))/os;) {
252 my($key, $val, $val_orig, $rest)
253 = ($1, (defined $3? $3: defined $4? $4: $5), $2, $');
255 $attr{+lc($key)} = [$key, $val, $val_orig, $i];
257 if ($val =~ /$re_tmpl_include/os) {
258 warn_normal "TMPL_INCLUDE in attribute: $val_orig\n", $lc;
259 } elsif ($val =~ /$re_tmpl_var/os && $val !~ /$re_tmpl_var_escaped/os) {
260 # XXX: we probably should not warn if key is "onclick" etc
261 # XXX: there's just no reasonable thing to suggest
262 my $suggest = ($key =~ /^(?:action|archive|background|cite|classid|codebase|data|datasrc|for|href|longdesc|profile|src|usemap)$/i? 'URL': 'HTML');
263 undef $suggest if $key =~ /^(?:onblur|onchange|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onload|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onreset|onselect|onsubmit|onunload)$/i;
265 "Suggest ESCAPE=$suggest for TMPL_VAR in attribute \"$key\""
267 $lc, \$pedantic_tmpl_var_use_in_nonpedantic_mode_p
268 if defined $suggest && (pedantic_p || !$pedantic_tmpl_var_use_in_nonpedantic_mode_p);
269 } elsif ($val_orig !~ /^['"]/) {
270 my $t = $val; $t =~ s/$re_directive_control//os;
272 "Unquoted attribute contains character(s) that should be quoted"
274 $lc, \$pedantic_attribute_error_in_nonpedantic_mode_p
275 if $t =~ /[^-\.A-Za-z0-9]/s;
278 my $s2 = $s; $s2 =~ s/$re_tmpl_endif_endloop//g; # for the next check
279 if ($s2 =~ /\S/s) { # should never happen
280 if ($s =~ /^([^\n]*)\n/s) { # this is even worse
281 error_normal("Completely confused while extracting attributes: $1", $lc);
282 error_normal((scalar(split(/\n/, $s)) - 1) . " more line(s) not shown.", undef);
283 $this->_set_fatal( 1 );
285 warn_normal "Strange attribute syntax: $s\n", $lc;
291 sub _next_token_internal {
296 $this->_pop_readahead if $this->has_readahead_p
297 && !ref $this->_peek_readahead
298 && !length $this->_peek_readahead;
299 if (!$this->has_readahead_p) {
300 my $next = scalar <$h>;
301 $eof_p = !defined $next;
303 $this->_increment_line_number;
304 $this->_push_readahead( $next );
307 $this->_set_line_number_start( $this->line_number ); # remember 1st line num
308 if ($this->has_readahead_p && ref $this->_peek_readahead) { # TmplToken obj.
309 ($it, $kind) = ($this->_pop_readahead, undef);
310 } elsif ($eof_p && !$this->has_readahead_p) { # nothing left to do
312 } elsif ($this->_peek_readahead =~ /^\s+/s) { # whitespace
313 ($kind, $it) = (TmplTokenType::TEXT, $&);
314 $this->_set_readahead( $' );
315 # FIXME the following (the [<\s] part) is an unreliable HACK :-(
316 } elsif ($this->_peek_readahead =~ /^(?:[^<]|<[<\s])*(?:[^<\s])/s) { # non-space normal text
317 ($kind, $it) = (TmplTokenType::TEXT, $&);
318 $this->_set_readahead( $' );
319 warn_normal "Unescaped < in $it\n", $this->line_number_start
320 if !$this->cdata_mode_p && $it =~ /</s;
321 } else { # tag/declaration/processing instruction
323 for (my $cdata_close = $this->cdata_close;;) {
324 if ($this->cdata_mode_p) {
325 if ($this->_peek_readahead =~ /^$cdata_close/) {
326 ($kind, $it) = (TmplTokenType::TAG, $&);
327 $this->_set_readahead( $' );
330 ($kind, $it) = (TmplTokenType::TEXT, $this->_pop_readahead);
333 } elsif ($this->_peek_readahead =~ /^$re_tag_compat/os) {
334 # If we detect a "closed start tag" but we know that the
335 # following token looks like a TMPL_VAR, don't stop
336 my($head, $tail, $post) = ($1, $2, $3);
337 if ($tail eq '' && $post =~ $re_tmpl_var) {
338 warn_normal "Possible SGML \"closed start tag\" notation: $head<\n", $this->line_number;
340 ($kind, $it) = (TmplTokenType::TAG, "$head>");
341 $this->_set_readahead( $post );
343 warn_normal "SGML \"closed start tag\" notation: $head<\n", $this->line_number if $tail eq '';
345 } elsif ($this->_peek_readahead =~ /^<!--(?:(?!-->).)*-->/s) {
346 ($kind, $it) = (TmplTokenType::COMMENT, $&);
347 $this->_set_readahead( $' );
349 warn_normal "Syntax error in comment: $&\n", $this->line_number_start;
350 $this->_set_syntaxerror( 1 );
353 my $next = scalar <$h>;
354 $eof_p = !defined $next;
356 $this->_increment_line_number;
357 $this->_append_readahead( $next );
359 if ($kind ne TmplTokenType::TAG) {
361 } elsif ($it =~ /^<!/) {
362 $kind = TmplTokenType::DECL;
363 $kind = TmplTokenType::COMMENT if $it =~ /^<!--(?:(?!-->).)*-->/;
364 if ($kind == TmplTokenType::COMMENT && $it =~ /^<!--\s*#include/s) {
365 warn_normal "Apache #include directive found instead of HTML::Template <TMPL_INCLUDE> directive", $this->line_number_start;
367 } elsif ($it =~ /^<\?/) {
368 $kind = TmplTokenType::PI;
370 if ($it =~ /^$re_directive/ios && !$this->cdata_mode_p) {
371 $kind = TmplTokenType::DIRECTIVE;
373 if (!$ok_p && $eof_p) {
374 ($kind, $it) = (TmplTokenType::UNKNOWN, $this->_peek_readahead);
375 $this->_set_readahead, undef;
376 $this->_set_syntaxerror( 1 );
379 warn_normal "Unrecognizable token found: $it\n", $this->line_number_start
380 if $kind == TmplTokenType::UNKNOWN;
381 return defined $it? (ref $it? $it: TmplToken->new($it, $kind, $this->line_number, $this->filename)): undef;
384 sub _next_token_intermediate {
386 my $h = $this->_handle;
388 if (!$this->cdata_mode_p) {
389 $it = $this->_next_token_internal($h);
390 if (defined $it && $it->type == TmplTokenType::TAG) {
391 if ($it->string =~ /^<(script|style|textarea)\b/i) {
392 $this->_set_cdata_mode( 1 );
393 $this->_set_cdata_close( "</$1\\s*>" );
395 $it->set_attributes( $this->_extract_attributes($it->string, $it->line_number) );
398 for ($it = '', my $cdata_close = $this->cdata_close;;) {
399 my $next = $this->_next_token_internal($h);
400 last if !defined $next;
401 if (defined $next && $next->string =~ /$cdata_close/i) {
402 $this->_push_readahead( $next ); # push entire TmplToken object
403 $this->_set_cdata_mode( 0 );
405 last unless $this->cdata_mode_p;
406 $it .= $next->string;
408 $it = TmplToken->new( $it, TmplTokenType::CDATA, $this->line_number );
409 $this->_set_cdata_close, undef;
414 sub _token_groupable_p ($) { # groupable into a TEXT_PARAMETRIZED token
416 return $t->type == TmplTokenType::TEXT
417 || ($t->type == TmplTokenType::DIRECTIVE
418 && $t->string =~ /^(?:$re_tmpl_var)$/os)
419 || ($t->type == TmplTokenType::TAG
420 && ($t->string =~ /^<\/?(?:b|em|h[123456]|i|u)\b/is
421 || ($t->string =~ /^<input/i
422 && $t->attributes->{'type'} =~ /^(?:text)$/i)))
425 sub _quote_cformat ($) {
433 return $t->type == TmplTokenType::DIRECTIVE? '%s': _quote_cformat($t->string);
438 my $h = $this->_handle;
440 $this->{_queue} = [] unless defined $this->{_queue};
441 if (@{$this->{_queue}}) {
442 $it = pop @{$this->{_queue}};
444 $it = $this->_next_token_intermediate($h);
445 if ($this->allow_cformat_p && defined $it
446 && ($it->type == TmplTokenType::TEXT?
447 !blank_p( $it->string ): _token_groupable_p( $it ))) {
448 my @structure = ( $it );
449 my($n_trailing_spaces, $next) = (0, undef);
450 my($nonblank_text_p, $parametrized_p, $next) = (0, 0);
451 if ($it->type == TmplTokenType::TEXT) {
452 $nonblank_text_p = 1 if !blank_p( $it->string );
453 } elsif ($it->type == TmplTokenType::DIRECTIVE) {
456 for (my $i = 1, $n_trailing_spaces = 0;; $i += 1) {
457 $next = $this->_next_token_intermediate($h);
458 push @structure, $next; # for consistency (with initialization)
459 last unless defined $next && _token_groupable_p( $next );
460 if ($next->type == TmplTokenType::TEXT) {
461 if (blank_p( $next->string )) {
462 $n_trailing_spaces += 1;
464 ($n_trailing_spaces, $nonblank_text_p) = (0, 1);
466 } elsif ($next->type == TmplTokenType::DIRECTIVE) {
467 $n_trailing_spaces = 0;
470 $n_trailing_spaces = 0;
473 # Undo the last token
474 push @{$this->{_queue}}, pop @structure;
475 # Undo trailing blank tokens
476 for (my $i = 0; $i < $n_trailing_spaces; $i += 1) {
477 push @{$this->{_queue}}, pop @structure;
479 if (@structure < 2) {
482 } elsif ($nonblank_text_p && $parametrized_p) {
483 # Create the corresponding c-format string
484 my $string = join('', map { $_->string } @structure);
485 my $form = join('', map { _formalize $_ } @structure);
486 $it = TmplToken->new($string, TmplTokenType::TEXT_PARAMETRIZED, $it->line_number, $it->pathname);
487 $it->set_form( $form );
488 $it->set_children( @structure );
489 # } elsif ($nonblank_text_p) {
490 # # Combine the strings
491 # my $string = join('', map { $_->string } @structure);
494 # Requeue the tokens thus seen for re-emitting
496 push @{$this->{_queue}}, pop @structure;
499 $it = pop @{$this->{_queue}};
506 ###############################################################################
508 # Other simple functions (These are not methods)
512 return $s =~ /^(?:\s|\ $re_end_entity|$re_tmpl_var)*$/os;
519 $s =~ s/^(\s|\ $re_end_entity)+//os; my $l1 = $l0 - length $s;
520 $s =~ s/(\s|\ $re_end_entity)+$//os; my $l2 = $l0 - $l1 - length $s;
521 return wantarray? (substr($s0, 0, $l1), $s, substr($s0, $l0 - $l2)): $s;
526 # Locale::PO->quote is buggy, it doesn't quote newlines :-/
527 $s =~ s/([\\"])/\\\1/gs;
532 # Complication function that shouldn't be here
533 sub parametrize ($@) {
534 my($fmt, @params) = @_;
536 for (my $n = 0; length $fmt;) {
537 if ($fmt =~ /^[^%]+/) {
540 } elsif ($fmt =~ /^%%/) {
543 } elsif ($fmt =~ /^%(?:(\d+)\$)?s/) {
545 my $i = (defined $1? $1: $n) - 1;
548 } elsif ($fmt =~ /^%[^%a-zA-Z]*[a-zA-Z]/) {
551 die "Unknown or unsupported format specification: $&\n"; #XXX
553 die "Completely confused parametrizing: $fmt\n";#XXX
559 ###############################################################################
563 In addition to the basic scanning, this class will also perform
570 Emulation of c-format strings (see below)
574 Display of warnings for certain things that affects either the
575 ability of this class to yield correct output, or things that
576 are known to cause the original template to cause trouble.
580 Automatic correction of some of the things warned about
581 (e.g., SGML "closed start tag" notation).
585 =head2 c-format strings emulation
587 Because English word order is not universal, a simple extraction
588 of translatable strings may yield some strings like "Accounts for"
589 or ambiguous strings like "in". This makes the resulting strings
590 difficult to translate, but does not affect all languages alike.
591 For example, Chinese (with a somewhat different word order) would
592 be hit harder, but French would be relatively unaffected.
594 To overcome this problem, the scanner can be configured to detect
595 patterns with <TMPL_VAR> directives (as well as certain HTML tags),
596 and try to construct a larger pattern that will appear in the PO
597 file as c-format strings with %s placeholders. This additional
598 step allows the translator to deal with cases where word order
599 is different (replacing %s with %1$s, %2$s, etc.), or when certain
600 words will require certain inflectional suffixes in sentences.
602 Because this is an incompatible change, this mode must be explicitly
603 turned on using the set_cformat(1) method call.
607 This tokenizer is mostly based
608 on Ambrose's hideous Perl script known as subst.pl.