4 #use warnings; FIXME - Bug 2505
7 use VerboseWarnings qw( pedantic_p error_normal warn_normal warn_pedantic );
10 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
12 ###############################################################################
16 TmplTokenizer.pm - Simple-minded tokenizer class for HTML::Template .tmpl files
20 Because .tmpl files contains HTML::Template directives
21 that tend to confuse real parsers (e.g., HTML::Parse),
22 it might be better to create a customized scanner
23 to scan the template files for tokens.
24 This module is a simple-minded attempt at such a scanner.
28 ###############################################################################
35 use vars qw( $pedantic_attribute_error_in_nonpedantic_mode_p );
36 use vars qw( $pedantic_tmpl_var_use_in_nonpedantic_mode_p );
37 use vars qw( $pedantic_error_markup_in_pcdata_p );
39 ###############################################################################
42 use vars qw( $re_directive $re_tmpl_var $re_tmpl_var_escaped $re_tmpl_include );
43 use vars qw( $re_directive_control $re_tmpl_endif_endloop $re_xsl);
45 # $re_directive must not do any backreferences
46 $re_directive = q{<(?:(?i)(?:!--\s*)?\/?TMPL_(?:VAR|LOOP|INCLUDE|IF|ELSE|UNLESS)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
47 # TMPL_VAR or TMPL_INCLUDE
48 $re_tmpl_var = q{<(?:(?i)(?:!--\s*)?TMPL_(?:VAR)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
49 $re_tmpl_include = q{<(?:(?i)(?:!--\s*)?TMPL_(?:INCLUDE)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
50 # TMPL_VAR ESCAPE=1/HTML/URL
51 $re_xsl = q{<\/?(?:xsl:)(?:[\s\-a-zA-Z0-9"'\/\.\[\]\@\(\):=,$]+)\/?>};
52 $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*(?:--)?)>};
53 # Any control flow directive
54 $re_directive_control = q{<(?:(?i)(?:!--\s*)?\/?TMPL_(?:LOOP|IF|ELSE|UNLESS)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
55 # /LOOP or /IF or /UNLESS
56 $re_tmpl_endif_endloop = q{<(?:(?i)(?:!--\s*)?\/TMPL_(?:LOOP|IF|UNLESS)(?:\s+(?:[a-zA-Z][-a-zA-Z0-9]*=)?(?:'[^']*'|"[^"]*"|[^\s<>]+))*\s*(?:--)?)>};
59 # Hideous stuff from subst.pl, slightly modified to use the above hideous stuff
60 # Note: The $re_tag's set $1 (<tag), $2 (>), and $3 (rest of string)
61 use vars qw( $re_comment $re_entity_name $re_end_entity $re_etag );
62 use vars qw( $re_tag_strict $re_tag_compat @re_tag );
65 my $etag = $compat? '>': '<>\/';
66 # This is no longer similar to the original regexp in subst.pl :-(
67 # Note that we don't want <> in compat mode; Mozilla knows about <
68 q{(<\/?(?:|(?:"(?:} . $re_directive . q{|[^"])*"|'(?:} . $re_directive . q{|[^'])*'|--(?:(?!--)(?:$re_directive)*.)*--|(?:}
70 . q{|(?!--)[^"'<>} . $etag . q{]))+))([} . $etag . q{]|(?=<))(.*)};
73 $re_comment = '(?:--(?:[^-]|-[^-])*--)';
74 $re_entity_name = '(?:[^&%#;<>\s]+)'; # NOTE: not really correct SGML
75 $re_end_entity = '(?:;|$|(?=\s))'; # semicolon or before-whitespace
76 $re_etag = q{(?:<\/?(?:"[^"]*"|'[^']*'|[^"'>\/])*[>\/])}; # end-tag
77 @re_tag = ($re_tag_strict, $re_tag_compat) = (re_tag(0), re_tag(1));
80 # End of the hideous stuff
82 use vars qw( $serial );
84 ###############################################################################
86 sub FATAL_P () {'fatal-p'}
87 sub SYNTAXERROR_P () {'syntaxerror-p'}
89 sub FILENAME () {'input'}
90 sub HANDLE () {'handle'}
92 sub READAHEAD () {'readahead'}
93 sub LINENUM_START () {'lc_0'}
95 sub CDATA_MODE_P () {'cdata-mode-p'}
96 sub CDATA_CLOSE () {'cdata-close'}
97 sub PCDATA_MODE_P () {'pcdata-mode-p'} # additional submode for CDATA
98 sub JS_MODE_P () {'js-mode-p'} # cdata-mode-p must also be true
100 sub ALLOW_CFORMAT_P () {'allow-cformat-p'}
105 open my $handle,$filename or die "can't open $filename";
107 filename => $filename
113 ###############################################################################
119 return $this->{filename};
124 return $this->{handle};
129 return $this->{+FATAL_P};
134 return $this->{+SYNTAXERROR_P};
137 sub has_readahead_p {
139 return @{$this->{readahead}};
142 sub _peek_readahead {
144 return $this->{readahead}->[$#{$this->{readahead}}];
147 sub line_number_start {
149 return $this->{+LINENUM_START};
154 return $this->{+LINENUM};
159 return $this->{+CDATA_MODE_P};
164 return $this->{+PCDATA_MODE_P};
169 return $this->{+JS_MODE_P};
174 return $this->{+CDATA_CLOSE};
177 sub allow_cformat_p {
179 return $this->{+ALLOW_CFORMAT_P};
186 $this->{+FATAL_P} = $_[0];
190 sub _set_syntaxerror {
192 $this->{+SYNTAXERROR_P} = $_[0];
196 sub _push_readahead {
198 push @{$this->{readahead}}, $_[0];
204 return pop @{$this->{readahead}};
207 sub _append_readahead {
209 $this->{readahead}->[$#{$this->{readahead}}] .= $_[0];
215 $this->{readahead}->[$#{$this->{readahead}}] = $_[0];
219 sub _increment_line_number {
221 $this->{+LINENUM} += 1;
225 sub _set_line_number_start {
227 $this->{+LINENUM_START} = $_[0];
231 sub _set_cdata_mode {
233 $this->{+CDATA_MODE_P} = $_[0];
237 sub _set_pcdata_mode {
239 $this->{+PCDATA_MODE_P} = $_[0];
245 $this->{+JS_MODE_P} = $_[0];
249 sub _set_cdata_close {
251 $this->{+CDATA_CLOSE} = $_[0];
255 sub set_allow_cformat {
257 $this->{+ALLOW_CFORMAT_P} = $_[0];
261 ###############################################################################
263 use vars qw( $js_EscapeSequence );
265 # Perl quoting is really screwed up, but this common subexp is way too long
266 $js_EscapeSequence = q{\\\\(?:['"\\\\bfnrt]|[^0-7xu]|[0-3]?[0-7]{1,2}|x[\da-fA-F]{2}|u[\da-fA-F]{4})};
268 sub parenleft () { '(' }
269 sub parenright () { ')' }
275 if ($s0 =~ /^\s+/s) { # whitespace
278 } elsif ($s0 =~ /^\/\/[^\r\n]*(?:[\r\n]|$)/s) { # C++-style comment
281 } elsif ($s0 =~ /^\/\*(?:(?!\*\/).)*\*\//s) { # C-style comment
284 # Keyword or identifier, ECMA-262 p.13 (section 7.5)
285 } elsif ($s0 =~ /^[A-Z_\$][A-Z\d_\$]*/is) { # IdentifierName
288 # Punctuator, ECMA-262 p.13 (section 7.6)
289 } elsif ($s0 =~ /^(?:[\(\){}\[\];]|>>>=|<<=|>>=|[-\+\*\/\&\|\^\%]=|>>>|<<|>>|--|\+\+|\|\||\&\&|==|<=|>=|!=|[=><,!~\?:\.\-\+\*\/\&\|\^\%])/s) {
292 # DecimalLiteral, ECMA-262 p.14 (section 7.7.3); note: bug in the spec
293 } elsif ($s0 =~ /^(?:0|[1-9]\d+(?:\.\d*(?:[eE][-\+]?\d+)?)?)/s) {
296 # HexIntegerLiteral, ECMA-262 p.15 (section 7.7.3)
297 } elsif ($s0 =~ /^0[xX][\da-fA-F]+/s) {
300 # OctalIntegerLiteral, ECMA-262 p.15 (section 7.7.3)
301 } elsif ($s0 =~ /^0[\da-fA-F]+/s) {
304 # StringLiteral, ECMA-262 p.17 (section 7.7.4)
305 # XXX SourceCharacter doesn't seem to be defined (?)
306 } elsif ($s0 =~ /^(?:"(?:(?!["\\\r\n]).|$js_EscapeSequence)*"|'(?:(?!['\\\r\n]).|$js_EscapeSequence)*')/os) {
309 } elsif ($s0 =~ /^./) { # UNKNOWN TOKEN !!!
317 sub STATE_UNDERSCORE () { 1 }
318 sub STATE_PARENLEFT () { 2 }
319 sub STATE_STRING_LITERAL () { 3 }
321 # XXX This is a crazy hack. I don't want to write an ECMAScript parser.
322 # XXX A scanner is one thing; a parser another thing.
323 sub identify_js_translatables (@) {
326 # We mark a JavaScript translatable string as in C, i.e., _("literal")
327 # For simplicity, we ONLY look for "_" "(" StringLiteral ")"
328 for (my $i = 0, my $state = 0, my($j, $q, $s); $i <= $#input; $i += 1) {
329 my $reset_state_p = 0;
330 push @output, [0, $input[$i]];
331 if ($input[$i] !~ /\S/s) {
333 } elsif ($state == 0) {
334 $state = STATE_UNDERSCORE if $input[$i] eq '_';
335 } elsif ($state == STATE_UNDERSCORE) {
336 $state = $input[$i] eq parenleft ? STATE_PARENLEFT : 0;
337 } elsif ($state == STATE_PARENLEFT) {
338 if ($input[$i] =~ /^(['"])(.*)\1$/s) {
339 ($state, $j, $q, $s) = (STATE_STRING_LITERAL, $#output, $1, $2);
343 } elsif ($state == STATE_STRING_LITERAL) {
344 if ($input[$i] eq parenright) {
345 $output[$j] = [1, $output[$j]->[1], $q, $s];
349 die "identify_js_translatables internal error: Unknown state $state"
355 ###############################################################################
357 sub _extract_attributes ($;$) {
361 $s = $1 if $s =~ /^<(?:(?!$re_directive_control)\S)+(.*)\/\S$/s # XML-style self-closing tags
362 || $s =~ /^<(?:(?!$re_directive_control)\S)+(.*)\S$/s; # SGML-style tags
364 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;) {
365 my($key, $val, $val_orig, $rest)
366 = ($1, (defined $3? $3: defined $4? $4: $5), $2, $');
368 $attr{+lc($key)} = [$key, $val, $val_orig, $i];
370 if ($val =~ /$re_tmpl_include/os) {
371 warn_normal "TMPL_INCLUDE in attribute: $val_orig\n", $lc;
372 } elsif ($val =~ /$re_tmpl_var/os && $val !~ /$re_tmpl_var_escaped/os) {
373 # XXX: we probably should not warn if key is "onclick" etc
374 # XXX: there's just no reasonable thing to suggest
375 my $suggest = ($key =~ /^(?:action|archive|background|cite|classid|codebase|data|datasrc|for|href|longdesc|profile|src|usemap)$/i? 'URL': 'HTML');
376 undef $suggest if $key =~ /^(?:onblur|onchange|onclick|ondblclick|onfocus|onkeydown|onkeypress|onkeyup|onload|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onreset|onselect|onsubmit|onunload)$/i;
378 "Suggest ESCAPE=$suggest for TMPL_VAR in attribute \"$key\""
380 $lc, \$pedantic_tmpl_var_use_in_nonpedantic_mode_p
381 if defined $suggest && (pedantic_p || !$pedantic_tmpl_var_use_in_nonpedantic_mode_p);
382 } elsif ($val_orig !~ /^['"]/) {
383 my $t = $val; $t =~ s/$re_directive_control//os;
385 "Unquoted attribute contains character(s) that should be quoted"
387 $lc, \$pedantic_attribute_error_in_nonpedantic_mode_p
388 if $t =~ /[^-\.A-Za-z0-9]/s;
391 my $s2 = $s; $s2 =~ s/$re_tmpl_endif_endloop//g; # for the next check
392 if ($s2 =~ /\S/s) { # should never happen
393 if ($s =~ /^([^\n]*)\n/s) { # this is even worse
394 error_normal("Completely confused while extracting attributes: $1", $lc);
395 error_normal((scalar(split(/\n/, $s)) - 1) . " more line(s) not shown.", undef);
396 $this->_set_fatal( 1 );
398 # There's something wrong with the attribute syntax.
399 # We might be able to deduce a likely cause by looking more.
400 if ($s =~ /^[a-z0-9]/is && "<foo $s>" =~ /^$re_tag_compat$/s) {
401 warn_normal "Probably missing whitespace before or missing quotation mark near: $s\n", $lc;
403 warn_normal "Strange attribute syntax: $s\n", $lc;
410 sub _next_token_internal {
415 $this->_pop_readahead if $this->has_readahead_p
416 && !ref $this->_peek_readahead
417 && !length $this->_peek_readahead;
418 if (!$this->has_readahead_p) {
419 my $next = scalar <$h>;
420 $eof_p = !defined $next;
422 $this->_increment_line_number;
423 $this->_push_readahead( $next );
426 $this->_set_line_number_start( $this->line_number ); # remember 1st line num
427 if ($this->has_readahead_p && ref $this->_peek_readahead) { # TmplToken obj.
428 ($it, $kind) = ($this->_pop_readahead, undef);
429 } elsif ($eof_p && !$this->has_readahead_p) { # nothing left to do
431 } elsif ($this->_peek_readahead =~ /^\s+/s) { # whitespace
432 ($kind, $it) = (TmplTokenType::TEXT, $&);
433 $this->_set_readahead( $' );
434 # FIXME the following (the [<\s] part) is an unreliable HACK :-(
435 } elsif ($this->_peek_readahead =~ /^(?:[^<]|<[<\s])*(?:[^<\s])/s) { # non-space normal text
436 ($kind, $it) = (TmplTokenType::TEXT, $&);
437 $this->_set_readahead( $' );
438 warn_normal "Unescaped < in $it\n", $this->line_number_start
439 if !$this->cdata_mode_p && $it =~ /</s;
440 } else { # tag/declaration/processing instruction
442 my $bad_comment_p = 0;
443 for (my $cdata_close = $this->cdata_close;;) {
444 if ($this->cdata_mode_p) {
445 my $next = $this->_pop_readahead;
446 if ($next =~ /^$cdata_close/is) {
447 ($kind, $it) = (TmplTokenType::TAG, $&);
448 $this->_push_readahead( $' );
450 } elsif ($next =~ /^((?:(?!$cdata_close).)+)($cdata_close)/is) {
451 ($kind, $it) = (TmplTokenType::TEXT, $1);
452 $this->_push_readahead( "$2$'" );
455 ($kind, $it) = (TmplTokenType::TEXT, $next);
458 } elsif ($this->_peek_readahead =~ /^$re_tag_compat/os) {
459 # If we detect a "closed start tag" but we know that the
460 # following token looks like a TMPL_VAR, don't stop
461 my($head, $tail, $post) = ($1, $2, $3);
462 if ($tail eq '' && $post =~ $re_tmpl_var) {
463 # Don't bother to show the warning if we're too confused
464 # FIXME. There's no method for _closed_start_tag_warning
465 if (!defined $this->{'_closed_start_tag_warning'}
466 || ($this->{'_closed_start_tag_warning'}->[0] eq $head
467 && $this->{'_closed_start_tag_warning'}->[1] != $this->line_number - 1)) {
468 warn_normal "Possible SGML \"closed start tag\" notation: $head<\n", $this->line_number
469 if split(/\n/, $head) < 10;
471 $this->{'_closed_start_tag_warning'} = [$head, $this->line_number];
473 ($kind, $it) = (TmplTokenType::TAG, "$head>");
474 $this->_set_readahead( $post );
476 warn_normal "SGML \"closed start tag\" notation: $head<\n", $this->line_number if $tail eq '';
478 } elsif ($this->_peek_readahead =~ /^<!--(?:(?!-->)$re_directive*.)*-->/os) {
479 ($kind, $it) = (TmplTokenType::COMMENT, $&);
480 $this->_set_readahead( $' );
485 my $next = scalar <$h>;
486 $eof_p = !defined $next;
488 $this->_increment_line_number;
489 $this->_append_readahead( $next );
491 if ($kind ne TmplTokenType::TAG) {
493 } elsif ($it =~ /^<!/) {
494 $kind = TmplTokenType::DECL;
495 $kind = TmplTokenType::COMMENT if $it =~ /^<!--(?:(?!-->).)*-->/;
496 if ($kind == TmplTokenType::COMMENT && $it =~ /^<!--\s*#include/s) {
497 warn_normal "Apache #include directive found instead of HTML::Template <TMPL_INCLUDE> directive", $this->line_number_start;
499 } elsif ($it =~ /^<\?/) {
500 $kind = TmplTokenType::PI;
502 if ($it =~ /^$re_directive/ios && !$this->cdata_mode_p) {
503 $kind = TmplTokenType::DIRECTIVE;
504 } elsif ($bad_comment_p) {
505 warn_normal sprintf("Syntax error in comment: %s\n", $it),
506 $this->line_number_start;
507 $this->_set_syntaxerror( 1 );
509 if (!$ok_p && $eof_p) {
510 ($kind, $it) = (TmplTokenType::UNKNOWN, $this->_peek_readahead);
511 $this->_set_readahead, undef;
512 $this->_set_syntaxerror( 1 );
515 warn_normal "Unrecognizable token found: "
516 . (split(/\n/, $it) < 10? $it: '(too confused to show details)')
517 . "\n", $this->line_number_start
518 if $kind == TmplTokenType::UNKNOWN;
519 return defined $it? (ref $it? $it: TmplToken->new($it, $kind, $this->line_number, $this->filename)): undef;
522 sub _next_token_intermediate {
524 my $h = $this->_handle;
526 if (!$this->cdata_mode_p) {
527 $it = $this->_next_token_internal($h);
528 if (defined $it && $it->type == TmplTokenType::TAG) {
529 if ($it->string =~ /^<(script|style|textarea)\b/is) {
530 $this->_set_cdata_mode( 1 );
531 $this->_set_cdata_close( "</$1\\s*>" );
532 $this->_set_pcdata_mode( 0 );
533 $this->_set_js_mode( lc($1) eq 'script' );
534 # } elsif ($it->string =~ /^<(title)\b/is) {
535 # $this->_set_cdata_mode( 1 );
536 # $this->_set_cdata_close( "</$1\\s*>" );
537 # $this->_set_pcdata_mode( 1 );
539 $it->set_attributes( $this->_extract_attributes($it->string, $it->line_number) );
543 for ($it = '', my $cdata_close = $this->cdata_close;;) {
544 my $next = $this->_next_token_internal($h);
545 $eof_p = !defined $next;
547 if (defined $next && $next->string =~ /$cdata_close/is) {
548 $this->_push_readahead( $next ); # push entire TmplToken object
549 $this->_set_cdata_mode( 0 );
551 last unless $this->cdata_mode_p;
552 $it .= $next->string;
556 error_normal "Unexpected end of file while looking for "
558 . "\n", $this->line_number_start;
559 $this->_set_fatal( 1 );
560 $this->_set_syntaxerror( 1 );
562 if ($this->pcdata_mode_p) {
564 $check =~ s/$re_directive//gos;
565 warn_pedantic "Markup found in PCDATA\n", $this->line_number,
566 \$pedantic_error_markup_in_pcdata_p
567 if $check =~ /$re_tag_compat/s;
569 # PCDATA should be treated as text, not CDATA
570 # Actually it should be treated as TEXT_PARAMETRIZED :-(
571 $it = TmplToken->new( $it,
572 ($this->pcdata_mode_p?
573 TmplTokenType::TEXT: TmplTokenType::CDATA),
574 $this->line_number, $this->filename )
576 if ($this->js_mode_p) {
577 my $s0 = $it->string;
580 if ($s0 =~ /^(\s*<!--\s*)(.*)(\s*--\s*>\s*)$/s) {
585 push @head, split_js $s0;
586 $it->set_js_data( identify_js_translatables(@head, @tail) );
588 $this->_set_pcdata_mode, 0;
589 $this->_set_cdata_close, undef unless !defined $it;
594 sub _token_groupable1_p ($) { # as first token, groupable into TEXT_PARAMETRIZED
596 return ($t->type == TmplTokenType::TEXT && $t->string !~ /^[,\.:\|\s]+$/is)
597 || ($t->type == TmplTokenType::DIRECTIVE
598 && $t->string =~ /^(?:$re_tmpl_var)$/os)
599 || ($t->type == TmplTokenType::TAG
600 && ($t->string =~ /^<(?:a|b|em|h[123456]|i|u)\b/is
601 || ($t->string =~ /^<input\b/is
602 && $t->attributes->{'type'}->[1] =~ /^(?:radio|text)$/is)
606 sub _token_groupable2_p ($) { # as other token, groupable into TEXT_PARAMETRIZED
608 return ($t->type == TmplTokenType::TEXT && ($t->string =~ /^\s*$/s || $t->string !~ /^[\|\s]+$/is))
609 || ($t->type == TmplTokenType::DIRECTIVE
610 && $t->string =~ /^(?:$re_tmpl_var)$/os)
611 || ($t->type == TmplTokenType::TAG
612 && ($t->string =~ /^<\/?(?:a|b|em|h[123456]|i|u)\b/is
613 || ($t->string =~ /^<input\b/is
614 && $t->attributes->{'type'}->[1] =~ /^(?:radio|text)$/is)))
617 sub _quote_cformat ($) {
623 sub string_canon ($) {
626 # Fold all whitespace into single blanks
632 sub _formalize_string_cformat ($) {
634 return _quote_cformat string_canon $s;
639 return $t->type == TmplTokenType::DIRECTIVE? '%s':
640 $t->type == TmplTokenType::TEXT?
641 _formalize_string_cformat($t->string):
642 $t->type == TmplTokenType::TAG?
643 ($t->string =~ /^<a\b/is? '<a>':
644 $t->string =~ /^<input\b/is? (
645 lc $t->attributes->{'type'}->[1] eq 'text' ? '%S':
647 _quote_cformat($t->string)):
648 _quote_cformat($t->string);
654 my $undo_trailing_blanks = sub {
655 for (my $i = $#structure; $i >= 0; $i -= 1) {
656 last unless ($structure[$i]->type == TmplTokenType::TEXT && blank_p($structure[$i]->string)) ;#|| ($structure[$i]->type == TmplTokenType::TAG && $structure[$i]->string =~ /^<br\b/is);
657 # Queue element structure: [reanalysis-p, token]
658 push @{$this->{_queue}}, [1, pop @structure];
661 &$undo_trailing_blanks;
662 while (@structure >= 2) {
663 my $something_done_p = 0;
664 # FIXME: If the last token is a close tag but there are no tags
665 # FIXME: before it, drop the close tag back into the queue. This
666 # FIXME: is an ugly hack to get rid of "foo %s</h1>" type mess.
668 && $structure[$#structure]->type == TmplTokenType::TAG
669 && $structure[$#structure]->string =~ /^<\//s) {
670 my $has_other_tags_p = 0;
671 for (my $i = 0; $i < $#structure; $i += 1) {
672 $has_other_tags_p = 1
673 if $structure[$i]->type == TmplTokenType::TAG;
674 last if $has_other_tags_p;
676 if (!$has_other_tags_p) {
677 push @{$this->{_queue}}, [0, pop @structure]
678 &$undo_trailing_blanks;
679 $something_done_p = 1;
682 # FIXME: Do the same ugly hack for the last token being a ( or [
684 && $structure[$#structure]->type == TmplTokenType::TEXT
685 && $structure[$#structure]->string =~ /^[\(\[]$/) { # not )]
686 push @{$this->{_queue}}, [1, pop @structure];
687 &$undo_trailing_blanks;
688 $something_done_p = 1;
690 # FIXME: If the first token is an open tag, but there is no
691 # FIXME: corresponding close tag, "drop the open tag", i.e.,
692 # FIXME: requeue everything for reanalysis, except the frist tag. :-(
694 && $structure[0]->type == TmplTokenType::TAG
695 && $structure[0]->string =~ /^<([a-z0-9]+)/is
696 && (my $tag = $1) !~ /^(?:br|hr|img|input)\b/is
698 my $tag_open_count = 1;
699 for (my $i = 1; $i <= $#structure; $i += 1) {
700 if ($structure[$i]->type == TmplTokenType::TAG) {
701 if ($structure[$i]->string =~ /^<(\/?)$tag\b/is) {
702 $tag_open_count += ($1? -1: +1);
706 if ($tag_open_count > 0) {
707 for (my $i = $#structure; $i; $i -= 1) {
708 push @{$this->{_queue}}, [1, pop @structure];
710 $something_done_p = 1;
713 # FIXME: If the first token is an open tag, the last token is the
714 # FIXME: corresponding close tag, and there are no other close tags
715 # FIXME: inbetween, requeue the tokens from the second token on,
716 # FIXME: flagged as ok for re-analysis
718 && $structure[0]->type == TmplTokenType::TAG
719 && $structure[0]->string =~ /^<([a-z0-9]+)/is && (my $tag = $1)
720 && $structure[$#structure]->type == TmplTokenType::TAG
721 && $structure[$#structure]->string =~ /^<\/$1\s*>$/is) {
722 my $has_other_open_or_close_tags_p = 0;
723 for (my $i = 1; $i < $#structure; $i += 1) {
724 $has_other_open_or_close_tags_p = 1
725 if $structure[$i]->type == TmplTokenType::TAG
726 && $structure[$i]->string =~ /^<\/?$tag\b/is;
727 last if $has_other_open_or_close_tags_p;
729 if (!$has_other_open_or_close_tags_p) {
730 for (my $i = $#structure; $i; $i -= 1) {
731 push @{$this->{_queue}}, [1, pop @structure];
733 $something_done_p = 1;
736 last if !$something_done_p;
741 sub looks_plausibly_like_groupable_text_p (@) {
743 # The text would look plausibly groupable if all open tags are also closed.
746 for (my $i = 0; $i <= $#structure; $i += 1) {
747 if ($structure[$i]->type == TmplTokenType::TAG) {
748 my $form = $structure[$i]->string;
749 if ($form =~ /^<([A-Z0-9]+)/is) {
751 if ($tag !~ /^(?:br|input)$/is && $form !~ /\/>$/is) {
754 } elsif ($form =~ /^<\/([A-Z0-9]+)/is) {
755 if (@tags && lc($1) eq $tags[$#tags]) {
761 } elsif ($structure[$i]->type != TmplTokenType::TEXT) {
766 return !$error_p && !@tags;
771 my $h = $this->_handle;
773 $this->{_queue} = [] unless defined $this->{_queue};
775 # Elements in the queue are ordered pairs. The first in the ordered pair
776 # specifies whether we are allowed to reanalysis; the second is the token.
777 if (@{$this->{_queue}} && !$this->{_queue}->[$#{$this->{_queue}}]->[0]) {
778 $it = (pop @{$this->{_queue}})->[1];
780 if (@{$this->{_queue}}) {
781 $it = (pop @{$this->{_queue}})->[1];
783 $it = $this->_next_token_intermediate($h);
785 if (!$this->cdata_mode_p && $this->allow_cformat_p && defined $it
786 && ($it->type == TmplTokenType::TEXT?
787 !blank_p( $it->string ): _token_groupable1_p( $it ))) {
788 my @structure = ( $it );
791 my($nonblank_text_p, $parametrized_p, $with_anchor_p, $with_input_p) = (0, 0, 0, 0);
792 if ($it->type == TmplTokenType::TEXT) {
793 $nonblank_text_p = 1 if !blank_p( $it->string );
794 } elsif ($it->type == TmplTokenType::DIRECTIVE) {
796 } elsif ($it->type == TmplTokenType::TAG && $it->string =~ /^<([A-Z0-9]+)/is) {
798 push @tags, $tag if $tag !~ /^(?:br|input)$/i;
799 $with_anchor_p = 1 if $tag eq 'a';
800 $with_input_p = 1 if $tag eq 'input';
802 # We hate | and || in msgid strings, so we try to avoid them
803 for (my $i = 1, my $quit_p = 0, my $quit_next_p = ($it->type == TmplTokenType::TEXT && $it->string =~ /^\|+$/s);; $i += 1) {
804 if (@{$this->{_queue}}) {
805 $next = (pop @{$this->{_queue}})->[1];
807 $next = $this->_next_token_intermediate($h);
809 push @structure, $next; # for consistency (with initialization)
810 last unless defined $next && _token_groupable2_p( $next );
811 last if $quit_next_p;
812 if ($next->type == TmplTokenType::TEXT) {
813 $nonblank_text_p = 1 if !blank_p( $next->string );
814 $quit_p = 1 if $next->string =~ /^\|+$/s; # We hate | and ||
815 } elsif ($next->type == TmplTokenType::DIRECTIVE) {
817 } elsif ($next->type == TmplTokenType::TAG) {
818 if ($next->string =~ /^<([A-Z0-9]+)/is) {
820 push @tags, $tag if $tag !~ /^(?:br|input)$/i;
821 $with_anchor_p = 1 if $tag eq 'a';
822 $with_input_p = 1 if $tag eq 'input';
823 } elsif ($next->string =~ /^<\/([A-Z0-9]+)/is) {
825 $quit_p = 1 unless @tags && $close eq $tags[$#tags];
826 $quit_next_p = 1 if $close =~ /^h\d$/;
832 # Undo the last token, allowing reanalysis
833 push @{$this->{_queue}}, [1, pop @structure];
834 # Simply it a bit more
835 @structure = $this->_optimize( @structure );
836 if (@structure < 2) {
839 } elsif ($nonblank_text_p && ($parametrized_p || $with_anchor_p || $with_input_p)) {
840 # Create the corresponding c-format string
841 my $string = join('', map { $_->string } @structure);
842 my $form = join('', map { _formalize $_ } @structure);
843 my($a_counter, $input_counter) = (0, 0);
844 $form =~ s/<a>/ $a_counter += 1, "<a$a_counter>" /egs;
845 $form =~ s/<input>/ $input_counter += 1, "<input$input_counter>" /egs;
846 $it = TmplToken->new($string, TmplTokenType::TEXT_PARAMETRIZED,
847 $it->line_number, $it->pathname);
848 $it->set_form( $form );
849 $it->set_children( @structure );
850 } elsif ($nonblank_text_p
851 && looks_plausibly_like_groupable_text_p( @structure )
852 && $structure[$#structure]->type == TmplTokenType::TEXT) {
853 # Combine the strings
854 my $string = join('', map { $_->string } @structure);
855 $it = TmplToken->new($string, TmplTokenType::TEXT,
856 $it->line_number, $it->pathname);;
858 # Requeue the tokens thus seen for re-emitting, allow reanalysis
860 push @{$this->{_queue}}, [1, pop @structure];
863 $it = (pop @{$this->{_queue}})->[1];
867 if (defined $it && $it->type == TmplTokenType::TEXT) {
868 my $form = string_canon $it->string;
869 $it->set_form( $form );
874 ###############################################################################
876 # Other simple functions (These are not methods)
880 return $s =~ /^(?:\s|\ $re_end_entity|$re_tmpl_var|$re_xsl)*$/os;
887 $s =~ s/^(\s|\ $re_end_entity)+//os; my $l1 = $l0 - length $s;
888 $s =~ s/(\s|\ $re_end_entity)+$//os; my $l2 = $l0 - $l1 - length $s;
889 return wantarray? (substr($s0, 0, $l1), $s, substr($s0, $l0 - $l2)): $s;
894 # Locale::PO->quote is buggy, it doesn't quote newlines :-/
895 $s =~ s/([\\"])/\\\1/gs;
897 #$s =~ s/[\177-\377]/ sprintf("\\%03o", ord($&)) /egs;
901 # Some functions that shouldn't be here... should be moved out some time
902 sub parametrize ($$$$) {
903 my($fmt_0, $cformat_p, $t, $f) = @_;
906 my @params = $t->parameters_and_fields;
907 for (my $n = 0, my $fmt = $fmt_0; length $fmt;) {
908 if ($fmt =~ /^[^%]+/) {
911 } elsif ($fmt =~ /^%%/) {
914 } elsif ($fmt =~ /^%(?:(\d+)\$)?(?:(\d+)(?:\.(\d+))?)?s/s) {
916 my($i, $width, $prec) = ((defined $1? $1: $n), $2, $3);
918 if (defined $width && defined $prec && !$width && !$prec) {
920 } elsif (defined $params[$i - 1]) {
921 my $param = $params[$i - 1];
922 warn_normal "$fmt_0: $&: Expected a TMPL_VAR, but found a "
923 . $param->type->to_string . "\n", undef
924 if $param->type != TmplTokenType::DIRECTIVE;
925 warn_normal "$fmt_0: $&: Unsupported "
926 . "field width or precision\n", undef
927 if defined $width || defined $prec;
928 warn_normal "$fmt_0: $&: Parameter $i not known", undef
929 unless defined $param;
930 $it .= defined $f? &$f( $param ): $param->string;
932 } elsif ($fmt =~ /^%(?:(\d+)\$)?(?:(\d+)(?:\.(\d+))?)?([pS])/s) {
934 my($i, $width, $prec, $conv) = ((defined $1? $1: $n), $2, $3, $4);
937 my $param = $params[$i - 1];
938 if (!defined $param) {
939 warn_normal "$fmt_0: $&: Parameter $i not known", undef;
941 if ($param->type == TmplTokenType::TAG
942 && $param->string =~ /^<input\b/is) {
943 my $type = defined $param->attributes?
944 lc($param->attributes->{'type'}->[1]): undef;
946 warn_normal "$fmt_0: $&: Expected type=text, "
947 . "but found type=$type", undef
948 unless $type eq 'text';
949 } elsif ($conv eq 'p') {
950 warn_normal "$fmt_0: $&: Expected type=radio, "
951 . "but found type=$type", undef
952 unless $type eq 'radio';
955 warn_normal "$&: Expected an INPUT, but found a "
956 . $param->type->to_string . "\n", undef
958 warn_normal "$fmt_0: $&: Unsupported "
959 . "field width or precision\n", undef
960 if defined $width || defined $prec;
961 $it .= defined $f? &$f( $param ): $param->string;
963 } elsif ($fmt =~ /^%[^%a-zA-Z]*[a-zA-Z]/) {
966 die "$&: Unknown or unsupported format specification\n"; #XXX
968 die "$&: Completely confused parametrizing\n";#XXX
972 my @anchors = $t->anchors;
973 for (my $n = 0, my $fmt = $it, $it = ''; length $fmt;) {
974 if ($fmt =~ /^(?:(?!<a\d+>).)+/is) {
977 } elsif ($fmt =~ /^<a(\d+)>/is) {
981 my $anchor = $anchors[$i - 1];
982 warn_normal "$&: Anchor $1 not found for msgid \"$fmt_0\"", undef #FIXME
983 unless defined $anchor;
984 $it .= $anchor->string;
986 die "Completely confused decoding anchors: $fmt\n";#XXX
992 sub charset_canon ($) {
994 $charset = uc($charset);
995 $charset = "$1-$2" if $charset =~ /^(ISO|UTF)(\d.*)/i;
996 $charset = 'Big5' if $charset eq 'BIG5'; # "Big5" must be in mixed case
1000 use vars qw( @latin1_utf8 );
1002 "\302\200", "\302\201", "\302\202", "\302\203", "\302\204", "\302\205",
1003 "\302\206", "\302\207", "\302\210", "\302\211", "\302\212", "\302\213",
1004 "\302\214", "\302\215", undef, undef, "\302\220", "\302\221",
1005 "\302\222", "\302\223", "\302\224", "\302\225", "\302\226", "\302\227",
1006 "\302\230", "\302\231", "\302\232", "\302\233", "\302\234", "\302\235",
1007 "\302\236", "\302\237", "\302\240", "\302\241", "\302\242", "\302\243",
1008 "\302\244", "\302\245", "\302\246", "\302\247", "\302\250", "\302\251",
1009 "\302\252", "\302\253", "\302\254", "\302\255", "\302\256", "\302\257",
1010 "\302\260", "\302\261", "\302\262", "\302\263", "\302\264", "\302\265",
1011 "\302\266", "\302\267", "\302\270", "\302\271", "\302\272", "\302\273",
1012 "\302\274", "\302\275", "\302\276", "\302\277", "\303\200", "\303\201",
1013 "\303\202", "\303\203", "\303\204", "\303\205", "\303\206", "\303\207",
1014 "\303\210", "\303\211", "\303\212", "\303\213", "\303\214", "\303\215",
1015 "\303\216", "\303\217", "\303\220", "\303\221", "\303\222", "\303\223",
1016 "\303\224", "\303\225", "\303\226", "\303\227", "\303\230", "\303\231",
1017 "\303\232", "\303\233", "\303\234", "\303\235", "\303\236", "\303\237",
1018 "\303\240", "\303\241", "\303\242", "\303\243", "\303\244", "\303\245",
1019 "\303\246", "\303\247", "\303\250", "\303\251", "\303\252", "\303\253",
1020 "\303\254", "\303\255", "\303\256", "\303\257", "\303\260", "\303\261",
1021 "\303\262", "\303\263", "\303\264", "\303\265", "\303\266", "\303\267",
1022 "\303\270", "\303\271", "\303\272", "\303\273", "\303\274", "\303\275",
1023 "\303\276", "\303\277" );
1025 sub charset_convert ($$$) {
1026 my($s, $charset_in, $charset_out) = @_;
1027 if ($s !~ /[\200-\377]/s) { # FIXME: don't worry about iso2022 for now
1029 } elsif ($charset_in eq 'ISO-8859-1' && $charset_out eq 'UTF-8') {
1030 $s =~ s/[\200-\377]/ $latin1_utf8[ord($&) - 128] /egs;
1031 } elsif ($charset_in ne $charset_out) {
1032 VerboseWarnings::warn_normal "conversion from $charset_in to $charset_out is not supported\n", undef;
1037 ###############################################################################
1041 In addition to the basic scanning, this class will also perform
1048 Emulation of c-format strings (see below)
1052 Display of warnings for certain things that affects either the
1053 ability of this class to yield correct output, or things that
1054 are known to cause the original template to cause trouble.
1058 Automatic correction of some of the things warned about
1059 (e.g., SGML "closed start tag" notation).
1063 =head2 c-format strings emulation
1065 Because English word order is not universal, a simple extraction
1066 of translatable strings may yield some strings like "Accounts for"
1067 or ambiguous strings like "in". This makes the resulting strings
1068 difficult to translate, but does not affect all languages alike.
1069 For example, Chinese (with a somewhat different word order) would
1070 be hit harder, but French would be relatively unaffected.
1072 To overcome this problem, the scanner can be configured to detect
1073 patterns with <TMPL_VAR> directives (as well as certain HTML tags),
1074 and try to construct a larger pattern that will appear in the PO
1075 file as c-format strings with %s placeholders. This additional
1076 step allows the translator to deal with cases where word order
1077 is different (replacing %s with %1$s, %2$s, etc.), or when certain
1078 words will require certain inflectional suffixes in sentences.
1080 Because this is an incompatible change, this mode must be explicitly
1081 turned on using the set_cformat(1) method call.
1083 =head2 The flag characters
1085 The character % is followed by zero or more of the following flags:
1091 The value comes from HTML <INPUT> elements.
1092 This abuse of the flag character is somewhat reasonable,
1093 since TMPL_VAR and INPUT are both variables, but of different kinds.
1097 =head2 The field width and precision
1099 An optional 0.0 can be specified for %s to specify
1100 that the <TMPL_VAR> should be suppressed.
1102 =head2 The conversion specifier
1108 Specifies any input field that is neither text nor hidden
1109 (which currently mean radio buttons).
1110 The p conversion specifier is chosen because this does not
1111 evoke any certain sensible data type.
1115 Specifies a text input field (<INPUT TYPE=TEXT>).
1116 This use of the S conversion specifier is somewhat reasonable,
1117 since text input fields contain values of undeterminable type,
1118 which can be treated as strings.
1122 Specifies a <TMPL_VAR>.
1123 This use of the o conversion specifier is somewhat reasonable,
1124 since <TMPL_VAR> denotes values of undeterminable type, which
1125 can be treated as strings.
1131 There is no code to save the tag name anywhere in the scanned token.
1133 The use of <AI<i>> to stand for the I<i>th anchor
1134 is not very well thought out.
1135 Some abuse of c-format specifies might have been more appropriate.
1139 This tokenizer is mostly based
1140 on Ambrose's hideous Perl script known as subst.pl.