/[suikacvs]/markup/html/whatpm/Whatpm/HTML.pm.src
Suika

Diff of /markup/html/whatpm/Whatpm/HTML.pm.src

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.17 by wakaba, Sat Jun 23 08:15:21 2007 UTC revision 1.233 by wakaba, Sun Sep 6 01:45:58 2009 UTC
# Line 1  Line 1 
1  package Whatpm::HTML;  package Whatpm::HTML;
2  use strict;  use strict;
3  our $VERSION=do{my @r=(q$Revision$=~/\d+/g);sprintf "%d."."%02d" x $#r,@r};  our $VERSION=do{my @r=(q$Revision$=~/\d+/g);sprintf "%d."."%02d" x $#r,@r};
4    use Error qw(:try);
5    
6  ## This is an early version of an HTML parser.  use Whatpm::HTML::Tokenizer;
7    
8  my $permitted_slash_tag_name = {  ## NOTE: This module don't check all HTML5 parse errors; character
9    base => 1,  ## encoding related parse errors are expected to be handled by relevant
10    link => 1,  ## modules.
11    meta => 1,  ## Parse errors for control characters that are not allowed in HTML5
12    hr => 1,  ## documents, for surrogate code points, and for noncharacter code
13    br => 1,  ## points, as well as U+FFFD substitions for characters whose code points
14    img=> 1,  ## is higher than U+10FFFF may be detected by combining the parser with
15    embed => 1,  ## the checker implemented by Whatpm::Charset::UnicodeChecker (for its
16    param => 1,  ## usage example, see |t/HTML-tree.t| in the Whatpm package or the
17    area => 1,  ## WebHACC::Language::HTML module in the WebHACC package).
18    col => 1,  
19    input => 1,  ## ISSUE:
20    ## var doc = implementation.createDocument (null, null, null);
21    ## doc.write ('');
22    ## alert (doc.compatMode);
23    
24    require IO::Handle;
25    
26    ## Namespace URLs
27    
28    my $HTML_NS = q<http://www.w3.org/1999/xhtml>;
29    my $MML_NS = q<http://www.w3.org/1998/Math/MathML>;
30    my $SVG_NS = q<http://www.w3.org/2000/svg>;
31    my $XLINK_NS = q<http://www.w3.org/1999/xlink>;
32    my $XML_NS = q<http://www.w3.org/XML/1998/namespace>;
33    my $XMLNS_NS = q<http://www.w3.org/2000/xmlns/>;
34    
35    ## Element categories
36    
37    ## Bits 12-15
38    sub SPECIAL_EL () { 0b1_000000000000000 }
39    sub SCOPING_EL () { 0b1_00000000000000 }
40    sub FORMATTING_EL () { 0b1_0000000000000 }
41    sub PHRASING_EL () { 0b1_000000000000 }
42    
43    ## Bits 10-11
44    #sub FOREIGN_EL () { 0b1_00000000000 } # see Whatpm::HTML::Tokenizer
45    sub FOREIGN_FLOW_CONTENT_EL () { 0b1_0000000000 }
46    
47    ## Bits 6-9
48    sub TABLE_SCOPING_EL () { 0b1_000000000 }
49    sub TABLE_ROWS_SCOPING_EL () { 0b1_00000000 }
50    sub TABLE_ROW_SCOPING_EL () { 0b1_0000000 }
51    sub TABLE_ROWS_EL () { 0b1_000000 }
52    
53    ## Bit 5
54    sub ADDRESS_DIV_P_EL () { 0b1_00000 }
55    
56    ## NOTE: Used in </body> and EOF algorithms.
57    ## Bit 4
58    sub ALL_END_TAG_OPTIONAL_EL () { 0b1_0000 }
59    
60    ## NOTE: Used in "generate implied end tags" algorithm.
61    ## NOTE: There is a code where a modified version of
62    ## END_TAG_OPTIONAL_EL is used in "generate implied end tags"
63    ## implementation (search for the algorithm name).
64    ## Bit 3
65    sub END_TAG_OPTIONAL_EL () { 0b1_000 }
66    
67    ## Bits 0-2
68    
69    sub MISC_SPECIAL_EL () { SPECIAL_EL | 0b000 }
70    sub FORM_EL () { SPECIAL_EL | 0b001 }
71    sub FRAMESET_EL () { SPECIAL_EL | 0b010 }
72    sub HEADING_EL () { SPECIAL_EL | 0b011 }
73    sub SELECT_EL () { SPECIAL_EL | 0b100 }
74    sub SCRIPT_EL () { SPECIAL_EL | 0b101 }
75    
76    sub ADDRESS_DIV_EL () { SPECIAL_EL | ADDRESS_DIV_P_EL | 0b001 }
77    sub BODY_EL () { SPECIAL_EL | ALL_END_TAG_OPTIONAL_EL | 0b001 }
78    
79    sub DTDD_EL () {
80      SPECIAL_EL |
81      END_TAG_OPTIONAL_EL |
82      ALL_END_TAG_OPTIONAL_EL |
83      0b010
84    }
85    sub LI_EL () {
86      SPECIAL_EL |
87      END_TAG_OPTIONAL_EL |
88      ALL_END_TAG_OPTIONAL_EL |
89      0b100
90    }
91    sub P_EL () {
92      SPECIAL_EL |
93      ADDRESS_DIV_P_EL |
94      END_TAG_OPTIONAL_EL |
95      ALL_END_TAG_OPTIONAL_EL |
96      0b001
97    }
98    
99    sub TABLE_ROW_EL () {
100      SPECIAL_EL |
101      TABLE_ROWS_EL |
102      TABLE_ROW_SCOPING_EL |
103      ALL_END_TAG_OPTIONAL_EL |
104      0b001
105    }
106    sub TABLE_ROW_GROUP_EL () {
107      SPECIAL_EL |
108      TABLE_ROWS_EL |
109      TABLE_ROWS_SCOPING_EL |
110      ALL_END_TAG_OPTIONAL_EL |
111      0b001
112    }
113    
114    sub MISC_SCOPING_EL () { SCOPING_EL | 0b000 }
115    sub BUTTON_EL () { SCOPING_EL | 0b001 }
116    sub CAPTION_EL () { SCOPING_EL | 0b010 }
117    sub HTML_EL () {
118      SCOPING_EL |
119      TABLE_SCOPING_EL |
120      TABLE_ROWS_SCOPING_EL |
121      TABLE_ROW_SCOPING_EL |
122      ALL_END_TAG_OPTIONAL_EL |
123      0b001
124    }
125    sub TABLE_EL () {
126      SCOPING_EL |
127      TABLE_ROWS_EL |
128      TABLE_SCOPING_EL |
129      0b001
130    }
131    sub TABLE_CELL_EL () {
132      SCOPING_EL |
133      TABLE_ROW_SCOPING_EL |
134      ALL_END_TAG_OPTIONAL_EL |
135      0b001
136    }
137    
138    sub MISC_FORMATTING_EL () { FORMATTING_EL | 0b000 }
139    sub A_EL () { FORMATTING_EL | 0b001 }
140    sub NOBR_EL () { FORMATTING_EL | 0b010 }
141    
142    sub RUBY_EL () { PHRASING_EL | 0b001 }
143    
144    ## ISSUE: ALL_END_TAG_OPTIONAL_EL?
145    sub OPTGROUP_EL () { PHRASING_EL | END_TAG_OPTIONAL_EL | 0b001 }
146    sub OPTION_EL () { PHRASING_EL | END_TAG_OPTIONAL_EL | 0b010 }
147    sub RUBY_COMPONENT_EL () { PHRASING_EL | END_TAG_OPTIONAL_EL | 0b100 }
148    
149    sub MML_AXML_EL () { PHRASING_EL | FOREIGN_EL | 0b001 }
150    
151    my $el_category = {
152      a => A_EL,
153      address => ADDRESS_DIV_EL,
154      applet => MISC_SCOPING_EL,
155      area => MISC_SPECIAL_EL,
156      article => MISC_SPECIAL_EL,
157      aside => MISC_SPECIAL_EL,
158      b => FORMATTING_EL,
159      base => MISC_SPECIAL_EL,
160      basefont => MISC_SPECIAL_EL,
161      bgsound => MISC_SPECIAL_EL,
162      big => FORMATTING_EL,
163      blockquote => MISC_SPECIAL_EL,
164      body => BODY_EL,
165      br => MISC_SPECIAL_EL,
166      button => BUTTON_EL,
167      caption => CAPTION_EL,
168      center => MISC_SPECIAL_EL,
169      col => MISC_SPECIAL_EL,
170      colgroup => MISC_SPECIAL_EL,
171      command => MISC_SPECIAL_EL,
172      datagrid => MISC_SPECIAL_EL,
173      dd => DTDD_EL,
174      details => MISC_SPECIAL_EL,
175      dialog => MISC_SPECIAL_EL,
176      dir => MISC_SPECIAL_EL,
177      div => ADDRESS_DIV_EL,
178      dl => MISC_SPECIAL_EL,
179      dt => DTDD_EL,
180      em => FORMATTING_EL,
181      embed => MISC_SPECIAL_EL,
182      fieldset => MISC_SPECIAL_EL,
183      figure => MISC_SPECIAL_EL,
184      font => FORMATTING_EL,
185      footer => MISC_SPECIAL_EL,
186      form => FORM_EL,
187      frame => MISC_SPECIAL_EL,
188      frameset => FRAMESET_EL,
189      h1 => HEADING_EL,
190      h2 => HEADING_EL,
191      h3 => HEADING_EL,
192      h4 => HEADING_EL,
193      h5 => HEADING_EL,
194      h6 => HEADING_EL,
195      head => MISC_SPECIAL_EL,
196      header => MISC_SPECIAL_EL,
197      hr => MISC_SPECIAL_EL,
198      html => HTML_EL,
199      i => FORMATTING_EL,
200      iframe => MISC_SPECIAL_EL,
201      img => MISC_SPECIAL_EL,
202      #image => MISC_SPECIAL_EL, ## NOTE: Commented out in the spec.
203      input => MISC_SPECIAL_EL,
204      isindex => MISC_SPECIAL_EL,
205      ## XXX keygen? (Whether a void element is in Special or not does not
206      ## affect to the processing, however.)
207      li => LI_EL,
208      link => MISC_SPECIAL_EL,
209      listing => MISC_SPECIAL_EL,
210      marquee => MISC_SCOPING_EL,
211      menu => MISC_SPECIAL_EL,
212      meta => MISC_SPECIAL_EL,
213      nav => MISC_SPECIAL_EL,
214      nobr => NOBR_EL,
215      noembed => MISC_SPECIAL_EL,
216      noframes => MISC_SPECIAL_EL,
217      noscript => MISC_SPECIAL_EL,
218      object => MISC_SCOPING_EL,
219      ol => MISC_SPECIAL_EL,
220      optgroup => OPTGROUP_EL,
221      option => OPTION_EL,
222      p => P_EL,
223      param => MISC_SPECIAL_EL,
224      plaintext => MISC_SPECIAL_EL,
225      pre => MISC_SPECIAL_EL,
226      rp => RUBY_COMPONENT_EL,
227      rt => RUBY_COMPONENT_EL,
228      ruby => RUBY_EL,
229      s => FORMATTING_EL,
230      script => MISC_SPECIAL_EL,
231      select => SELECT_EL,
232      section => MISC_SPECIAL_EL,
233      small => FORMATTING_EL,
234      spacer => MISC_SPECIAL_EL,
235      strike => FORMATTING_EL,
236      strong => FORMATTING_EL,
237      style => MISC_SPECIAL_EL,
238      table => TABLE_EL,
239      tbody => TABLE_ROW_GROUP_EL,
240      td => TABLE_CELL_EL,
241      textarea => MISC_SPECIAL_EL,
242      tfoot => TABLE_ROW_GROUP_EL,
243      th => TABLE_CELL_EL,
244      thead => TABLE_ROW_GROUP_EL,
245      title => MISC_SPECIAL_EL,
246      tr => TABLE_ROW_EL,
247      tt => FORMATTING_EL,
248      u => FORMATTING_EL,
249      ul => MISC_SPECIAL_EL,
250      wbr => MISC_SPECIAL_EL,
251  };  };
252    
253  my $c1_entity_char = {  my $el_category_f = {
254    0x80 => 0x20AC,    $MML_NS => {
255    0x81 => 0xFFFD,      'annotation-xml' => MML_AXML_EL,
256    0x82 => 0x201A,      mi => FOREIGN_EL | FOREIGN_FLOW_CONTENT_EL,
257    0x83 => 0x0192,      mo => FOREIGN_EL | FOREIGN_FLOW_CONTENT_EL,
258    0x84 => 0x201E,      mn => FOREIGN_EL | FOREIGN_FLOW_CONTENT_EL,
259    0x85 => 0x2026,      ms => FOREIGN_EL | FOREIGN_FLOW_CONTENT_EL,
260    0x86 => 0x2020,      mtext => FOREIGN_EL | FOREIGN_FLOW_CONTENT_EL,
261    0x87 => 0x2021,    },
262    0x88 => 0x02C6,    $SVG_NS => {
263    0x89 => 0x2030,      foreignObject => SCOPING_EL | FOREIGN_EL | FOREIGN_FLOW_CONTENT_EL,
264    0x8A => 0x0160,      desc => FOREIGN_EL | FOREIGN_FLOW_CONTENT_EL,
265    0x8B => 0x2039,      title => FOREIGN_EL | FOREIGN_FLOW_CONTENT_EL,
266    0x8C => 0x0152,    },
267    0x8D => 0xFFFD,    ## NOTE: In addition, FOREIGN_EL is set to non-HTML elements.
   0x8E => 0x017D,  
   0x8F => 0xFFFD,  
   0x90 => 0xFFFD,  
   0x91 => 0x2018,  
   0x92 => 0x2019,  
   0x93 => 0x201C,  
   0x94 => 0x201D,  
   0x95 => 0x2022,  
   0x96 => 0x2013,  
   0x97 => 0x2014,  
   0x98 => 0x02DC,  
   0x99 => 0x2122,  
   0x9A => 0x0161,  
   0x9B => 0x203A,  
   0x9C => 0x0153,  
   0x9D => 0xFFFD,  
   0x9E => 0x017E,  
   0x9F => 0x0178,  
 }; # $c1_entity_char  
   
 my $special_category = {  
   address => 1, area => 1, base => 1, basefont => 1, bgsound => 1,  
   blockquote => 1, body => 1, br => 1, center => 1, col => 1, colgroup => 1,  
   dd => 1, dir => 1, div => 1, dl => 1, dt => 1, embed => 1, fieldset => 1,  
   form => 1, frame => 1, frameset => 1, h1 => 1, h2 => 1, h3 => 1,  
   h4 => 1, h5 => 1, h6 => 1, head => 1, hr => 1, iframe => 1, image => 1,  
   img => 1, input => 1, isindex => 1, li => 1, link => 1, listing => 1,  
   menu => 1, meta => 1, noembed => 1, noframes => 1, noscript => 1,  
   ol => 1, optgroup => 1, option => 1, p => 1, param => 1, plaintext => 1,  
   pre => 1, script => 1, select => 1, spacer => 1, style => 1, tbody => 1,  
   textarea => 1, tfoot => 1, thead => 1, title => 1, tr => 1, ul => 1, wbr => 1,  
268  };  };
 my $scoping_category = {  
   button => 1, caption => 1, html => 1, marquee => 1, object => 1,  
   table => 1, td => 1, th => 1,  
 };  
 my $formatting_category = {  
   a => 1, b => 1, big => 1, em => 1, font => 1, i => 1, nobr => 1,  
   s => 1, small => 1, strile => 1, strong => 1, tt => 1, u => 1,  
 };  
 # $phrasing_category: all other elements  
269    
270  sub parse_string ($$$;$) {  my $svg_attr_name = {
271    my $self = shift->new;    attributename => 'attributeName',
272    my $s = \$_[0];    attributetype => 'attributeType',
273    $self->{document} = $_[1];    basefrequency => 'baseFrequency',
274      baseprofile => 'baseProfile',
275      calcmode => 'calcMode',
276      clippathunits => 'clipPathUnits',
277      contentscripttype => 'contentScriptType',
278      contentstyletype => 'contentStyleType',
279      diffuseconstant => 'diffuseConstant',
280      edgemode => 'edgeMode',
281      externalresourcesrequired => 'externalResourcesRequired',
282      filterres => 'filterRes',
283      filterunits => 'filterUnits',
284      glyphref => 'glyphRef',
285      gradienttransform => 'gradientTransform',
286      gradientunits => 'gradientUnits',
287      kernelmatrix => 'kernelMatrix',
288      kernelunitlength => 'kernelUnitLength',
289      keypoints => 'keyPoints',
290      keysplines => 'keySplines',
291      keytimes => 'keyTimes',
292      lengthadjust => 'lengthAdjust',
293      limitingconeangle => 'limitingConeAngle',
294      markerheight => 'markerHeight',
295      markerunits => 'markerUnits',
296      markerwidth => 'markerWidth',
297      maskcontentunits => 'maskContentUnits',
298      maskunits => 'maskUnits',
299      numoctaves => 'numOctaves',
300      pathlength => 'pathLength',
301      patterncontentunits => 'patternContentUnits',
302      patterntransform => 'patternTransform',
303      patternunits => 'patternUnits',
304      pointsatx => 'pointsAtX',
305      pointsaty => 'pointsAtY',
306      pointsatz => 'pointsAtZ',
307      preservealpha => 'preserveAlpha',
308      preserveaspectratio => 'preserveAspectRatio',
309      primitiveunits => 'primitiveUnits',
310      refx => 'refX',
311      refy => 'refY',
312      repeatcount => 'repeatCount',
313      repeatdur => 'repeatDur',
314      requiredextensions => 'requiredExtensions',
315      requiredfeatures => 'requiredFeatures',
316      specularconstant => 'specularConstant',
317      specularexponent => 'specularExponent',
318      spreadmethod => 'spreadMethod',
319      startoffset => 'startOffset',
320      stddeviation => 'stdDeviation',
321      stitchtiles => 'stitchTiles',
322      surfacescale => 'surfaceScale',
323      systemlanguage => 'systemLanguage',
324      tablevalues => 'tableValues',
325      targetx => 'targetX',
326      targety => 'targetY',
327      textlength => 'textLength',
328      viewbox => 'viewBox',
329      viewtarget => 'viewTarget',
330      xchannelselector => 'xChannelSelector',
331      ychannelselector => 'yChannelSelector',
332      zoomandpan => 'zoomAndPan',
333    };
334    
335    ## NOTE: |set_inner_html| copies most of this method's code  my $foreign_attr_xname = {
336      'xlink:actuate' => [$XLINK_NS, ['xlink', 'actuate']],
337      'xlink:arcrole' => [$XLINK_NS, ['xlink', 'arcrole']],
338      'xlink:href' => [$XLINK_NS, ['xlink', 'href']],
339      'xlink:role' => [$XLINK_NS, ['xlink', 'role']],
340      'xlink:show' => [$XLINK_NS, ['xlink', 'show']],
341      'xlink:title' => [$XLINK_NS, ['xlink', 'title']],
342      'xlink:type' => [$XLINK_NS, ['xlink', 'type']],
343      'xml:base' => [$XML_NS, ['xml', 'base']],
344      'xml:lang' => [$XML_NS, ['xml', 'lang']],
345      'xml:space' => [$XML_NS, ['xml', 'space']],
346      'xmlns' => [$XMLNS_NS, [undef, 'xmlns']],
347      'xmlns:xlink' => [$XMLNS_NS, ['xmlns', 'xlink']],
348    };
349    
350    my $i = 0;  ## ISSUE: xmlns:xlink="non-xlink-ns" is not an error.
   my $line = 1;  
   my $column = 0;  
   $self->{set_next_input_character} = sub {  
     my $self = shift;  
351    
352      pop @{$self->{prev_input_character}};  ## TODO: Invoke the reset algorithm when a resettable element is
353      unshift @{$self->{prev_input_character}}, $self->{next_input_character};  ## created (cf. HTML5 revision 2259).
354    
355      $self->{next_input_character} = -1 and return if $i >= length $$s;  sub parse_byte_string ($$$$;$) {
356      $self->{next_input_character} = ord substr $$s, $i++, 1;    my $self = shift;
357      $column++;    my $charset_name = shift;
358          open my $input, '<', ref $_[0] ? $_[0] : \($_[0]);
359      if ($self->{next_input_character} == 0x000A) { # LF    return $self->parse_byte_stream ($charset_name, $input, @_[1..$#_]);
360        $line++;  } # parse_byte_string
361        $column = 0;  
362      } elsif ($self->{next_input_character} == 0x000D) { # CR  sub parse_byte_stream ($$$$;$$) {
363        $i++ if substr ($$s, $i, 1) eq "\x0A";    # my ($self, $charset_name, $byte_stream, $doc, $onerror, $get_wrapper) = @_;
364        $self->{next_input_character} = 0x000A; # LF # MUST    my $self = ref $_[0] ? shift : shift->new;
365        $line++;    my $charset_name = shift;
366        $column = 0;    my $byte_stream = $_[0];
     } elsif ($self->{next_input_character} > 0x10FFFF) {  
       $self->{next_input_character} = 0xFFFD; # REPLACEMENT CHARACTER # MUST  
     } elsif ($self->{next_input_character} == 0x0000) { # NULL  
       !!!parse-error (type => 'NULL');  
       $self->{next_input_character} = 0xFFFD; # REPLACEMENT CHARACTER # MUST  
     }  
   };  
   $self->{prev_input_character} = [-1, -1, -1];  
   $self->{next_input_character} = -1;  
367    
368    my $onerror = $_[2] || sub {    my $onerror = $_[2] || sub {
369      my (%opt) = @_;      my (%opt) = @_;
370      warn "Parse error ($opt{type}) at line $opt{line} column $opt{column}\n";      warn "Parse error ($opt{type})\n";
371    };    };
372    $self->{parse_error} = sub {    $self->{parse_error} = $onerror; # updated later by parse_char_string
     $onerror->(@_, line => $line, column => $column);  
   };  
   
   $self->_initialize_tokenizer;  
   $self->_initialize_tree_constructor;  
   $self->_construct_tree;  
   $self->_terminate_tree_constructor;  
373    
374    return $self->{document};    my $get_wrapper = $_[3] || sub ($) {
375  } # parse_string      return $_[0]; # $_[0] = byte stream handle, returned = arg to char handle
   
 sub new ($) {  
   my $class = shift;  
   my $self = bless {}, $class;  
   $self->{set_next_input_character} = sub {  
     $self->{next_input_character} = -1;  
   };  
   $self->{parse_error} = sub {  
     #  
376    };    };
   return $self;  
 } # new  
   
 ## Implementations MUST act as if state machine in the spec  
   
 sub _initialize_tokenizer ($) {  
   my $self = shift;  
   $self->{state} = 'data'; # MUST  
   $self->{content_model_flag} = 'PCDATA'; # be  
   undef $self->{current_token}; # start tag, end tag, comment, or DOCTYPE  
   undef $self->{current_attribute};  
   undef $self->{last_emitted_start_tag_name};  
   undef $self->{last_attribute_value_state};  
   $self->{char} = [];  
   # $self->{next_input_character}  
   !!!next-input-character;  
   $self->{token} = [];  
 } # _initialize_tokenizer  
   
 ## A token has:  
 ##   ->{type} eq 'DOCTYPE', 'start tag', 'end tag', 'comment',  
 ##       'character', or 'end-of-file'  
 ##   ->{name} (DOCTYPE, start tag (tagname), end tag (tagname))  
     ## ISSUE: the spec need s/tagname/tag name/  
 ##   ->{error} == 1 or 0 (DOCTYPE)  
 ##   ->{attributes} isa HASH (start tag, end tag)  
 ##   ->{data} (comment, character)  
   
 ## Macros  
 ##   Macros MUST be preceded by three EXCLAMATION MARKs.  
 ##   emit ($token)  
 ##     Emits the specified token.  
   
 ## Emitted token MUST immediately be handled by the tree construction state.  
   
 ## Before each step, UA MAY check to see if either one of the scripts in  
 ## "list of scripts that will execute as soon as possible" or the first  
 ## script in the "list of scripts that will execute asynchronously",  
 ## has completed loading.  If one has, then it MUST be executed  
 ## and removed from the list.  
   
 sub _get_next_token ($) {  
   my $self = shift;  
   if (@{$self->{token}}) {  
     return shift @{$self->{token}};  
   }  
   
   A: {  
     if ($self->{state} eq 'data') {  
       if ($self->{next_input_character} == 0x0026) { # &  
         if ($self->{content_model_flag} eq 'PCDATA' or  
             $self->{content_model_flag} eq 'RCDATA') {  
           $self->{state} = 'entity data';  
           !!!next-input-character;  
           redo A;  
         } else {  
           #  
         }  
       } elsif ($self->{next_input_character} == 0x002D) { # -  
         if ($self->{content_model_flag} eq 'RCDATA' or  
             $self->{content_model_flag} eq 'CDATA') {  
           unless ($self->{escape}) {  
             if ($self->{prev_input_character}->[0] == 0x002D and # -  
                 $self->{prev_input_character}->[1] == 0x0021 and # !  
                 $self->{prev_input_character}->[2] == 0x003C) { # <  
               $self->{escape} = 1;  
             }  
           }  
         }  
           
         #  
       } elsif ($self->{next_input_character} == 0x003C) { # <  
         if ($self->{content_model_flag} eq 'PCDATA' or  
             (($self->{content_model_flag} eq 'CDATA' or  
               $self->{content_model_flag} eq 'RCDATA') and  
              not $self->{escape})) {  
           $self->{state} = 'tag open';  
           !!!next-input-character;  
           redo A;  
         } else {  
           #  
         }  
       } elsif ($self->{next_input_character} == 0x003E) { # >  
         if ($self->{escape} and  
             ($self->{content_model_flag} eq 'RCDATA' or  
              $self->{content_model_flag} eq 'CDATA')) {  
           if ($self->{prev_input_character}->[0] == 0x002D and # -  
               $self->{prev_input_character}->[1] == 0x002D) { # -  
             delete $self->{escape};  
           }  
         }  
           
         #  
       } elsif ($self->{next_input_character} == -1) {  
         !!!emit ({type => 'end-of-file'});  
         last A; ## TODO: ok?  
       }  
       # Anything else  
       my $token = {type => 'character',  
                    data => chr $self->{next_input_character}};  
       ## Stay in the data state  
       !!!next-input-character;  
   
       !!!emit ($token);  
   
       redo A;  
     } elsif ($self->{state} eq 'entity data') {  
       ## (cannot happen in CDATA state)  
         
       my $token = $self->_tokenize_attempt_to_consume_an_entity;  
377    
378        $self->{state} = 'data';    ## HTML5 encoding sniffing algorithm
379        # next-input-character is already done    require Message::Charset::Info;
380      my $charset;
381      my $buffer;
382      my ($char_stream, $e_status);
383    
384      SNIFFING: {
385        ## NOTE: By setting |allow_fallback| option true when the
386        ## |get_decode_handle| method is invoked, we ignore what the HTML5
387        ## spec requires, i.e. unsupported encoding should be ignored.
388          ## TODO: We should not do this unless the parser is invoked
389          ## in the conformance checking mode, in which this behavior
390          ## would be useful.
391    
392        unless (defined $token) {      ## Step 1
393          !!!emit ({type => 'character', data => '&'});      if (defined $charset_name) {
394          $charset = Message::Charset::Info->get_by_html_name ($charset_name);
395              ## TODO: Is this ok?  Transfer protocol's parameter should be
396              ## interpreted in its semantics?
397    
398          ($char_stream, $e_status) = $charset->get_decode_handle
399              ($byte_stream, allow_error_reporting => 1,
400               allow_fallback => 1);
401          if ($char_stream) {
402            $self->{confident} = 1;
403            last SNIFFING;
404        } else {        } else {
405          !!!emit ($token);          !!!parse-error (type => 'charset:not supported',
406                            layer => 'encode',
407                            line => 1, column => 1,
408                            value => $charset_name,
409                            level => $self->{level}->{uncertain});
410        }        }
411        }
412    
413        redo A;      ## Step 2
414      } elsif ($self->{state} eq 'tag open') {      my $byte_buffer = '';
415        if ($self->{content_model_flag} eq 'RCDATA' or      for (1..1024) {
416            $self->{content_model_flag} eq 'CDATA') {        my $char = $byte_stream->getc;
417          if ($self->{next_input_character} == 0x002F) { # /        last unless defined $char;
418            !!!next-input-character;        $byte_buffer .= $char;
419            $self->{state} = 'close tag open';      } ## TODO: timeout
           redo A;  
         } else {  
           ## reconsume  
           $self->{state} = 'data';  
   
           !!!emit ({type => 'character', data => '<'});  
   
           redo A;  
         }  
       } elsif ($self->{content_model_flag} eq 'PCDATA') {  
         if ($self->{next_input_character} == 0x0021) { # !  
           $self->{state} = 'markup declaration open';  
           !!!next-input-character;  
           redo A;  
         } elsif ($self->{next_input_character} == 0x002F) { # /  
           $self->{state} = 'close tag open';  
           !!!next-input-character;  
           redo A;  
         } elsif (0x0041 <= $self->{next_input_character} and  
                  $self->{next_input_character} <= 0x005A) { # A..Z  
           $self->{current_token}  
             = {type => 'start tag',  
                tag_name => chr ($self->{next_input_character} + 0x0020)};  
           $self->{state} = 'tag name';  
           !!!next-input-character;  
           redo A;  
         } elsif (0x0061 <= $self->{next_input_character} and  
                  $self->{next_input_character} <= 0x007A) { # a..z  
           $self->{current_token} = {type => 'start tag',  
                             tag_name => chr ($self->{next_input_character})};  
           $self->{state} = 'tag name';  
           !!!next-input-character;  
           redo A;  
         } elsif ($self->{next_input_character} == 0x003E) { # >  
           !!!parse-error (type => 'empty start tag');  
           $self->{state} = 'data';  
           !!!next-input-character;  
   
           !!!emit ({type => 'character', data => '<>'});  
   
           redo A;  
         } elsif ($self->{next_input_character} == 0x003F) { # ?  
           !!!parse-error (type => 'pio');  
           $self->{state} = 'bogus comment';  
           ## $self->{next_input_character} is intentionally left as is  
           redo A;  
         } else {  
           !!!parse-error (type => 'bare stago');  
           $self->{state} = 'data';  
           ## reconsume  
420    
421            !!!emit ({type => 'character', data => '<'});      ## Step 3
422        if ($byte_buffer =~ /^\xFE\xFF/) {
423          $charset = Message::Charset::Info->get_by_html_name ('utf-16be');
424          ($char_stream, $e_status) = $charset->get_decode_handle
425              ($byte_stream, allow_error_reporting => 1,
426               allow_fallback => 1, byte_buffer => \$byte_buffer);
427          $self->{confident} = 1;
428          last SNIFFING;
429        } elsif ($byte_buffer =~ /^\xFF\xFE/) {
430          $charset = Message::Charset::Info->get_by_html_name ('utf-16le');
431          ($char_stream, $e_status) = $charset->get_decode_handle
432              ($byte_stream, allow_error_reporting => 1,
433               allow_fallback => 1, byte_buffer => \$byte_buffer);
434          $self->{confident} = 1;
435          last SNIFFING;
436        } elsif ($byte_buffer =~ /^\xEF\xBB\xBF/) {
437          $charset = Message::Charset::Info->get_by_html_name ('utf-8');
438          ($char_stream, $e_status) = $charset->get_decode_handle
439              ($byte_stream, allow_error_reporting => 1,
440               allow_fallback => 1, byte_buffer => \$byte_buffer);
441          $self->{confident} = 1;
442          last SNIFFING;
443        }
444    
445            redo A;      ## Step 4
446          }      ## TODO: <meta charset>
       } else {  
         die "$0: $self->{content_model_flag}: Unknown content model flag";  
       }  
     } elsif ($self->{state} eq 'close tag open') {  
       if ($self->{content_model_flag} eq 'RCDATA' or  
           $self->{content_model_flag} eq 'CDATA') {  
         my @next_char;  
         TAGNAME: for (my $i = 0; $i < length $self->{last_emitted_start_tag_name}; $i++) {  
           push @next_char, $self->{next_input_character};  
           my $c = ord substr ($self->{last_emitted_start_tag_name}, $i, 1);  
           my $C = 0x0061 <= $c && $c <= 0x007A ? $c - 0x0020 : $c;  
           if ($self->{next_input_character} == $c or $self->{next_input_character} == $C) {  
             !!!next-input-character;  
             next TAGNAME;  
           } else {  
             !!!parse-error (type => 'unmatched end tag');  
             $self->{next_input_character} = shift @next_char; # reconsume  
             !!!back-next-input-character (@next_char);  
             $self->{state} = 'data';  
447    
448              !!!emit ({type => 'character', data => '</'});      ## Step 5
449        ## TODO: from history
450    
451              redo A;      ## Step 6
452            }      require Whatpm::Charset::UniversalCharDet;
453          }      $charset_name = Whatpm::Charset::UniversalCharDet->detect_byte_string
454          push @next_char, $self->{next_input_character};          ($byte_buffer);
455            if (defined $charset_name) {
456          unless ($self->{next_input_character} == 0x0009 or # HT        $charset = Message::Charset::Info->get_by_html_name ($charset_name);
457                  $self->{next_input_character} == 0x000A or # LF  
458                  $self->{next_input_character} == 0x000B or # VT        require Whatpm::Charset::DecodeHandle;
459                  $self->{next_input_character} == 0x000C or # FF        $buffer = Whatpm::Charset::DecodeHandle::ByteBuffer->new
460                  $self->{next_input_character} == 0x0020 or # SP            ($byte_stream);
461                  $self->{next_input_character} == 0x003E or # >        ($char_stream, $e_status) = $charset->get_decode_handle
462                  $self->{next_input_character} == 0x002F or # /            ($buffer, allow_error_reporting => 1,
463                  $self->{next_input_character} == -1) {             allow_fallback => 1, byte_buffer => \$byte_buffer);
464            !!!parse-error (type => 'unmatched end tag');        if ($char_stream) {
465            $self->{next_input_character} = shift @next_char; # reconsume          $buffer->{buffer} = $byte_buffer;
466            !!!back-next-input-character (@next_char);          !!!parse-error (type => 'sniffing:chardet',
467            $self->{state} = 'data';                          text => $charset_name,
468                            level => $self->{level}->{info},
469            !!!emit ({type => 'character', data => '</'});                          layer => 'encode',
470                            line => 1, column => 1);
471            redo A;          $self->{confident} = 0;
472          } else {          last SNIFFING;
           $self->{next_input_character} = shift @next_char;  
           !!!back-next-input-character (@next_char);  
           # and consume...  
         }  
473        }        }
474              }
       if (0x0041 <= $self->{next_input_character} and  
           $self->{next_input_character} <= 0x005A) { # A..Z  
         $self->{current_token} = {type => 'end tag',  
                           tag_name => chr ($self->{next_input_character} + 0x0020)};  
         $self->{state} = 'tag name';  
         !!!next-input-character;  
         redo A;  
       } elsif (0x0061 <= $self->{next_input_character} and  
                $self->{next_input_character} <= 0x007A) { # a..z  
         $self->{current_token} = {type => 'end tag',  
                           tag_name => chr ($self->{next_input_character})};  
         $self->{state} = 'tag name';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x003E) { # >  
         !!!parse-error (type => 'empty end tag');  
         $self->{state} = 'data';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'bare etago');  
         $self->{state} = 'data';  
         # reconsume  
   
         !!!emit ({type => 'character', data => '</'});  
   
         redo A;  
       } else {  
         !!!parse-error (type => 'bogus end tag');  
         $self->{state} = 'bogus comment';  
         ## $self->{next_input_character} is intentionally left as is  
         redo A;  
       }  
     } elsif ($self->{state} eq 'tag name') {  
       if ($self->{next_input_character} == 0x0009 or # HT  
           $self->{next_input_character} == 0x000A or # LF  
           $self->{next_input_character} == 0x000B or # VT  
           $self->{next_input_character} == 0x000C or # FF  
           $self->{next_input_character} == 0x0020) { # SP  
         $self->{state} = 'before attribute name';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x003E) { # >  
         if ($self->{current_token}->{type} eq 'start tag') {  
           $self->{last_emitted_start_tag_name} = $self->{current_token}->{tag_name};  
         } elsif ($self->{current_token}->{type} eq 'end tag') {  
           $self->{content_model_flag} = 'PCDATA'; # MUST  
           if ($self->{current_token}->{attributes}) {  
             !!!parse-error (type => 'end tag attribute');  
           }  
         } else {  
           die "$0: $self->{current_token}->{type}: Unknown token type";  
         }  
         $self->{state} = 'data';  
         !!!next-input-character;  
   
         !!!emit ($self->{current_token}); # start tag or end tag  
         undef $self->{current_token};  
   
         redo A;  
       } elsif (0x0041 <= $self->{next_input_character} and  
                $self->{next_input_character} <= 0x005A) { # A..Z  
         $self->{current_token}->{tag_name} .= chr ($self->{next_input_character} + 0x0020);  
           # start tag or end tag  
         ## Stay in this state  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'unclosed tag');  
         if ($self->{current_token}->{type} eq 'start tag') {  
           $self->{last_emitted_start_tag_name} = $self->{current_token}->{tag_name};  
         } elsif ($self->{current_token}->{type} eq 'end tag') {  
           $self->{content_model_flag} = 'PCDATA'; # MUST  
           if ($self->{current_token}->{attributes}) {  
             !!!parse-error (type => 'end tag attribute');  
           }  
         } else {  
           die "$0: $self->{current_token}->{type}: Unknown token type";  
         }  
         $self->{state} = 'data';  
         # reconsume  
   
         !!!emit ($self->{current_token}); # start tag or end tag  
         undef $self->{current_token};  
   
         redo A;  
       } elsif ($self->{next_input_character} == 0x002F) { # /  
         !!!next-input-character;  
         if ($self->{next_input_character} == 0x003E and # >  
             $self->{current_token}->{type} eq 'start tag' and  
             $permitted_slash_tag_name->{$self->{current_token}->{tag_name}}) {  
           # permitted slash  
           #  
         } else {  
           !!!parse-error (type => 'nestc');  
         }  
         $self->{state} = 'before attribute name';  
         # next-input-character is already done  
         redo A;  
       } else {  
         $self->{current_token}->{tag_name} .= chr $self->{next_input_character};  
           # start tag or end tag  
         ## Stay in the state  
         !!!next-input-character;  
         redo A;  
       }  
     } elsif ($self->{state} eq 'before attribute name') {  
       if ($self->{next_input_character} == 0x0009 or # HT  
           $self->{next_input_character} == 0x000A or # LF  
           $self->{next_input_character} == 0x000B or # VT  
           $self->{next_input_character} == 0x000C or # FF  
           $self->{next_input_character} == 0x0020) { # SP  
         ## Stay in the state  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x003E) { # >  
         if ($self->{current_token}->{type} eq 'start tag') {  
           $self->{last_emitted_start_tag_name} = $self->{current_token}->{tag_name};  
         } elsif ($self->{current_token}->{type} eq 'end tag') {  
           $self->{content_model_flag} = 'PCDATA'; # MUST  
           if ($self->{current_token}->{attributes}) {  
             !!!parse-error (type => 'end tag attribute');  
           }  
         } else {  
           die "$0: $self->{current_token}->{type}: Unknown token type";  
         }  
         $self->{state} = 'data';  
         !!!next-input-character;  
   
         !!!emit ($self->{current_token}); # start tag or end tag  
         undef $self->{current_token};  
   
         redo A;  
       } elsif (0x0041 <= $self->{next_input_character} and  
                $self->{next_input_character} <= 0x005A) { # A..Z  
         $self->{current_attribute} = {name => chr ($self->{next_input_character} + 0x0020),  
                               value => ''};  
         $self->{state} = 'attribute name';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x002F) { # /  
         !!!next-input-character;  
         if ($self->{next_input_character} == 0x003E and # >  
             $self->{current_token}->{type} eq 'start tag' and  
             $permitted_slash_tag_name->{$self->{current_token}->{tag_name}}) {  
           # permitted slash  
           #  
         } else {  
           !!!parse-error (type => 'nestc');  
         }  
         ## Stay in the state  
         # next-input-character is already done  
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'unclosed tag');  
         if ($self->{current_token}->{type} eq 'start tag') {  
           $self->{last_emitted_start_tag_name} = $self->{current_token}->{tag_name};  
         } elsif ($self->{current_token}->{type} eq 'end tag') {  
           $self->{content_model_flag} = 'PCDATA'; # MUST  
           if ($self->{current_token}->{attributes}) {  
             !!!parse-error (type => 'end tag attribute');  
           }  
         } else {  
           die "$0: $self->{current_token}->{type}: Unknown token type";  
         }  
         $self->{state} = 'data';  
         # reconsume  
   
         !!!emit ($self->{current_token}); # start tag or end tag  
         undef $self->{current_token};  
   
         redo A;  
       } else {  
         $self->{current_attribute} = {name => chr ($self->{next_input_character}),  
                               value => ''};  
         $self->{state} = 'attribute name';  
         !!!next-input-character;  
         redo A;  
       }  
     } elsif ($self->{state} eq 'attribute name') {  
       my $before_leave = sub {  
         if (exists $self->{current_token}->{attributes} # start tag or end tag  
             ->{$self->{current_attribute}->{name}}) { # MUST  
           !!!parse-error (type => 'dupulicate attribute');  
           ## Discard $self->{current_attribute} # MUST  
         } else {  
           $self->{current_token}->{attributes}->{$self->{current_attribute}->{name}}  
             = $self->{current_attribute};  
         }  
       }; # $before_leave  
   
       if ($self->{next_input_character} == 0x0009 or # HT  
           $self->{next_input_character} == 0x000A or # LF  
           $self->{next_input_character} == 0x000B or # VT  
           $self->{next_input_character} == 0x000C or # FF  
           $self->{next_input_character} == 0x0020) { # SP  
         $before_leave->();  
         $self->{state} = 'after attribute name';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x003D) { # =  
         $before_leave->();  
         $self->{state} = 'before attribute value';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x003E) { # >  
         $before_leave->();  
         if ($self->{current_token}->{type} eq 'start tag') {  
           $self->{last_emitted_start_tag_name} = $self->{current_token}->{tag_name};  
         } elsif ($self->{current_token}->{type} eq 'end tag') {  
           $self->{content_model_flag} = 'PCDATA'; # MUST  
           if ($self->{current_token}->{attributes}) {  
             !!!parse-error (type => 'end tag attribute');  
           }  
         } else {  
           die "$0: $self->{current_token}->{type}: Unknown token type";  
         }  
         $self->{state} = 'data';  
         !!!next-input-character;  
   
         !!!emit ($self->{current_token}); # start tag or end tag  
         undef $self->{current_token};  
   
         redo A;  
       } elsif (0x0041 <= $self->{next_input_character} and  
                $self->{next_input_character} <= 0x005A) { # A..Z  
         $self->{current_attribute}->{name} .= chr ($self->{next_input_character} + 0x0020);  
         ## Stay in the state  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x002F) { # /  
         $before_leave->();  
         !!!next-input-character;  
         if ($self->{next_input_character} == 0x003E and # >  
             $self->{current_token}->{type} eq 'start tag' and  
             $permitted_slash_tag_name->{$self->{current_token}->{tag_name}}) {  
           # permitted slash  
           #  
         } else {  
           !!!parse-error (type => 'nestc');  
         }  
         $self->{state} = 'before attribute name';  
         # next-input-character is already done  
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'unclosed tag');  
         $before_leave->();  
         if ($self->{current_token}->{type} eq 'start tag') {  
           $self->{last_emitted_start_tag_name} = $self->{current_token}->{tag_name};  
         } elsif ($self->{current_token}->{type} eq 'end tag') {  
           $self->{content_model_flag} = 'PCDATA'; # MUST  
           if ($self->{current_token}->{attributes}) {  
             !!!parse-error (type => 'end tag attribute');  
           }  
         } else {  
           die "$0: $self->{current_token}->{type}: Unknown token type";  
         }  
         $self->{state} = 'data';  
         # reconsume  
   
         !!!emit ($self->{current_token}); # start tag or end tag  
         undef $self->{current_token};  
   
         redo A;  
       } else {  
         $self->{current_attribute}->{name} .= chr ($self->{next_input_character});  
         ## Stay in the state  
         !!!next-input-character;  
         redo A;  
       }  
     } elsif ($self->{state} eq 'after attribute name') {  
       if ($self->{next_input_character} == 0x0009 or # HT  
           $self->{next_input_character} == 0x000A or # LF  
           $self->{next_input_character} == 0x000B or # VT  
           $self->{next_input_character} == 0x000C or # FF  
           $self->{next_input_character} == 0x0020) { # SP  
         ## Stay in the state  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x003D) { # =  
         $self->{state} = 'before attribute value';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x003E) { # >  
         if ($self->{current_token}->{type} eq 'start tag') {  
           $self->{last_emitted_start_tag_name} = $self->{current_token}->{tag_name};  
         } elsif ($self->{current_token}->{type} eq 'end tag') {  
           $self->{content_model_flag} = 'PCDATA'; # MUST  
           if ($self->{current_token}->{attributes}) {  
             !!!parse-error (type => 'end tag attribute');  
           }  
         } else {  
           die "$0: $self->{current_token}->{type}: Unknown token type";  
         }  
         $self->{state} = 'data';  
         !!!next-input-character;  
   
         !!!emit ($self->{current_token}); # start tag or end tag  
         undef $self->{current_token};  
   
         redo A;  
       } elsif (0x0041 <= $self->{next_input_character} and  
                $self->{next_input_character} <= 0x005A) { # A..Z  
         $self->{current_attribute} = {name => chr ($self->{next_input_character} + 0x0020),  
                               value => ''};  
         $self->{state} = 'attribute name';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x002F) { # /  
         !!!next-input-character;  
         if ($self->{next_input_character} == 0x003E and # >  
             $self->{current_token}->{type} eq 'start tag' and  
             $permitted_slash_tag_name->{$self->{current_token}->{tag_name}}) {  
           # permitted slash  
           #  
         } else {  
           !!!parse-error (type => 'nestc');  
         }  
         $self->{state} = 'before attribute name';  
         # next-input-character is already done  
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'unclosed tag');  
         if ($self->{current_token}->{type} eq 'start tag') {  
           $self->{last_emitted_start_tag_name} = $self->{current_token}->{tag_name};  
         } elsif ($self->{current_token}->{type} eq 'end tag') {  
           $self->{content_model_flag} = 'PCDATA'; # MUST  
           if ($self->{current_token}->{attributes}) {  
             !!!parse-error (type => 'end tag attribute');  
           }  
         } else {  
           die "$0: $self->{current_token}->{type}: Unknown token type";  
         }  
         $self->{state} = 'data';  
         # reconsume  
   
         !!!emit ($self->{current_token}); # start tag or end tag  
         undef $self->{current_token};  
   
         redo A;  
       } else {  
         $self->{current_attribute} = {name => chr ($self->{next_input_character}),  
                               value => ''};  
         $self->{state} = 'attribute name';  
         !!!next-input-character;  
         redo A;          
       }  
     } elsif ($self->{state} eq 'before attribute value') {  
       if ($self->{next_input_character} == 0x0009 or # HT  
           $self->{next_input_character} == 0x000A or # LF  
           $self->{next_input_character} == 0x000B or # VT  
           $self->{next_input_character} == 0x000C or # FF  
           $self->{next_input_character} == 0x0020) { # SP        
         ## Stay in the state  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x0022) { # "  
         $self->{state} = 'attribute value (double-quoted)';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x0026) { # &  
         $self->{state} = 'attribute value (unquoted)';  
         ## reconsume  
         redo A;  
       } elsif ($self->{next_input_character} == 0x0027) { # '  
         $self->{state} = 'attribute value (single-quoted)';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x003E) { # >  
         if ($self->{current_token}->{type} eq 'start tag') {  
           $self->{last_emitted_start_tag_name} = $self->{current_token}->{tag_name};  
         } elsif ($self->{current_token}->{type} eq 'end tag') {  
           $self->{content_model_flag} = 'PCDATA'; # MUST  
           if ($self->{current_token}->{attributes}) {  
             !!!parse-error (type => 'end tag attribute');  
           }  
         } else {  
           die "$0: $self->{current_token}->{type}: Unknown token type";  
         }  
         $self->{state} = 'data';  
         !!!next-input-character;  
   
         !!!emit ($self->{current_token}); # start tag or end tag  
         undef $self->{current_token};  
   
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'unclosed tag');  
         if ($self->{current_token}->{type} eq 'start tag') {  
           $self->{last_emitted_start_tag_name} = $self->{current_token}->{tag_name};  
         } elsif ($self->{current_token}->{type} eq 'end tag') {  
           $self->{content_model_flag} = 'PCDATA'; # MUST  
           if ($self->{current_token}->{attributes}) {  
             !!!parse-error (type => 'end tag attribute');  
           }  
         } else {  
           die "$0: $self->{current_token}->{type}: Unknown token type";  
         }  
         $self->{state} = 'data';  
         ## reconsume  
   
         !!!emit ($self->{current_token}); # start tag or end tag  
         undef $self->{current_token};  
   
         redo A;  
       } else {  
         $self->{current_attribute}->{value} .= chr ($self->{next_input_character});  
         $self->{state} = 'attribute value (unquoted)';  
         !!!next-input-character;  
         redo A;  
       }  
     } elsif ($self->{state} eq 'attribute value (double-quoted)') {  
       if ($self->{next_input_character} == 0x0022) { # "  
         $self->{state} = 'before attribute name';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x0026) { # &  
         $self->{last_attribute_value_state} = 'attribute value (double-quoted)';  
         $self->{state} = 'entity in attribute value';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'unclosed attribute value');  
         if ($self->{current_token}->{type} eq 'start tag') {  
           $self->{last_emitted_start_tag_name} = $self->{current_token}->{tag_name};  
         } elsif ($self->{current_token}->{type} eq 'end tag') {  
           $self->{content_model_flag} = 'PCDATA'; # MUST  
           if ($self->{current_token}->{attributes}) {  
             !!!parse-error (type => 'end tag attribute');  
           }  
         } else {  
           die "$0: $self->{current_token}->{type}: Unknown token type";  
         }  
         $self->{state} = 'data';  
         ## reconsume  
   
         !!!emit ($self->{current_token}); # start tag or end tag  
         undef $self->{current_token};  
   
         redo A;  
       } else {  
         $self->{current_attribute}->{value} .= chr ($self->{next_input_character});  
         ## Stay in the state  
         !!!next-input-character;  
         redo A;  
       }  
     } elsif ($self->{state} eq 'attribute value (single-quoted)') {  
       if ($self->{next_input_character} == 0x0027) { # '  
         $self->{state} = 'before attribute name';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x0026) { # &  
         $self->{last_attribute_value_state} = 'attribute value (single-quoted)';  
         $self->{state} = 'entity in attribute value';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'unclosed attribute value');  
         if ($self->{current_token}->{type} eq 'start tag') {  
           $self->{last_emitted_start_tag_name} = $self->{current_token}->{tag_name};  
         } elsif ($self->{current_token}->{type} eq 'end tag') {  
           $self->{content_model_flag} = 'PCDATA'; # MUST  
           if ($self->{current_token}->{attributes}) {  
             !!!parse-error (type => 'end tag attribute');  
           }  
         } else {  
           die "$0: $self->{current_token}->{type}: Unknown token type";  
         }  
         $self->{state} = 'data';  
         ## reconsume  
   
         !!!emit ($self->{current_token}); # start tag or end tag  
         undef $self->{current_token};  
475    
476          redo A;      ## Step 7: default
477        } else {      ## TODO: Make this configurable.
478          $self->{current_attribute}->{value} .= chr ($self->{next_input_character});      $charset = Message::Charset::Info->get_by_html_name ('windows-1252');
479          ## Stay in the state          ## NOTE: We choose |windows-1252| here, since |utf-8| should be
480          !!!next-input-character;          ## detectable in the step 6.
481          redo A;      require Whatpm::Charset::DecodeHandle;
482        }      $buffer = Whatpm::Charset::DecodeHandle::ByteBuffer->new
483      } elsif ($self->{state} eq 'attribute value (unquoted)') {          ($byte_stream);
484        if ($self->{next_input_character} == 0x0009 or # HT      ($char_stream, $e_status)
485            $self->{next_input_character} == 0x000A or # LF          = $charset->get_decode_handle ($buffer,
486            $self->{next_input_character} == 0x000B or # HT                                         allow_error_reporting => 1,
487            $self->{next_input_character} == 0x000C or # FF                                         allow_fallback => 1,
488            $self->{next_input_character} == 0x0020) { # SP                                         byte_buffer => \$byte_buffer);
489          $self->{state} = 'before attribute name';      $buffer->{buffer} = $byte_buffer;
490          !!!next-input-character;      !!!parse-error (type => 'sniffing:default',
491          redo A;                      text => 'windows-1252',
492        } elsif ($self->{next_input_character} == 0x0026) { # &                      level => $self->{level}->{info},
493          $self->{last_attribute_value_state} = 'attribute value (unquoted)';                      line => 1, column => 1,
494          $self->{state} = 'entity in attribute value';                      layer => 'encode');
495          !!!next-input-character;      $self->{confident} = 0;
496          redo A;    } # SNIFFING
497        } elsif ($self->{next_input_character} == 0x003E) { # >  
498          if ($self->{current_token}->{type} eq 'start tag') {    if ($e_status & Message::Charset::Info::FALLBACK_ENCODING_IMPL ()) {
499            $self->{last_emitted_start_tag_name} = $self->{current_token}->{tag_name};      $self->{input_encoding} = $charset->get_iana_name; ## TODO: Should we set actual charset decoder's encoding name?
500          } elsif ($self->{current_token}->{type} eq 'end tag') {      !!!parse-error (type => 'chardecode:fallback',
501            $self->{content_model_flag} = 'PCDATA'; # MUST                      #text => $self->{input_encoding},
502            if ($self->{current_token}->{attributes}) {                      level => $self->{level}->{uncertain},
503              !!!parse-error (type => 'end tag attribute');                      line => 1, column => 1,
504            }                      layer => 'encode');
505          } else {    } elsif (not ($e_status &
506            die "$0: $self->{current_token}->{type}: Unknown token type";                  Message::Charset::Info::ERROR_REPORTING_ENCODING_IMPL ())) {
507          }      $self->{input_encoding} = $charset->get_iana_name;
508          $self->{state} = 'data';      !!!parse-error (type => 'chardecode:no error',
509          !!!next-input-character;                      text => $self->{input_encoding},
510                        level => $self->{level}->{uncertain},
511          !!!emit ($self->{current_token}); # start tag or end tag                      line => 1, column => 1,
512          undef $self->{current_token};                      layer => 'encode');
513      } else {
514          redo A;      $self->{input_encoding} = $charset->get_iana_name;
515        } elsif ($self->{next_input_character} == -1) {    }
         !!!parse-error (type => 'unclosed tag');  
         if ($self->{current_token}->{type} eq 'start tag') {  
           $self->{last_emitted_start_tag_name} = $self->{current_token}->{tag_name};  
         } elsif ($self->{current_token}->{type} eq 'end tag') {  
           $self->{content_model_flag} = 'PCDATA'; # MUST  
           if ($self->{current_token}->{attributes}) {  
             !!!parse-error (type => 'end tag attribute');  
           }  
         } else {  
           die "$0: $self->{current_token}->{type}: Unknown token type";  
         }  
         $self->{state} = 'data';  
         ## reconsume  
516    
517          !!!emit ($self->{current_token}); # start tag or end tag    $self->{change_encoding} = sub {
518          undef $self->{current_token};      my $self = shift;
519        $charset_name = shift;
520        my $token = shift;
521    
522          redo A;      $charset = Message::Charset::Info->get_by_html_name ($charset_name);
523        } else {      ($char_stream, $e_status) = $charset->get_decode_handle
524          $self->{current_attribute}->{value} .= chr ($self->{next_input_character});          ($byte_stream, allow_error_reporting => 1, allow_fallback => 1,
525          ## Stay in the state           byte_buffer => \ $buffer->{buffer});
526          !!!next-input-character;      
527          redo A;      if ($char_stream) { # if supported
528          ## "Change the encoding" algorithm:
529          
530          ## Step 1
531          if (defined $self->{input_encoding} and
532              $self->{input_encoding} eq $charset_name) {
533            !!!parse-error (type => 'charset label:matching',
534                            text => $charset_name,
535                            level => $self->{level}->{info});
536            $self->{confident} = 1;
537            return;
538        }        }
     } elsif ($self->{state} eq 'entity in attribute value') {  
       my $token = $self->_tokenize_attempt_to_consume_an_entity;  
539    
540        unless (defined $token) {        ## Step 2 (HTML5 revision 3205)
541          $self->{current_attribute}->{value} .= '&';        if (defined $self->{input_encoding} and
542        } else {            Message::Charset::Info->get_by_html_name ($self->{input_encoding})
543          $self->{current_attribute}->{value} .= $token->{data};            ->{category} & Message::Charset::Info::CHARSET_CATEGORY_UTF16 ()) {
544          ## ISSUE: spec says "append the returned character token to the current attribute's value"          $self->{confident} = 1;
545            return;
546        }        }
547    
548        $self->{state} = $self->{last_attribute_value_state};        ## Step 3
549        # next-input-character is already done        if ($charset->{category} &
550        redo A;            Message::Charset::Info::CHARSET_CATEGORY_UTF16 ()) {
551      } elsif ($self->{state} eq 'bogus comment') {          $charset = Message::Charset::Info->get_by_html_name ('utf-8');
552        ## (only happen if PCDATA state)          ($char_stream, $e_status) = $charset->get_decode_handle
553                      ($byte_stream,
554        my $token = {type => 'comment', data => ''};               byte_buffer => \ $buffer->{buffer});
555          }
556        BC: {        $charset_name = $charset->get_iana_name;
557          if ($self->{next_input_character} == 0x003E) { # >  
558            $self->{state} = 'data';        !!!parse-error (type => 'charset label detected',
559            !!!next-input-character;                        text => $self->{input_encoding},
560                          value => $charset_name,
561            !!!emit ($token);                        level => $self->{level}->{warn},
562                          token => $token);
           redo A;  
         } elsif ($self->{next_input_character} == -1) {  
           $self->{state} = 'data';  
           ## reconsume  
   
           !!!emit ($token);  
   
           redo A;  
         } else {  
           $token->{data} .= chr ($self->{next_input_character});  
           !!!next-input-character;  
           redo BC;  
         }  
       } # BC  
     } elsif ($self->{state} eq 'markup declaration open') {  
       ## (only happen if PCDATA state)  
   
       my @next_char;  
       push @next_char, $self->{next_input_character};  
563                
564        if ($self->{next_input_character} == 0x002D) { # -        ## Step 4
565          !!!next-input-character;        # if (can) {
566          push @next_char, $self->{next_input_character};          ## change the encoding on the fly.
567          if ($self->{next_input_character} == 0x002D) { # -          #$self->{confident} = 1;
568            $self->{current_token} = {type => 'comment', data => ''};          #return;
569            $self->{state} = 'comment';        # }
           !!!next-input-character;  
           redo A;  
         }  
       } elsif ($self->{next_input_character} == 0x0044 or # D  
                $self->{next_input_character} == 0x0064) { # d  
         !!!next-input-character;  
         push @next_char, $self->{next_input_character};  
         if ($self->{next_input_character} == 0x004F or # O  
             $self->{next_input_character} == 0x006F) { # o  
           !!!next-input-character;  
           push @next_char, $self->{next_input_character};  
           if ($self->{next_input_character} == 0x0043 or # C  
               $self->{next_input_character} == 0x0063) { # c  
             !!!next-input-character;  
             push @next_char, $self->{next_input_character};  
             if ($self->{next_input_character} == 0x0054 or # T  
                 $self->{next_input_character} == 0x0074) { # t  
               !!!next-input-character;  
               push @next_char, $self->{next_input_character};  
               if ($self->{next_input_character} == 0x0059 or # Y  
                   $self->{next_input_character} == 0x0079) { # y  
                 !!!next-input-character;  
                 push @next_char, $self->{next_input_character};  
                 if ($self->{next_input_character} == 0x0050 or # P  
                     $self->{next_input_character} == 0x0070) { # p  
                   !!!next-input-character;  
                   push @next_char, $self->{next_input_character};  
                   if ($self->{next_input_character} == 0x0045 or # E  
                       $self->{next_input_character} == 0x0065) { # e  
                     ## ISSUE: What a stupid code this is!  
                     $self->{state} = 'DOCTYPE';  
                     !!!next-input-character;  
                     redo A;  
                   }  
                 }  
               }  
             }  
           }  
         }  
       }  
   
       !!!parse-error (type => 'bogus comment open');  
       $self->{next_input_character} = shift @next_char;  
       !!!back-next-input-character (@next_char);  
       $self->{state} = 'bogus comment';  
       redo A;  
570                
571        ## ISSUE: typos in spec: chacacters, is is a parse error        ## Step 5
572        ## ISSUE: spec is somewhat unclear on "is the first character that will be in the comment"; what is "that will be in the comment" is what the algorithm defines, isn't it?        throw Whatpm::HTML::RestartParser ();
573      } elsif ($self->{state} eq 'comment') {      }
574        if ($self->{next_input_character} == 0x002D) { # -    }; # $self->{change_encoding}
         $self->{state} = 'comment dash';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'unclosed comment');  
         $self->{state} = 'data';  
         ## reconsume  
   
         !!!emit ($self->{current_token}); # comment  
         undef $self->{current_token};  
   
         redo A;  
       } else {  
         $self->{current_token}->{data} .= chr ($self->{next_input_character}); # comment  
         ## Stay in the state  
         !!!next-input-character;  
         redo A;  
       }  
     } elsif ($self->{state} eq 'comment dash') {  
       if ($self->{next_input_character} == 0x002D) { # -  
         $self->{state} = 'comment end';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'unclosed comment');  
         $self->{state} = 'data';  
         ## reconsume  
   
         !!!emit ($self->{current_token}); # comment  
         undef $self->{current_token};  
   
         redo A;  
       } else {  
         $self->{current_token}->{data} .= '-' . chr ($self->{next_input_character}); # comment  
         $self->{state} = 'comment';  
         !!!next-input-character;  
         redo A;  
       }  
     } elsif ($self->{state} eq 'comment end') {  
       if ($self->{next_input_character} == 0x003E) { # >  
         $self->{state} = 'data';  
         !!!next-input-character;  
   
         !!!emit ($self->{current_token}); # comment  
         undef $self->{current_token};  
   
         redo A;  
       } elsif ($self->{next_input_character} == 0x002D) { # -  
         !!!parse-error (type => 'dash in comment');  
         $self->{current_token}->{data} .= '-'; # comment  
         ## Stay in the state  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'unclosed comment');  
         $self->{state} = 'data';  
         ## reconsume  
575    
576          !!!emit ($self->{current_token}); # comment    my $char_onerror = sub {
577          undef $self->{current_token};      my (undef, $type, %opt) = @_;
578        !!!parse-error (layer => 'encode',
579                        line => $self->{line}, column => $self->{column} + 1,
580                        %opt, type => $type);
581        if ($opt{octets}) {
582          ${$opt{octets}} = "\x{FFFD}"; # relacement character
583        }
584      };
585    
586          redo A;    my $wrapped_char_stream = $get_wrapper->($char_stream);
587        } else {    $wrapped_char_stream->onerror ($char_onerror);
         !!!parse-error (type => 'dash in comment');  
         $self->{current_token}->{data} .= '--' . chr ($self->{next_input_character}); # comment  
         $self->{state} = 'comment';  
         !!!next-input-character;  
         redo A;  
       }  
     } elsif ($self->{state} eq 'DOCTYPE') {  
       if ($self->{next_input_character} == 0x0009 or # HT  
           $self->{next_input_character} == 0x000A or # LF  
           $self->{next_input_character} == 0x000B or # VT  
           $self->{next_input_character} == 0x000C or # FF  
           $self->{next_input_character} == 0x0020) { # SP  
         $self->{state} = 'before DOCTYPE name';  
         !!!next-input-character;  
         redo A;  
       } else {  
         !!!parse-error (type => 'no space before DOCTYPE name');  
         $self->{state} = 'before DOCTYPE name';  
         ## reconsume  
         redo A;  
       }  
     } elsif ($self->{state} eq 'before DOCTYPE name') {  
       if ($self->{next_input_character} == 0x0009 or # HT  
           $self->{next_input_character} == 0x000A or # LF  
           $self->{next_input_character} == 0x000B or # VT  
           $self->{next_input_character} == 0x000C or # FF  
           $self->{next_input_character} == 0x0020) { # SP  
         ## Stay in the state  
         !!!next-input-character;  
         redo A;  
       } elsif (0x0061 <= $self->{next_input_character} and  
                $self->{next_input_character} <= 0x007A) { # a..z  
 ## ISSUE: "Set the token's name name to the" in the spec  
         $self->{current_token} = {type => 'DOCTYPE',  
                           name => chr ($self->{next_input_character} - 0x0020),  
                           error => 1};  
         $self->{state} = 'DOCTYPE name';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x003E) { # >  
         !!!parse-error (type => 'no DOCTYPE name');  
         $self->{state} = 'data';  
         !!!next-input-character;  
   
         !!!emit ({type => 'DOCTYPE', name => '', error => 1});  
   
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'no DOCTYPE name');  
         $self->{state} = 'data';  
         ## reconsume  
588    
589          !!!emit ({type => 'DOCTYPE', name => '', error => 1});    my @args = ($_[1], $_[2]); # $doc, $onerror - $get_wrapper = undef;
590      my $return;
591      try {
592        $return = $self->parse_char_stream ($wrapped_char_stream, @args);  
593      } catch Whatpm::HTML::RestartParser with {
594        ## NOTE: Invoked after {change_encoding}.
595    
596        if ($e_status & Message::Charset::Info::FALLBACK_ENCODING_IMPL ()) {
597          $self->{input_encoding} = $charset->get_iana_name; ## TODO: Should we set actual charset decoder's encoding name?
598          !!!parse-error (type => 'chardecode:fallback',
599                          level => $self->{level}->{uncertain},
600                          #text => $self->{input_encoding},
601                          line => 1, column => 1,
602                          layer => 'encode');
603        } elsif (not ($e_status &
604                      Message::Charset::Info::ERROR_REPORTING_ENCODING_IMPL ())) {
605          $self->{input_encoding} = $charset->get_iana_name;
606          !!!parse-error (type => 'chardecode:no error',
607                          text => $self->{input_encoding},
608                          level => $self->{level}->{uncertain},
609                          line => 1, column => 1,
610                          layer => 'encode');
611        } else {
612          $self->{input_encoding} = $charset->get_iana_name;
613        }
614        $self->{confident} = 1;
615    
616          redo A;      $wrapped_char_stream = $get_wrapper->($char_stream);
617        } else {      $wrapped_char_stream->onerror ($char_onerror);
         $self->{current_token} = {type => 'DOCTYPE',  
                           name => chr ($self->{next_input_character}),  
                           error => 1};  
 ## ISSUE: "Set the token's name name to the" in the spec  
         $self->{state} = 'DOCTYPE name';  
         !!!next-input-character;  
         redo A;  
       }  
     } elsif ($self->{state} eq 'DOCTYPE name') {  
       if ($self->{next_input_character} == 0x0009 or # HT  
           $self->{next_input_character} == 0x000A or # LF  
           $self->{next_input_character} == 0x000B or # VT  
           $self->{next_input_character} == 0x000C or # FF  
           $self->{next_input_character} == 0x0020) { # SP  
         $self->{current_token}->{error} = ($self->{current_token}->{name} ne 'HTML'); # DOCTYPE  
         $self->{state} = 'after DOCTYPE name';  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x003E) { # >  
         $self->{current_token}->{error} = ($self->{current_token}->{name} ne 'HTML'); # DOCTYPE  
         $self->{state} = 'data';  
         !!!next-input-character;  
   
         !!!emit ($self->{current_token}); # DOCTYPE  
         undef $self->{current_token};  
   
         redo A;  
       } elsif (0x0061 <= $self->{next_input_character} and  
                $self->{next_input_character} <= 0x007A) { # a..z  
         $self->{current_token}->{name} .= chr ($self->{next_input_character} - 0x0020); # DOCTYPE  
         #$self->{current_token}->{error} = ($self->{current_token}->{name} ne 'HTML');  
         ## Stay in the state  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'unclosed DOCTYPE');  
         $self->{current_token}->{error} = ($self->{current_token}->{name} ne 'HTML'); # DOCTYPE  
         $self->{state} = 'data';  
         ## reconsume  
618    
619          !!!emit ($self->{current_token});      $return = $self->parse_char_stream ($wrapped_char_stream, @args);
620          undef $self->{current_token};    };
621      return $return;
622    } # parse_byte_stream
623    
624          redo A;  ## NOTE: HTML5 spec says that the encoding layer MUST NOT strip BOM
625        } else {  ## and the HTML layer MUST ignore it.  However, we does strip BOM in
626          $self->{current_token}->{name}  ## the encoding layer and the HTML layer does not ignore any U+FEFF,
627            .= chr ($self->{next_input_character}); # DOCTYPE  ## because the core part of our HTML parser expects a string of character,
628          #$self->{current_token}->{error} = ($self->{current_token}->{name} ne 'HTML');  ## not a string of bytes or code units or anything which might contain a BOM.
629          ## Stay in the state  ## Therefore, any parser interface that accepts a string of bytes,
630          !!!next-input-character;  ## such as |parse_byte_string| in this module, must ensure that it does
631          redo A;  ## strip the BOM and never strip any ZWNBSP.
       }  
     } elsif ($self->{state} eq 'after DOCTYPE name') {  
       if ($self->{next_input_character} == 0x0009 or # HT  
           $self->{next_input_character} == 0x000A or # LF  
           $self->{next_input_character} == 0x000B or # VT  
           $self->{next_input_character} == 0x000C or # FF  
           $self->{next_input_character} == 0x0020) { # SP  
         ## Stay in the state  
         !!!next-input-character;  
         redo A;  
       } elsif ($self->{next_input_character} == 0x003E) { # >  
         $self->{state} = 'data';  
         !!!next-input-character;  
   
         !!!emit ($self->{current_token}); # DOCTYPE  
         undef $self->{current_token};  
   
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'unclosed DOCTYPE');  
         $self->{state} = 'data';  
         ## reconsume  
632    
633          !!!emit ($self->{current_token}); # DOCTYPE  sub parse_char_string ($$$;$$) {
634          undef $self->{current_token};    #my ($self, $s, $doc, $onerror, $get_wrapper) = @_;
635      my $self = shift;
636      my $s = ref $_[0] ? $_[0] : \($_[0]);
637      require Whatpm::Charset::DecodeHandle;
638      my $input = Whatpm::Charset::DecodeHandle::CharString->new ($s);
639      return $self->parse_char_stream ($input, @_[1..$#_]);
640    } # parse_char_string
641    *parse_string = \&parse_char_string; ## NOTE: Alias for backward compatibility.
642    
643    sub parse_char_stream ($$$;$$) {
644      my $self = ref $_[0] ? shift : shift->new;
645      my $input = $_[0];
646      $self->{document} = $_[1];
647      @{$self->{document}->child_nodes} = ();
648    
649          redo A;    ## NOTE: |set_inner_html| copies most of this method's code
       } else {  
         !!!parse-error (type => 'string after DOCTYPE name');  
         $self->{current_token}->{error} = 1; # DOCTYPE  
         $self->{state} = 'bogus DOCTYPE';  
         !!!next-input-character;  
         redo A;  
       }  
     } elsif ($self->{state} eq 'bogus DOCTYPE') {  
       if ($self->{next_input_character} == 0x003E) { # >  
         $self->{state} = 'data';  
         !!!next-input-character;  
   
         !!!emit ($self->{current_token}); # DOCTYPE  
         undef $self->{current_token};  
   
         redo A;  
       } elsif ($self->{next_input_character} == -1) {  
         !!!parse-error (type => 'unclosed DOCTYPE');  
         $self->{state} = 'data';  
         ## reconsume  
650    
651          !!!emit ($self->{current_token}); # DOCTYPE    $self->{confident} = 1 unless exists $self->{confident};
652          undef $self->{current_token};    $self->{document}->input_encoding ($self->{input_encoding})
653          if defined $self->{input_encoding};
654    ## TODO: |{input_encoding}| is needless?
655    
656      $self->{line_prev} = $self->{line} = 1;
657      $self->{column_prev} = -1;
658      $self->{column} = 0;
659      $self->{set_nc} = sub {
660        my $self = shift;
661    
662          redo A;      my $char = '';
663        } else {      if (defined $self->{next_nc}) {
664          ## Stay in the state        $char = $self->{next_nc};
665          !!!next-input-character;        delete $self->{next_nc};
666          redo A;        $self->{nc} = ord $char;
       }  
667      } else {      } else {
668        die "$0: $self->{state}: Unknown state";        $self->{char_buffer} = '';
669      }        $self->{char_buffer_pos} = 0;
   } # A    
670    
671    die "$0: _get_next_token: unexpected case";        my $count = $input->manakai_read_until
672  } # _get_next_token           ($self->{char_buffer}, qr/[^\x00\x0A\x0D]/, $self->{char_buffer_pos});
673          if ($count) {
674  sub _tokenize_attempt_to_consume_an_entity ($) {          $self->{line_prev} = $self->{line};
675    my $self = shift;          $self->{column_prev} = $self->{column};
676              $self->{column}++;
677    if ($self->{next_input_character} == 0x0023) { # #          $self->{nc}
678      !!!next-input-character;              = ord substr ($self->{char_buffer}, $self->{char_buffer_pos}++, 1);
679      if ($self->{next_input_character} == 0x0078 or # x          return;
         $self->{next_input_character} == 0x0058) { # X  
       my $num;  
       X: {  
         my $x_char = $self->{next_input_character};  
         !!!next-input-character;  
         if (0x0030 <= $self->{next_input_character} and  
             $self->{next_input_character} <= 0x0039) { # 0..9  
           $num ||= 0;  
           $num *= 0x10;  
           $num += $self->{next_input_character} - 0x0030;  
           redo X;  
         } elsif (0x0061 <= $self->{next_input_character} and  
                  $self->{next_input_character} <= 0x0066) { # a..f  
           ## ISSUE: the spec says U+0078, which is apparently incorrect  
           $num ||= 0;  
           $num *= 0x10;  
           $num += $self->{next_input_character} - 0x0060 + 9;  
           redo X;  
         } elsif (0x0041 <= $self->{next_input_character} and  
                  $self->{next_input_character} <= 0x0046) { # A..F  
           ## ISSUE: the spec says U+0058, which is apparently incorrect  
           $num ||= 0;  
           $num *= 0x10;  
           $num += $self->{next_input_character} - 0x0040 + 9;  
           redo X;  
         } elsif (not defined $num) { # no hexadecimal digit  
           !!!parse-error (type => 'bare hcro');  
           $self->{next_input_character} = 0x0023; # #  
           !!!back-next-input-character ($x_char);  
           return undef;  
         } elsif ($self->{next_input_character} == 0x003B) { # ;  
           !!!next-input-character;  
         } else {  
           !!!parse-error (type => 'no refc');  
         }  
   
         ## TODO: check the definition for |a valid Unicode character|.  
         ## <http://lists.whatwg.org/pipermail/whatwg-whatwg.org/2006-December/thread.html#8189>  
         if ($num > 1114111 or $num == 0) {  
           $num = 0xFFFD; # REPLACEMENT CHARACTER  
           ## ISSUE: Why this is not an error?  
         } elsif (0x80 <= $num and $num <= 0x9F) {  
           !!!parse-error (type => sprintf 'c1 entity:U+%04X', $num);  
           $num = $c1_entity_char->{$num};  
         }  
   
         return {type => 'character', data => chr $num};  
       } # X  
     } elsif (0x0030 <= $self->{next_input_character} and  
              $self->{next_input_character} <= 0x0039) { # 0..9  
       my $code = $self->{next_input_character} - 0x0030;  
       !!!next-input-character;  
         
       while (0x0030 <= $self->{next_input_character} and  
                 $self->{next_input_character} <= 0x0039) { # 0..9  
         $code *= 10;  
         $code += $self->{next_input_character} - 0x0030;  
           
         !!!next-input-character;  
680        }        }
681    
682        if ($self->{next_input_character} == 0x003B) { # ;        if ($input->read ($char, 1)) {
683          !!!next-input-character;          $self->{nc} = ord $char;
684        } else {        } else {
685          !!!parse-error (type => 'no refc');          $self->{nc} = -1;
686            return;
687        }        }
688        }
689    
690        ## TODO: check the definition for |a valid Unicode character|.      ($self->{line_prev}, $self->{column_prev})
691        if ($code > 1114111 or $code == 0) {          = ($self->{line}, $self->{column});
692          $code = 0xFFFD; # REPLACEMENT CHARACTER      $self->{column}++;
693          ## ISSUE: Why this is not an error?      
694        } elsif (0x80 <= $code and $code <= 0x9F) {      if ($self->{nc} == 0x000A) { # LF
695          !!!parse-error (type => sprintf 'c1 entity:U+%04X', $code);        !!!cp ('j1');
696          $code = $c1_entity_char->{$code};        $self->{line}++;
697        }        $self->{column} = 0;
698              } elsif ($self->{nc} == 0x000D) { # CR
699        return {type => 'character', data => chr $code};        !!!cp ('j2');
700      } else {  ## TODO: support for abort/streaming
701        !!!parse-error (type => 'bare nero');        my $next = '';
702        !!!back-next-input-character ($self->{next_input_character});        if ($input->read ($next, 1) and $next ne "\x0A") {
703        $self->{next_input_character} = 0x0023; # #          $self->{next_nc} = $next;
704        return undef;        }
705          $self->{nc} = 0x000A; # LF # MUST
706          $self->{line}++;
707          $self->{column} = 0;
708        } elsif ($self->{nc} == 0x0000) { # NULL
709          !!!cp ('j4');
710          !!!parse-error (type => 'NULL');
711          $self->{nc} = 0xFFFD; # REPLACEMENT CHARACTER # MUST
712      }      }
713    } elsif ((0x0041 <= $self->{next_input_character} and    };
714              $self->{next_input_character} <= 0x005A) or  
715             (0x0061 <= $self->{next_input_character} and    $self->{read_until} = sub {
716              $self->{next_input_character} <= 0x007A)) {      #my ($scalar, $specials_range, $offset) = @_;
717      my $entity_name = chr $self->{next_input_character};      return 0 if defined $self->{next_nc};
718      !!!next-input-character;  
719        my $pattern = qr/[^$_[1]\x00\x0A\x0D]/;
720      my $value = $entity_name;      my $offset = $_[2] || 0;
721      my $match;  
722      require Whatpm::_NamedEntityList;      if ($self->{char_buffer_pos} < length $self->{char_buffer}) {
723      our $EntityChar;        pos ($self->{char_buffer}) = $self->{char_buffer_pos};
724          if ($self->{char_buffer} =~ /\G(?>$pattern)+/) {
725      while (length $entity_name < 10 and          substr ($_[0], $offset)
726             ## NOTE: Some number greater than the maximum length of entity name              = substr ($self->{char_buffer}, $-[0], $+[0] - $-[0]);
727             ((0x0041 <= $self->{next_input_character} and # a          my $count = $+[0] - $-[0];
728               $self->{next_input_character} <= 0x005A) or # x          if ($count) {
729              (0x0061 <= $self->{next_input_character} and # a            $self->{column} += $count;
730               $self->{next_input_character} <= 0x007A) or # z            $self->{char_buffer_pos} += $count;
731              (0x0030 <= $self->{next_input_character} and # 0            $self->{line_prev} = $self->{line};
732               $self->{next_input_character} <= 0x0039) or # 9            $self->{column_prev} = $self->{column} - 1;
733              $self->{next_input_character} == 0x003B)) { # ;            $self->{nc} = -1;
       $entity_name .= chr $self->{next_input_character};  
       if (defined $EntityChar->{$entity_name}) {  
         $value = $EntityChar->{$entity_name};  
         if ($self->{next_input_character} == 0x003B) { # ;  
           $match = 1;  
           !!!next-input-character;  
           last;  
         } else {  
           $match = -1;  
734          }          }
735            return $count;
736        } else {        } else {
737          $value .= chr $self->{next_input_character};          return 0;
738        }        }
       !!!next-input-character;  
     }  
       
     if ($match > 0) {  
       return {type => 'character', data => $value};  
     } elsif ($match < 0) {  
       !!!parse-error (type => 'refc');  
       return {type => 'character', data => $value};  
739      } else {      } else {
740        !!!parse-error (type => 'bare ero');        my $count = $input->manakai_read_until ($_[0], $pattern, $_[2]);
741        ## NOTE: No characters are consumed in the spec.        if ($count) {
742        !!!back-token ({type => 'character', data => $value});          $self->{column} += $count;
743        return undef;          $self->{line_prev} = $self->{line};
744            $self->{column_prev} = $self->{column} - 1;
745            $self->{nc} = -1;
746          }
747          return $count;
748      }      }
749      }; # $self->{read_until}
750    
751      my $onerror = $_[2] || sub {
752        my (%opt) = @_;
753        my $line = $opt{token} ? $opt{token}->{line} : $opt{line};
754        my $column = $opt{token} ? $opt{token}->{column} : $opt{column};
755        warn "Parse error ($opt{type}) at line $line column $column\n";
756      };
757      $self->{parse_error} = sub {
758        $onerror->(line => $self->{line}, column => $self->{column}, @_);
759      };
760    
761      my $char_onerror = sub {
762        my (undef, $type, %opt) = @_;
763        !!!parse-error (layer => 'encode',
764                        line => $self->{line}, column => $self->{column} + 1,
765                        %opt, type => $type);
766      }; # $char_onerror
767    
768      if ($_[3]) {
769        $input = $_[3]->($input);
770        $input->onerror ($char_onerror);
771    } else {    } else {
772      ## no characters are consumed      $input->onerror ($char_onerror) unless defined $input->onerror;
     !!!parse-error (type => 'bare ero');  
     return undef;  
773    }    }
774  } # _tokenize_attempt_to_consume_an_entity  
775      $self->_initialize_tokenizer;
776      $self->_initialize_tree_constructor;
777      $self->_construct_tree;
778      $self->_terminate_tree_constructor;
779    
780      delete $self->{parse_error}; # remove loop
781    
782      return $self->{document};
783    } # parse_char_stream
784    
785    sub new ($) {
786      my $class = shift;
787      my $self = bless {
788        level => {must => 'm',
789                  should => 's',
790                  warn => 'w',
791                  info => 'i',
792                  uncertain => 'u'},
793      }, $class;
794      $self->{set_nc} = sub {
795        $self->{nc} = -1;
796      };
797      $self->{parse_error} = sub {
798        #
799      };
800      $self->{change_encoding} = sub {
801        # if ($_[0] is a supported encoding) {
802        #   run "change the encoding" algorithm;
803        #   throw Whatpm::HTML::RestartParser (charset => $new_encoding);
804        # }
805      };
806      $self->{application_cache_selection} = sub {
807        #
808      };
809      return $self;
810    } # new
811    
812    ## Insertion modes
813    
814    sub AFTER_HTML_IMS () { 0b100 }
815    sub HEAD_IMS ()       { 0b1000 }
816    sub BODY_IMS ()       { 0b10000 }
817    sub BODY_TABLE_IMS () { 0b100000 }
818    sub TABLE_IMS ()      { 0b1000000 }
819    sub ROW_IMS ()        { 0b10000000 }
820    sub BODY_AFTER_IMS () { 0b100000000 }
821    sub FRAME_IMS ()      { 0b1000000000 }
822    sub SELECT_IMS ()     { 0b10000000000 }
823    #sub IN_FOREIGN_CONTENT_IM () { 0b100000000000 } # see Whatpm::HTML::Tokenizer
824        ## NOTE: "in foreign content" insertion mode is special; it is combined
825        ## with the secondary insertion mode.  In this parser, they are stored
826        ## together in the bit-or'ed form.
827    sub IN_CDATA_RCDATA_IM () { 0b1000000000000 }
828        ## NOTE: "in CDATA/RCDATA" insertion mode is also special; it is
829        ## combined with the original insertion mode.  In thie parser,
830        ## they are stored together in the bit-or'ed form.
831    
832    sub IM_MASK () { 0b11111111111 }
833    
834    ## NOTE: "initial" and "before html" insertion modes have no constants.
835    
836    ## NOTE: "after after body" insertion mode.
837    sub AFTER_HTML_BODY_IM () { AFTER_HTML_IMS | BODY_AFTER_IMS }
838    
839    ## NOTE: "after after frameset" insertion mode.
840    sub AFTER_HTML_FRAMESET_IM () { AFTER_HTML_IMS | FRAME_IMS }
841    
842    sub IN_HEAD_IM () { HEAD_IMS | 0b00 }
843    sub IN_HEAD_NOSCRIPT_IM () { HEAD_IMS | 0b01 }
844    sub AFTER_HEAD_IM () { HEAD_IMS | 0b10 }
845    sub BEFORE_HEAD_IM () { HEAD_IMS | 0b11 }
846    sub IN_BODY_IM () { BODY_IMS }
847    sub IN_CELL_IM () { BODY_IMS | BODY_TABLE_IMS | 0b01 }
848    sub IN_CAPTION_IM () { BODY_IMS | BODY_TABLE_IMS | 0b10 }
849    sub IN_ROW_IM () { TABLE_IMS | ROW_IMS | 0b01 }
850    sub IN_TABLE_BODY_IM () { TABLE_IMS | ROW_IMS | 0b10 }
851    sub IN_TABLE_IM () { TABLE_IMS }
852    sub AFTER_BODY_IM () { BODY_AFTER_IMS }
853    sub IN_FRAMESET_IM () { FRAME_IMS | 0b01 }
854    sub AFTER_FRAMESET_IM () { FRAME_IMS | 0b10 }
855    sub IN_SELECT_IM () { SELECT_IMS | 0b01 }
856    sub IN_SELECT_IN_TABLE_IM () { SELECT_IMS | 0b10 }
857    sub IN_COLUMN_GROUP_IM () { 0b10 }
858    
859  sub _initialize_tree_constructor ($) {  sub _initialize_tree_constructor ($) {
860    my $self = shift;    my $self = shift;
# Line 1395  sub _initialize_tree_constructor ($) { Line 862  sub _initialize_tree_constructor ($) {
862    $self->{document}->strict_error_checking (0);    $self->{document}->strict_error_checking (0);
863    ## TODO: Turn mutation events off # MUST    ## TODO: Turn mutation events off # MUST
864    ## TODO: Turn loose Document option (manakai extension) on    ## TODO: Turn loose Document option (manakai extension) on
865    ## TODO: Mark the Document as an HTML document # MUST    $self->{document}->manakai_is_html (1); # MUST
866      $self->{document}->set_user_data (manakai_source_line => 1);
867      $self->{document}->set_user_data (manakai_source_column => 1);
868  } # _initialize_tree_constructor  } # _initialize_tree_constructor
869    
870  sub _terminate_tree_constructor ($) {  sub _terminate_tree_constructor ($) {
# Line 1415  sub _construct_tree ($) { Line 884  sub _construct_tree ($) {
884    ## When an interactive UA render the $self->{document} available    ## When an interactive UA render the $self->{document} available
885    ## to the user, or when it begin accepting user input, are    ## to the user, or when it begin accepting user input, are
886    ## not defined.    ## not defined.
   
   ## Append a character: collect it and all subsequent consecutive  
   ## characters and insert one Text node whose data is concatenation  
   ## of all those characters. # MUST  
887        
888    !!!next-token;    !!!next-token;
889    
   $self->{insertion_mode} = 'before head';  
890    undef $self->{form_element};    undef $self->{form_element};
891    undef $self->{head_element};    undef $self->{head_element};
892      undef $self->{head_element_inserted};
893    $self->{open_elements} = [];    $self->{open_elements} = [];
894    undef $self->{inner_html_node};    undef $self->{inner_html_node};
895      undef $self->{ignore_newline};
896    
897      ## NOTE: The "initial" insertion mode.
898    $self->_tree_construction_initial; # MUST    $self->_tree_construction_initial; # MUST
899    
900      ## NOTE: The "before html" insertion mode.
901    $self->_tree_construction_root_element;    $self->_tree_construction_root_element;
902      $self->{insertion_mode} = BEFORE_HEAD_IM;
903    
904      ## NOTE: The "before head" insertion mode and so on.
905    $self->_tree_construction_main;    $self->_tree_construction_main;
906  } # _construct_tree  } # _construct_tree
907    
908  sub _tree_construction_initial ($) {  sub _tree_construction_initial ($) {
909    my $self = shift;    my $self = shift;
910    B: {  
911        if ($token->{type} eq 'DOCTYPE') {    ## NOTE: "initial" insertion mode
912          if ($token->{error}) {  
913            ## ISSUE: Spec currently left this case undefined.    INITIAL: {
914            !!!parse-error (type => 'bogus DOCTYPE');      if ($token->{type} == DOCTYPE_TOKEN) {
915          }        ## NOTE: Conformance checkers MAY, instead of reporting "not
916          my $doctype = $self->{document}->create_document_type_definition        ## HTML5" error, switch to a conformance checking mode for
917            ($token->{name});        ## another language.  (We don't support such mode switchings; it
918          $self->{document}->append_child ($doctype);        ## is nonsense to do anything different from what browsers do.)
919          #$phase = 'root element';        my $doctype_name = $token->{name};
920          !!!next-token;        $doctype_name = '' unless defined $doctype_name;
921          #redo B;        my $doctype = $self->{document}->create_document_type_definition
922          return;            ($doctype_name);
923        } elsif ({  
924                  comment => 1,        $doctype_name =~ tr/A-Z/a-z/; # ASCII case-insensitive
925                  'start tag' => 1,        if ($doctype_name ne 'html') {
926                  'end tag' => 1,          !!!cp ('t1');
927                  'end-of-file' => 1,          !!!parse-error (type => 'not HTML5', token => $token);
928                 }->{$token->{type}}) {        } elsif (defined $token->{pubid}) {
929          ## ISSUE: Spec currently left this case undefined.          !!!cp ('t2');
930          !!!parse-error (type => 'missing DOCTYPE');          ## XXX Obsolete permitted DOCTYPEs
931          #$phase = 'root element';          !!!parse-error (type => 'not HTML5', token => $token);
932          ## reprocess        } elsif (defined $token->{sysid}) {
933          #redo B;          if ($token->{sysid} eq 'about:legacy-compat') {
934          return;            !!!cp ('t1.2'); ## <!DOCTYPE HTML SYSTEM "about:legacy-compat">
935        } elsif ($token->{type} eq 'character') {            !!!parse-error (type => 'XSLT-compat', token => $token,
936          if ($token->{data} =~ s/^([\x09\x0A\x0B\x0C\x20]+)//) {                            level => $self->{level}->{should});
937            $self->{document}->manakai_append_text ($1);          } else {
938            ## ISSUE: DOM3 Core does not allow Document > Text            !!!parse-error (type => 'not HTML5', token => $token);
939            unless (length $token->{data}) {          }
940              ## Stay in the phase        } else { ## <!DOCTYPE HTML>
941              !!!next-token;          !!!cp ('t3');
942              redo B;          #
943          }
944          
945          ## NOTE: Default value for both |public_id| and |system_id| attributes
946          ## are empty strings, so that we don't set any value in missing cases.
947          $doctype->public_id ($token->{pubid}) if defined $token->{pubid};
948          $doctype->system_id ($token->{sysid}) if defined $token->{sysid};
949    
950          ## NOTE: Other DocumentType attributes are null or empty lists.
951          ## In Firefox3, |internalSubset| attribute is set to the empty
952          ## string, while |null| is an allowed value for the attribute
953          ## according to DOM3 Core.
954          $self->{document}->append_child ($doctype);
955          
956          if ($token->{quirks} or $doctype_name ne 'html') {
957            !!!cp ('t4');
958            $self->{document}->manakai_compat_mode ('quirks');
959          } elsif (defined $token->{pubid}) {
960            my $pubid = $token->{pubid};
961            $pubid =~ tr/a-z/A-z/;
962            my $prefix = [
963              "+//SILMARIL//DTD HTML PRO V0R11 19970101//",
964              "-//ADVASOFT LTD//DTD HTML 3.0 ASWEDIT + EXTENSIONS//",
965              "-//AS//DTD HTML 3.0 ASWEDIT + EXTENSIONS//",
966              "-//IETF//DTD HTML 2.0 LEVEL 1//",
967              "-//IETF//DTD HTML 2.0 LEVEL 2//",
968              "-//IETF//DTD HTML 2.0 STRICT LEVEL 1//",
969              "-//IETF//DTD HTML 2.0 STRICT LEVEL 2//",
970              "-//IETF//DTD HTML 2.0 STRICT//",
971              "-//IETF//DTD HTML 2.0//",
972              "-//IETF//DTD HTML 2.1E//",
973              "-//IETF//DTD HTML 3.0//",
974              "-//IETF//DTD HTML 3.2 FINAL//",
975              "-//IETF//DTD HTML 3.2//",
976              "-//IETF//DTD HTML 3//",
977              "-//IETF//DTD HTML LEVEL 0//",
978              "-//IETF//DTD HTML LEVEL 1//",
979              "-//IETF//DTD HTML LEVEL 2//",
980              "-//IETF//DTD HTML LEVEL 3//",
981              "-//IETF//DTD HTML STRICT LEVEL 0//",
982              "-//IETF//DTD HTML STRICT LEVEL 1//",
983              "-//IETF//DTD HTML STRICT LEVEL 2//",
984              "-//IETF//DTD HTML STRICT LEVEL 3//",
985              "-//IETF//DTD HTML STRICT//",
986              "-//IETF//DTD HTML//",
987              "-//METRIUS//DTD METRIUS PRESENTATIONAL//",
988              "-//MICROSOFT//DTD INTERNET EXPLORER 2.0 HTML STRICT//",
989              "-//MICROSOFT//DTD INTERNET EXPLORER 2.0 HTML//",
990              "-//MICROSOFT//DTD INTERNET EXPLORER 2.0 TABLES//",
991              "-//MICROSOFT//DTD INTERNET EXPLORER 3.0 HTML STRICT//",
992              "-//MICROSOFT//DTD INTERNET EXPLORER 3.0 HTML//",
993              "-//MICROSOFT//DTD INTERNET EXPLORER 3.0 TABLES//",
994              "-//NETSCAPE COMM. CORP.//DTD HTML//",
995              "-//NETSCAPE COMM. CORP.//DTD STRICT HTML//",
996              "-//O'REILLY AND ASSOCIATES//DTD HTML 2.0//",
997              "-//O'REILLY AND ASSOCIATES//DTD HTML EXTENDED 1.0//",
998              "-//O'REILLY AND ASSOCIATES//DTD HTML EXTENDED RELAXED 1.0//",
999              "-//SOFTQUAD SOFTWARE//DTD HOTMETAL PRO 6.0::19990601::EXTENSIONS TO HTML 4.0//",
1000              "-//SOFTQUAD//DTD HOTMETAL PRO 4.0::19971010::EXTENSIONS TO HTML 4.0//",
1001              "-//SPYGLASS//DTD HTML 2.0 EXTENDED//",
1002              "-//SQ//DTD HTML 2.0 HOTMETAL + EXTENSIONS//",
1003              "-//SUN MICROSYSTEMS CORP.//DTD HOTJAVA HTML//",
1004              "-//SUN MICROSYSTEMS CORP.//DTD HOTJAVA STRICT HTML//",
1005              "-//W3C//DTD HTML 3 1995-03-24//",
1006              "-//W3C//DTD HTML 3.2 DRAFT//",
1007              "-//W3C//DTD HTML 3.2 FINAL//",
1008              "-//W3C//DTD HTML 3.2//",
1009              "-//W3C//DTD HTML 3.2S DRAFT//",
1010              "-//W3C//DTD HTML 4.0 FRAMESET//",
1011              "-//W3C//DTD HTML 4.0 TRANSITIONAL//",
1012              "-//W3C//DTD HTML EXPERIMETNAL 19960712//",
1013              "-//W3C//DTD HTML EXPERIMENTAL 970421//",
1014              "-//W3C//DTD W3 HTML//",
1015              "-//W3O//DTD W3 HTML 3.0//",
1016              "-//WEBTECHS//DTD MOZILLA HTML 2.0//",
1017              "-//WEBTECHS//DTD MOZILLA HTML//",
1018            ]; # $prefix
1019            my $match;
1020            for (@$prefix) {
1021              if (substr ($prefix, 0, length $_) eq $_) {
1022                $match = 1;
1023                last;
1024              }
1025            }
1026            if ($match or
1027                $pubid eq "-//W3O//DTD W3 HTML STRICT 3.0//EN//" or
1028                $pubid eq "-/W3C/DTD HTML 4.0 TRANSITIONAL/EN" or
1029                $pubid eq "HTML") {
1030              !!!cp ('t5');
1031              $self->{document}->manakai_compat_mode ('quirks');
1032            } elsif ($pubid =~ m[^-//W3C//DTD HTML 4.01 FRAMESET//] or
1033                     $pubid =~ m[^-//W3C//DTD HTML 4.01 TRANSITIONAL//]) {
1034              if (defined $token->{sysid}) {
1035                !!!cp ('t6');
1036                $self->{document}->manakai_compat_mode ('quirks');
1037              } else {
1038                !!!cp ('t7');
1039                $self->{document}->manakai_compat_mode ('limited quirks');
1040            }            }
1041            } elsif ($pubid =~ m[^-//W3C//DTD XHTML 1.0 FRAMESET//] or
1042                     $pubid =~ m[^-//W3C//DTD XHTML 1.0 TRANSITIONAL//]) {
1043              !!!cp ('t8');
1044              $self->{document}->manakai_compat_mode ('limited quirks');
1045            } else {
1046              !!!cp ('t9');
1047            }
1048          } else {
1049            !!!cp ('t10');
1050          }
1051          if (defined $token->{sysid}) {
1052            my $sysid = $token->{sysid};
1053            $sysid =~ tr/A-Z/a-z/;
1054            if ($sysid eq "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd") {
1055              ## NOTE: Ensure that |PUBLIC "(limited quirks)" "(quirks)"| is
1056              ## marked as quirks.
1057              $self->{document}->manakai_compat_mode ('quirks');
1058              !!!cp ('t11');
1059            } else {
1060              !!!cp ('t12');
1061            }
1062          } else {
1063            !!!cp ('t13');
1064          }
1065          
1066          ## Go to the "before html" insertion mode.
1067          !!!next-token;
1068          return;
1069        } elsif ({
1070                  START_TAG_TOKEN, 1,
1071                  END_TAG_TOKEN, 1,
1072                  END_OF_FILE_TOKEN, 1,
1073                 }->{$token->{type}}) {
1074          !!!cp ('t14');
1075          !!!parse-error (type => 'no DOCTYPE', token => $token);
1076          $self->{document}->manakai_compat_mode ('quirks');
1077          ## Go to the "before html" insertion mode.
1078          ## reprocess
1079          !!!ack-later;
1080          return;
1081        } elsif ($token->{type} == CHARACTER_TOKEN) {
1082          if ($token->{data} =~ s/^([\x09\x0A\x0C\x20]+)//) {
1083            ## Ignore the token
1084    
1085            unless (length $token->{data}) {
1086              !!!cp ('t15');
1087              ## Stay in the insertion mode.
1088              !!!next-token;
1089              redo INITIAL;
1090            } else {
1091              !!!cp ('t16');
1092          }          }
         ## ISSUE: Spec currently left this case undefined.  
         !!!parse-error (type => 'missing DOCTYPE');  
         #$phase = 'root element';  
         ## reprocess  
         #redo B;  
         return;  
1093        } else {        } else {
1094          die "$0: $token->{type}: Unknown token";          !!!cp ('t17');
1095        }        }
1096      } # B  
1097          !!!parse-error (type => 'no DOCTYPE', token => $token);
1098          $self->{document}->manakai_compat_mode ('quirks');
1099          ## Go to the "before html" insertion mode.
1100          ## reprocess
1101          return;
1102        } elsif ($token->{type} == COMMENT_TOKEN) {
1103          !!!cp ('t18');
1104          my $comment = $self->{document}->create_comment ($token->{data});
1105          $self->{document}->append_child ($comment);
1106          
1107          ## Stay in the insertion mode.
1108          !!!next-token;
1109          redo INITIAL;
1110        } else {
1111          die "$0: $token->{type}: Unknown token type";
1112        }
1113      } # INITIAL
1114    
1115      die "$0: _tree_construction_initial: This should be never reached";
1116  } # _tree_construction_initial  } # _tree_construction_initial
1117    
1118  sub _tree_construction_root_element ($) {  sub _tree_construction_root_element ($) {
1119    my $self = shift;    my $self = shift;
1120    
1121      ## NOTE: "before html" insertion mode.
1122        
1123    B: {    B: {
1124        if ($token->{type} eq 'DOCTYPE') {        if ($token->{type} == DOCTYPE_TOKEN) {
1125          !!!parse-error (type => 'in html:#DOCTYPE');          !!!cp ('t19');
1126            !!!parse-error (type => 'in html:#DOCTYPE', token => $token);
1127          ## Ignore the token          ## Ignore the token
1128          ## Stay in the phase          ## Stay in the insertion mode.
1129          !!!next-token;          !!!next-token;
1130          redo B;          redo B;
1131        } elsif ($token->{type} eq 'comment') {        } elsif ($token->{type} == COMMENT_TOKEN) {
1132            !!!cp ('t20');
1133          my $comment = $self->{document}->create_comment ($token->{data});          my $comment = $self->{document}->create_comment ($token->{data});
1134          $self->{document}->append_child ($comment);          $self->{document}->append_child ($comment);
1135          ## Stay in the phase          ## Stay in the insertion mode.
1136          !!!next-token;          !!!next-token;
1137          redo B;          redo B;
1138        } elsif ($token->{type} eq 'character') {        } elsif ($token->{type} == CHARACTER_TOKEN) {
1139          if ($token->{data} =~ s/^([\x09\x0A\x0B\x0C\x20]+)//) {          if ($token->{data} =~ s/^([\x09\x0A\x0C\x20]+)//) {
1140            $self->{document}->manakai_append_text ($1);            ## Ignore the token.
1141            ## ISSUE: DOM3 Core does not allow Document > Text  
1142            unless (length $token->{data}) {            unless (length $token->{data}) {
1143              ## Stay in the phase              !!!cp ('t21');
1144                ## Stay in the insertion mode.
1145              !!!next-token;              !!!next-token;
1146              redo B;              redo B;
1147              } else {
1148                !!!cp ('t22');
1149            }            }
1150            } else {
1151              !!!cp ('t23');
1152          }          }
1153    
1154            $self->{application_cache_selection}->(undef);
1155    
1156          #          #
1157          } elsif ($token->{type} == START_TAG_TOKEN) {
1158            if ($token->{tag_name} eq 'html') {
1159              my $root_element;
1160              !!!create-element ($root_element, $HTML_NS, $token->{tag_name}, $token->{attributes}, $token);
1161              $self->{document}->append_child ($root_element);
1162              push @{$self->{open_elements}},
1163                  [$root_element, $el_category->{html}];
1164    
1165              if ($token->{attributes}->{manifest}) {
1166                !!!cp ('t24');
1167                $self->{application_cache_selection}
1168                    ->($token->{attributes}->{manifest}->{value});
1169                ## ISSUE: Spec is unclear on relative references.
1170                ## According to Hixie (#whatwg 2008-03-19), it should be
1171                ## resolved against the base URI of the document in HTML
1172                ## or xml:base of the element in XHTML.
1173              } else {
1174                !!!cp ('t25');
1175                $self->{application_cache_selection}->(undef);
1176              }
1177    
1178              !!!nack ('t25c');
1179    
1180              !!!next-token;
1181              return; ## Go to the "before head" insertion mode.
1182            } else {
1183              !!!cp ('t25.1');
1184              #
1185            }
1186        } elsif ({        } elsif ({
1187                  'start tag' => 1,                  END_TAG_TOKEN, 1,
1188                  'end tag' => 1,                  END_OF_FILE_TOKEN, 1,
                 'end-of-file' => 1,  
1189                 }->{$token->{type}}) {                 }->{$token->{type}}) {
1190          ## ISSUE: There is an issue in the spec          !!!cp ('t26');
1191          #          #
1192        } else {        } else {
1193          die "$0: $token->{type}: Unknown token";          die "$0: $token->{type}: Unknown token type";
1194        }        }
1195        my $root_element; !!!create-element ($root_element, 'html');  
1196        $self->{document}->append_child ($root_element);      my $root_element;
1197        push @{$self->{open_elements}}, [$root_element, 'html'];      !!!create-element ($root_element, $HTML_NS, 'html',, $token);
1198        #$phase = 'main';      $self->{document}->append_child ($root_element);
1199        ## reprocess      push @{$self->{open_elements}}, [$root_element, $el_category->{html}];
1200        #redo B;  
1201        return;      $self->{application_cache_selection}->(undef);
1202    
1203        ## NOTE: Reprocess the token.
1204        !!!ack-later;
1205        return; ## Go to the "before head" insertion mode.
1206    } # B    } # B
1207    
1208      die "$0: _tree_construction_root_element: This should never be reached";
1209  } # _tree_construction_root_element  } # _tree_construction_root_element
1210    
1211  sub _reset_insertion_mode ($) {  sub _reset_insertion_mode ($) {
# Line 1541  sub _reset_insertion_mode ($) { Line 1220  sub _reset_insertion_mode ($) {
1220            
1221      ## Step 3      ## Step 3
1222      S3: {      S3: {
1223        $last = 1 if $self->{open_elements}->[0]->[0] eq $node->[0];        if ($self->{open_elements}->[0]->[0] eq $node->[0]) {
1224        if (defined $self->{inner_html_node}) {          $last = 1;
1225          if ($self->{inner_html_node}->[1] eq 'td' or          if (defined $self->{inner_html_node}) {
1226              $self->{inner_html_node}->[1] eq 'th') {            !!!cp ('t28');
1227              $node = $self->{inner_html_node};
1228            } else {
1229              die "_reset_insertion_mode: t27";
1230            }
1231          }
1232          
1233          ## Step 4..14
1234          my $new_mode;
1235          if ($node->[1] & FOREIGN_EL) {
1236            !!!cp ('t28.1');
1237            ## NOTE: Strictly spaking, the line below only applies to MathML and
1238            ## SVG elements.  Currently the HTML syntax supports only MathML and
1239            ## SVG elements as foreigners.
1240            $new_mode = IN_BODY_IM | IN_FOREIGN_CONTENT_IM;
1241          } elsif ($node->[1] == TABLE_CELL_EL) {
1242            if ($last) {
1243              !!!cp ('t28.2');
1244            #            #
1245          } else {          } else {
1246            $node = $self->{inner_html_node};            !!!cp ('t28.3');
1247              $new_mode = IN_CELL_IM;
1248          }          }
1249          } else {
1250            !!!cp ('t28.4');
1251            $new_mode = {
1252                          select => IN_SELECT_IM,
1253                          ## NOTE: |option| and |optgroup| do not set
1254                          ## insertion mode to "in select" by themselves.
1255                          tr => IN_ROW_IM,
1256                          tbody => IN_TABLE_BODY_IM,
1257                          thead => IN_TABLE_BODY_IM,
1258                          tfoot => IN_TABLE_BODY_IM,
1259                          caption => IN_CAPTION_IM,
1260                          colgroup => IN_COLUMN_GROUP_IM,
1261                          table => IN_TABLE_IM,
1262                          head => IN_BODY_IM, # not in head!
1263                          body => IN_BODY_IM,
1264                          frameset => IN_FRAMESET_IM,
1265                         }->{$node->[0]->manakai_local_name};
1266        }        }
       
       ## Step 4..13  
       my $new_mode = {  
                       select => 'in select',  
                       td => 'in cell',  
                       th => 'in cell',  
                       tr => 'in row',  
                       tbody => 'in table body',  
                       thead => 'in table head',  
                       tfoot => 'in table foot',  
                       caption => 'in caption',  
                       colgroup => 'in column group',  
                       table => 'in table',  
                       head => 'in body', # not in head!  
                       body => 'in body',  
                       frameset => 'in frameset',  
                      }->{$node->[1]};  
1267        $self->{insertion_mode} = $new_mode and return if defined $new_mode;        $self->{insertion_mode} = $new_mode and return if defined $new_mode;
1268                
1269        ## Step 14        ## Step 15
1270        if ($node->[1] eq 'html') {        if ($node->[1] == HTML_EL) {
1271          unless (defined $self->{head_element}) {          unless (defined $self->{head_element}) {
1272            $self->{insertion_mode} = 'before head';            !!!cp ('t29');
1273              $self->{insertion_mode} = BEFORE_HEAD_IM;
1274          } else {          } else {
1275            $self->{insertion_mode} = 'after head';            ## ISSUE: Can this state be reached?
1276              !!!cp ('t30');
1277              $self->{insertion_mode} = AFTER_HEAD_IM;
1278          }          }
1279          return;          return;
1280          } else {
1281            !!!cp ('t31');
1282        }        }
1283                
       ## Step 15  
       $self->{insertion_mode} = 'in body' and return if $last;  
         
1284        ## Step 16        ## Step 16
1285          $self->{insertion_mode} = IN_BODY_IM and return if $last;
1286          
1287          ## Step 17
1288        $i--;        $i--;
1289        $node = $self->{open_elements}->[$i];        $node = $self->{open_elements}->[$i];
1290                
1291        ## Step 17        ## Step 18
1292        redo S3;        redo S3;
1293      } # S3      } # S3
1294    
1295      die "$0: _reset_insertion_mode: This line should never be reached";
1296  } # _reset_insertion_mode  } # _reset_insertion_mode
1297    
1298  sub _tree_construction_main ($) {  sub _tree_construction_main ($) {
1299    my $self = shift;    my $self = shift;
1300    
   my $phase = 'main';  
   
1301    my $active_formatting_elements = [];    my $active_formatting_elements = [];
1302    
1303    my $reconstruct_active_formatting_elements = sub { # MUST    my $reconstruct_active_formatting_elements = sub { # MUST
# Line 1612  sub _tree_construction_main ($) { Line 1314  sub _tree_construction_main ($) {
1314      return if $entry->[0] eq '#marker';      return if $entry->[0] eq '#marker';
1315      for (@{$self->{open_elements}}) {      for (@{$self->{open_elements}}) {
1316        if ($entry->[0] eq $_->[0]) {        if ($entry->[0] eq $_->[0]) {
1317            !!!cp ('t32');
1318          return;          return;
1319        }        }
1320      }      }
# Line 1626  sub _tree_construction_main ($) { Line 1329  sub _tree_construction_main ($) {
1329    
1330        ## Step 6        ## Step 6
1331        if ($entry->[0] eq '#marker') {        if ($entry->[0] eq '#marker') {
1332            !!!cp ('t33_1');
1333          #          #
1334        } else {        } else {
1335          my $in_open_elements;          my $in_open_elements;
1336          OE: for (@{$self->{open_elements}}) {          OE: for (@{$self->{open_elements}}) {
1337            if ($entry->[0] eq $_->[0]) {            if ($entry->[0] eq $_->[0]) {
1338                !!!cp ('t33');
1339              $in_open_elements = 1;              $in_open_elements = 1;
1340              last OE;              last OE;
1341            }            }
1342          }          }
1343          if ($in_open_elements) {          if ($in_open_elements) {
1344              !!!cp ('t34');
1345            #            #
1346          } else {          } else {
1347              ## NOTE: <!DOCTYPE HTML><p><b><i><u></p> <p>X
1348              !!!cp ('t35');
1349            redo S4;            redo S4;
1350          }          }
1351        }        }
# Line 1660  sub _tree_construction_main ($) { Line 1368  sub _tree_construction_main ($) {
1368    
1369        ## Step 11        ## Step 11
1370        unless ($clone->[0] eq $active_formatting_elements->[-1]->[0]) {        unless ($clone->[0] eq $active_formatting_elements->[-1]->[0]) {
1371            !!!cp ('t36');
1372          ## Step 7'          ## Step 7'
1373          $i++;          $i++;
1374          $entry = $active_formatting_elements->[$i];          $entry = $active_formatting_elements->[$i];
1375                    
1376          redo S7;          redo S7;
1377        }        }
1378    
1379          !!!cp ('t37');
1380      } # S7      } # S7
1381    }; # $reconstruct_active_formatting_elements    }; # $reconstruct_active_formatting_elements
1382    
1383    my $clear_up_to_marker = sub {    my $clear_up_to_marker = sub {
1384      for (reverse 0..$#$active_formatting_elements) {      for (reverse 0..$#$active_formatting_elements) {
1385        if ($active_formatting_elements->[$_]->[0] eq '#marker') {        if ($active_formatting_elements->[$_]->[0] eq '#marker') {
1386            !!!cp ('t38');
1387          splice @$active_formatting_elements, $_;          splice @$active_formatting_elements, $_;
1388          return;          return;
1389        }        }
1390      }      }
1391    
1392        !!!cp ('t39');
1393    }; # $clear_up_to_marker    }; # $clear_up_to_marker
1394    
1395    my $style_start_tag = sub {    my $insert;
1396      my $style_el; !!!create-element ($style_el, 'style', $token->{attributes});  
1397      ## $self->{insertion_mode} eq 'in head' and ... (always true)    my $parse_rcdata = sub ($) {
1398      (($self->{insertion_mode} eq 'in head' and defined $self->{head_element})      my ($content_model_flag) = @_;
1399       ? $self->{head_element} : $self->{open_elements}->[-1]->[0])  
1400        ->append_child ($style_el);      ## Step 1
1401      $self->{content_model_flag} = 'CDATA';      my $start_tag_name = $token->{tag_name};
1402        !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
1403    
1404        ## Step 2
1405        $self->{content_model} = $content_model_flag; # CDATA or RCDATA
1406      delete $self->{escape}; # MUST      delete $self->{escape}; # MUST
1407                  
1408      my $text = '';      ## Step 3, 4
1409      !!!next-token;      $self->{insertion_mode} |= IN_CDATA_RCDATA_IM;
1410      while ($token->{type} eq 'character') {  
1411        $text .= $token->{data};      !!!nack ('t40.1');
       !!!next-token;  
     } # stop if non-character token or tokenizer stops tokenising  
     if (length $text) {  
       $style_el->manakai_append_text ($text);  
     }  
       
     $self->{content_model_flag} = 'PCDATA';  
                 
     if ($token->{type} eq 'end tag' and $token->{tag_name} eq 'style') {  
       ## Ignore the token  
     } else {  
       !!!parse-error (type => 'in CDATA:#'.$token->{type});  
       ## ISSUE: And ignore?  
     }  
1412      !!!next-token;      !!!next-token;
1413    }; # $style_start_tag    }; # $parse_rcdata
1414    
1415    my $script_start_tag = sub {    my $script_start_tag = sub () {
1416        ## Step 1
1417      my $script_el;      my $script_el;
1418      !!!create-element ($script_el, 'script', $token->{attributes});      !!!create-element ($script_el, $HTML_NS, 'script', $token->{attributes}, $token);
1419    
1420        ## Step 2
1421      ## TODO: mark as "parser-inserted"      ## TODO: mark as "parser-inserted"
1422    
1423      $self->{content_model_flag} = 'CDATA';      ## Step 3
1424        ## TODO: Mark as "already executed", if ...
1425    
1426        ## Step 4 (HTML5 revision 2702)
1427        $insert->($script_el);
1428        push @{$self->{open_elements}}, [$script_el, $el_category->{script}];
1429    
1430        ## Step 5
1431        $self->{content_model} = CDATA_CONTENT_MODEL;
1432      delete $self->{escape}; # MUST      delete $self->{escape}; # MUST
       
     my $text = '';  
     !!!next-token;  
     while ($token->{type} eq 'character') {  
       $text .= $token->{data};  
       !!!next-token;  
     } # stop if non-character token or tokenizer stops tokenising  
     if (length $text) {  
       $script_el->manakai_append_text ($text);  
     }  
                 
     $self->{content_model_flag} = 'PCDATA';  
1433    
1434      if ($token->{type} eq 'end tag' and      ## Step 6-7
1435          $token->{tag_name} eq 'script') {      $self->{insertion_mode} |= IN_CDATA_RCDATA_IM;
1436        ## Ignore the token  
1437      } else {      !!!nack ('t40.2');
       !!!parse-error (type => 'in CDATA:#'.$token->{type});  
       ## ISSUE: And ignore?  
       ## TODO: mark as "already executed"  
     }  
       
     if (defined $self->{inner_html_node}) {  
       ## TODO: mark as "already executed"  
     } else {  
       ## TODO: $old_insertion_point = current insertion point  
       ## TODO: insertion point = just before the next input character  
         
       (($self->{insertion_mode} eq 'in head' and defined $self->{head_element})  
        ? $self->{head_element} : $self->{open_elements}->[-1]->[0])->append_child ($script_el);  
         
       ## TODO: insertion point = $old_insertion_point (might be "undefined")  
         
       ## TODO: if there is a script that will execute as soon as the parser resume, then...  
     }  
       
1438      !!!next-token;      !!!next-token;
1439    }; # $script_start_tag    }; # $script_start_tag
1440    
1441      ## NOTE: $open_tables->[-1]->[0] is the "current table" element node.
1442      ## NOTE: $open_tables->[-1]->[1] is the "tainted" flag (OBSOLETE; unused).
1443      ## NOTE: $open_tables->[-1]->[2] is set false when non-Text node inserted.
1444      my $open_tables = [[$self->{open_elements}->[0]->[0]]];
1445    
1446    my $formatting_end_tag = sub {    my $formatting_end_tag = sub {
1447      my $tag_name = shift;      my $end_tag_token = shift;
1448        my $tag_name = $end_tag_token->{tag_name};
1449    
1450        ## NOTE: The adoption agency algorithm (AAA).
1451    
1452      FET: {      FET: {
1453        ## Step 1        ## Step 1
1454        my $formatting_element;        my $formatting_element;
1455        my $formatting_element_i_in_active;        my $formatting_element_i_in_active;
1456        AFE: for (reverse 0..$#$active_formatting_elements) {        AFE: for (reverse 0..$#$active_formatting_elements) {
1457          if ($active_formatting_elements->[$_]->[1] eq $tag_name) {          if ($active_formatting_elements->[$_]->[0] eq '#marker') {
1458              !!!cp ('t52');
1459              last AFE;
1460            } elsif ($active_formatting_elements->[$_]->[0]->manakai_local_name
1461                         eq $tag_name) {
1462              !!!cp ('t51');
1463            $formatting_element = $active_formatting_elements->[$_];            $formatting_element = $active_formatting_elements->[$_];
1464            $formatting_element_i_in_active = $_;            $formatting_element_i_in_active = $_;
1465            last AFE;            last AFE;
         } elsif ($active_formatting_elements->[$_]->[0] eq '#marker') {  
           last AFE;  
1466          }          }
1467        } # AFE        } # AFE
1468        unless (defined $formatting_element) {        unless (defined $formatting_element) {
1469          !!!parse-error (type => 'unmatched end tag:'.$tag_name);          !!!cp ('t53');
1470            !!!parse-error (type => 'unmatched end tag', text => $tag_name, token => $end_tag_token);
1471          ## Ignore the token          ## Ignore the token
1472          !!!next-token;          !!!next-token;
1473          return;          return;
# Line 1783  sub _tree_construction_main ($) { Line 1479  sub _tree_construction_main ($) {
1479          my $node = $self->{open_elements}->[$_];          my $node = $self->{open_elements}->[$_];
1480          if ($node->[0] eq $formatting_element->[0]) {          if ($node->[0] eq $formatting_element->[0]) {
1481            if ($in_scope) {            if ($in_scope) {
1482                !!!cp ('t54');
1483              $formatting_element_i_in_open = $_;              $formatting_element_i_in_open = $_;
1484              last INSCOPE;              last INSCOPE;
1485            } else { # in open elements but not in scope            } else { # in open elements but not in scope
1486              !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});              !!!cp ('t55');
1487                !!!parse-error (type => 'unmatched end tag',
1488                                text => $token->{tag_name},
1489                                token => $end_tag_token);
1490              ## Ignore the token              ## Ignore the token
1491              !!!next-token;              !!!next-token;
1492              return;              return;
1493            }            }
1494          } elsif ({          } elsif ($node->[1] & SCOPING_EL) {
1495                    table => 1, caption => 1, td => 1, th => 1,            !!!cp ('t56');
                   button => 1, marquee => 1, object => 1, html => 1,  
                  }->{$node->[1]}) {  
1496            $in_scope = 0;            $in_scope = 0;
1497          }          }
1498        } # INSCOPE        } # INSCOPE
1499        unless (defined $formatting_element_i_in_open) {        unless (defined $formatting_element_i_in_open) {
1500          !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});          !!!cp ('t57');
1501            !!!parse-error (type => 'unmatched end tag',
1502                            text => $token->{tag_name},
1503                            token => $end_tag_token);
1504          pop @$active_formatting_elements; # $formatting_element          pop @$active_formatting_elements; # $formatting_element
1505          !!!next-token; ## TODO: ok?          !!!next-token; ## TODO: ok?
1506          return;          return;
1507        }        }
1508        if (not $self->{open_elements}->[-1]->[0] eq $formatting_element->[0]) {        if (not $self->{open_elements}->[-1]->[0] eq $formatting_element->[0]) {
1509          !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);          !!!cp ('t58');
1510            !!!parse-error (type => 'not closed',
1511                            text => $self->{open_elements}->[-1]->[0]
1512                                ->manakai_local_name,
1513                            token => $end_tag_token);
1514        }        }
1515                
1516        ## Step 2        ## Step 2
# Line 1813  sub _tree_construction_main ($) { Line 1518  sub _tree_construction_main ($) {
1518        my $furthest_block_i_in_open;        my $furthest_block_i_in_open;
1519        OE: for (reverse 0..$#{$self->{open_elements}}) {        OE: for (reverse 0..$#{$self->{open_elements}}) {
1520          my $node = $self->{open_elements}->[$_];          my $node = $self->{open_elements}->[$_];
1521          if (not $formatting_category->{$node->[1]} and          if (not ($node->[1] & FORMATTING_EL) and
1522              #not $phrasing_category->{$node->[1]} and              #not $phrasing_category->{$node->[1]} and
1523              ($special_category->{$node->[1]} or              ($node->[1] & SPECIAL_EL or
1524               $scoping_category->{$node->[1]})) {               $node->[1] & SCOPING_EL)) { ## Scoping is redundant, maybe
1525              !!!cp ('t59');
1526            $furthest_block = $node;            $furthest_block = $node;
1527            $furthest_block_i_in_open = $_;            $furthest_block_i_in_open = $_;
1528              ## NOTE: The topmost (eldest) node.
1529          } elsif ($node->[0] eq $formatting_element->[0]) {          } elsif ($node->[0] eq $formatting_element->[0]) {
1530              !!!cp ('t60');
1531            last OE;            last OE;
1532          }          }
1533        } # OE        } # OE
1534                
1535        ## Step 3        ## Step 3
1536        unless (defined $furthest_block) { # MUST        unless (defined $furthest_block) { # MUST
1537            !!!cp ('t61');
1538          splice @{$self->{open_elements}}, $formatting_element_i_in_open;          splice @{$self->{open_elements}}, $formatting_element_i_in_open;
1539          splice @$active_formatting_elements, $formatting_element_i_in_active, 1;          splice @$active_formatting_elements, $formatting_element_i_in_active, 1;
1540          !!!next-token;          !!!next-token;
# Line 1838  sub _tree_construction_main ($) { Line 1547  sub _tree_construction_main ($) {
1547        ## Step 5        ## Step 5
1548        my $furthest_block_parent = $furthest_block->[0]->parent_node;        my $furthest_block_parent = $furthest_block->[0]->parent_node;
1549        if (defined $furthest_block_parent) {        if (defined $furthest_block_parent) {
1550            !!!cp ('t62');
1551          $furthest_block_parent->remove_child ($furthest_block->[0]);          $furthest_block_parent->remove_child ($furthest_block->[0]);
1552        }        }
1553                
# Line 1860  sub _tree_construction_main ($) { Line 1570  sub _tree_construction_main ($) {
1570          S7S2: {          S7S2: {
1571            for (reverse 0..$#$active_formatting_elements) {            for (reverse 0..$#$active_formatting_elements) {
1572              if ($active_formatting_elements->[$_]->[0] eq $node->[0]) {              if ($active_formatting_elements->[$_]->[0] eq $node->[0]) {
1573                  !!!cp ('t63');
1574                $node_i_in_active = $_;                $node_i_in_active = $_;
1575                last S7S2;                last S7S2;
1576              }              }
# Line 1873  sub _tree_construction_main ($) { Line 1584  sub _tree_construction_main ($) {
1584                    
1585          ## Step 4          ## Step 4
1586          if ($last_node->[0] eq $furthest_block->[0]) {          if ($last_node->[0] eq $furthest_block->[0]) {
1587              !!!cp ('t64');
1588            $bookmark_prev_el = $node->[0];            $bookmark_prev_el = $node->[0];
1589          }          }
1590                    
1591          ## Step 5          ## Step 5
1592          if ($node->[0]->has_child_nodes ()) {          if ($node->[0]->has_child_nodes ()) {
1593              !!!cp ('t65');
1594            my $clone = [$node->[0]->clone_node (0), $node->[1]];            my $clone = [$node->[0]->clone_node (0), $node->[1]];
1595            $active_formatting_elements->[$node_i_in_active] = $clone;            $active_formatting_elements->[$node_i_in_active] = $clone;
1596            $self->{open_elements}->[$node_i_in_open] = $clone;            $self->{open_elements}->[$node_i_in_open] = $clone;
# Line 1895  sub _tree_construction_main ($) { Line 1608  sub _tree_construction_main ($) {
1608        } # S7          } # S7  
1609                
1610        ## Step 8        ## Step 8
1611        $common_ancestor_node->[0]->append_child ($last_node->[0]);        if ($common_ancestor_node->[1] & TABLE_ROWS_EL) {
1612            my $foster_parent_element;
1613            my $next_sibling;
1614            OE: for (reverse 0..$#{$self->{open_elements}}) {
1615              if ($self->{open_elements}->[$_]->[1] == TABLE_EL) {
1616                                 my $parent = $self->{open_elements}->[$_]->[0]->parent_node;
1617                                 if (defined $parent and $parent->node_type == 1) {
1618                                   !!!cp ('t65.1');
1619                                   $foster_parent_element = $parent;
1620                                   $next_sibling = $self->{open_elements}->[$_]->[0];
1621                                 } else {
1622                                   !!!cp ('t65.2');
1623                                   $foster_parent_element
1624                                     = $self->{open_elements}->[$_ - 1]->[0];
1625                                 }
1626                                 last OE;
1627                               }
1628                             } # OE
1629                             $foster_parent_element = $self->{open_elements}->[0]->[0]
1630                               unless defined $foster_parent_element;
1631            $foster_parent_element->insert_before ($last_node->[0], $next_sibling);
1632            $open_tables->[-1]->[1] = 1; # tainted
1633          } else {
1634            !!!cp ('t65.3');
1635            $common_ancestor_node->[0]->append_child ($last_node->[0]);
1636          }
1637                
1638        ## Step 9        ## Step 9
1639        my $clone = [$formatting_element->[0]->clone_node (0),        my $clone = [$formatting_element->[0]->clone_node (0),
# Line 1912  sub _tree_construction_main ($) { Line 1650  sub _tree_construction_main ($) {
1650        my $i;        my $i;
1651        AFE: for (reverse 0..$#$active_formatting_elements) {        AFE: for (reverse 0..$#$active_formatting_elements) {
1652          if ($active_formatting_elements->[$_]->[0] eq $formatting_element->[0]) {          if ($active_formatting_elements->[$_]->[0] eq $formatting_element->[0]) {
1653              !!!cp ('t66');
1654            splice @$active_formatting_elements, $_, 1;            splice @$active_formatting_elements, $_, 1;
1655            $i-- and last AFE if defined $i;            $i-- and last AFE if defined $i;
1656          } elsif ($active_formatting_elements->[$_]->[0] eq $bookmark_prev_el) {          } elsif ($active_formatting_elements->[$_]->[0] eq $bookmark_prev_el) {
1657              !!!cp ('t67');
1658            $i = $_;            $i = $_;
1659          }          }
1660        } # AFE        } # AFE
# Line 1924  sub _tree_construction_main ($) { Line 1664  sub _tree_construction_main ($) {
1664        undef $i;        undef $i;
1665        OE: for (reverse 0..$#{$self->{open_elements}}) {        OE: for (reverse 0..$#{$self->{open_elements}}) {
1666          if ($self->{open_elements}->[$_]->[0] eq $formatting_element->[0]) {          if ($self->{open_elements}->[$_]->[0] eq $formatting_element->[0]) {
1667              !!!cp ('t68');
1668            splice @{$self->{open_elements}}, $_, 1;            splice @{$self->{open_elements}}, $_, 1;
1669            $i-- and last OE if defined $i;            $i-- and last OE if defined $i;
1670          } elsif ($self->{open_elements}->[$_]->[0] eq $furthest_block->[0]) {          } elsif ($self->{open_elements}->[$_]->[0] eq $furthest_block->[0]) {
1671              !!!cp ('t69');
1672            $i = $_;            $i = $_;
1673          }          }
1674        } # OE        } # OE
1675        splice @{$self->{open_elements}}, $i + 1, 1, $clone;        splice @{$self->{open_elements}}, $i + 1, 0, $clone;
1676                
1677        ## Step 14        ## Step 14
1678        redo FET;        redo FET;
1679      } # FET      } # FET
1680    }; # $formatting_end_tag    }; # $formatting_end_tag
1681    
1682    my $insert_to_current = sub {    $insert = my $insert_to_current = sub {
1683      $self->{open_elements}->[-1]->[0]->append_child (shift);      $self->{open_elements}->[-1]->[0]->append_child ($_[0]);
1684    }; # $insert_to_current    }; # $insert_to_current
1685    
1686    my $insert_to_foster = sub {    my $insert_to_foster = sub {
1687                         my $child = shift;      my $child = shift;
1688                         if ({      if ($self->{open_elements}->[-1]->[1] & TABLE_ROWS_EL) {
1689                              table => 1, tbody => 1, tfoot => 1,        # MUST
1690                              thead => 1, tr => 1,        my $foster_parent_element;
1691                             }->{$self->{open_elements}->[-1]->[1]}) {        my $next_sibling;
1692                           # MUST        OE: for (reverse 0..$#{$self->{open_elements}}) {
1693                           my $foster_parent_element;          if ($self->{open_elements}->[$_]->[1] == TABLE_EL) {
                          my $next_sibling;  
                          OE: for (reverse 0..$#{$self->{open_elements}}) {  
                            if ($self->{open_elements}->[$_]->[1] eq 'table') {  
1694                               my $parent = $self->{open_elements}->[$_]->[0]->parent_node;                               my $parent = $self->{open_elements}->[$_]->[0]->parent_node;
1695                               if (defined $parent and $parent->node_type == 1) {                               if (defined $parent and $parent->node_type == 1) {
1696                                   !!!cp ('t70');
1697                                 $foster_parent_element = $parent;                                 $foster_parent_element = $parent;
1698                                 $next_sibling = $self->{open_elements}->[$_]->[0];                                 $next_sibling = $self->{open_elements}->[$_]->[0];
1699                               } else {                               } else {
1700                                   !!!cp ('t71');
1701                                 $foster_parent_element                                 $foster_parent_element
1702                                   = $self->{open_elements}->[$_ - 1]->[0];                                   = $self->{open_elements}->[$_ - 1]->[0];
1703                               }                               }
# Line 1967  sub _tree_construction_main ($) { Line 1708  sub _tree_construction_main ($) {
1708                             unless defined $foster_parent_element;                             unless defined $foster_parent_element;
1709                           $foster_parent_element->insert_before                           $foster_parent_element->insert_before
1710                             ($child, $next_sibling);                             ($child, $next_sibling);
1711                         } else {        $open_tables->[-1]->[1] = 1; # tainted
1712                           $self->{open_elements}->[-1]->[0]->append_child ($child);      } else {
1713                         }        !!!cp ('t72');
1714          $self->{open_elements}->[-1]->[0]->append_child ($child);
1715        }
1716    }; # $insert_to_foster    }; # $insert_to_foster
1717    
1718    my $in_body = sub {    ## NOTE: Insert a character (MUST): When a character is inserted, if
1719      my $insert = shift;    ## the last node that was inserted by the parser is a Text node and
1720      if ($token->{type} eq 'start tag') {    ## the character has to be inserted after that node, then the
1721        if ($token->{tag_name} eq 'script') {    ## character is appended to the Text node.  However, if any other
1722          $script_start_tag->();    ## node is inserted by the parser, then a new Text node is created
1723          return;    ## and the character is appended as that Text node.  If I'm not
1724        } elsif ($token->{tag_name} eq 'style') {    ## wrong, for a parser with scripting disabled, there are only two
1725          $style_start_tag->();    ## cases where this occurs.  One is the case where an element node
1726          return;    ## is inserted to the |head| element.  This is covered by using the
1727        } elsif ({    ## |$self->{head_element_inserted}| flag.  Another is the case where
1728                  base => 1, link => 1, meta => 1,    ## an element or comment is inserted into the |table| subtree while
1729                 }->{$token->{tag_name}}) {    ## foster parenting happens.  This is covered by using the [2] flag
1730          !!!parse-error (type => 'in body:'.$token->{tag_name});    ## of the |$open_tables| structure.  All other cases are handled
1731          ## NOTE: This is an "as if in head" code clone    ## simply by calling |manakai_append_text| method.
1732          my $el;  
1733          !!!create-element ($el, $token->{tag_name}, $token->{attributes});    ## TODO: |<body><script>document.write("a<br>");
1734          if (defined $self->{head_element}) {    ## document.body.removeChild (document.body.lastChild);
1735            $self->{head_element}->append_child ($el);    ## document.write ("b")</script>|
1736          } else {  
1737            $insert->($el);    B: while (1) {
1738          }  
1739                ## The "in table text" insertion mode.
1740          !!!next-token;      if ($self->{insertion_mode} & TABLE_IMS and
1741          return;          not $self->{insertion_mode} & IN_FOREIGN_CONTENT_IM and
1742        } elsif ($token->{tag_name} eq 'title') {          not $self->{insertion_mode} & IN_CDATA_RCDATA_IM) {
1743          !!!parse-error (type => 'in body:title');        C: {
1744          ## NOTE: There is an "as if in head" code clone          my $s;
1745          my $title_el;          if ($token->{type} == CHARACTER_TOKEN) {
1746          !!!create-element ($title_el, 'title', $token->{attributes});            !!!cp ('t194');
1747          (defined $self->{head_element} ? $self->{head_element} : $self->{open_elements}->[-1]->[0])            $self->{pending_chars} ||= [];
1748            ->append_child ($title_el);            push @{$self->{pending_chars}}, $token;
         $self->{content_model_flag} = 'RCDATA';  
         delete $self->{escape}; # MUST  
           
         my $text = '';  
         !!!next-token;  
         while ($token->{type} eq 'character') {  
           $text .= $token->{data};  
1749            !!!next-token;            !!!next-token;
1750          }            next B;
         if (length $text) {  
           $title_el->manakai_append_text ($text);  
         }  
           
         $self->{content_model_flag} = 'PCDATA';  
           
         if ($token->{type} eq 'end tag' and  
             $token->{tag_name} eq 'title') {  
           ## Ignore the token  
         } else {  
           !!!parse-error (type => 'in RCDATA:#'.$token->{type});  
           ## ISSUE: And ignore?  
         }  
         !!!next-token;  
         return;  
       } elsif ($token->{tag_name} eq 'body') {  
         !!!parse-error (type => 'in body:body');  
                 
         if (@{$self->{open_elements}} == 1 or  
             $self->{open_elements}->[1]->[1] ne 'body') {  
           ## Ignore the token  
1751          } else {          } else {
1752            my $body_el = $self->{open_elements}->[1]->[0];            if ($self->{pending_chars}) {
1753            for my $attr_name (keys %{$token->{attributes}}) {              $s = join '', map { $_->{data} } @{$self->{pending_chars}};
1754              unless ($body_el->has_attribute_ns (undef, $attr_name)) {              delete $self->{pending_chars};
1755                $body_el->set_attribute_ns              if ($s =~ /[^\x09\x0A\x0C\x0D\x20]/) {
1756                  (undef, [undef, $attr_name],                !!!cp ('t195');
1757                   $token->{attributes}->{$attr_name}->{value});                #
1758                } else {
1759                  !!!cp ('t195.1');
1760                  #$self->{open_elements}->[-1]->[0]->manakai_append_text ($s);
1761                  $self->{open_elements}->[-1]->[0]->append_child
1762                      ($self->{document}->create_text_node ($s));
1763                  last C;
1764              }              }
1765              } else {
1766                !!!cp ('t195.2');
1767                last C;
1768            }            }
1769          }          }
1770          !!!next-token;  
1771          return;          ## Foster parenting
1772        } elsif ({          !!!parse-error (type => 'in table:#text', token => $token);
1773                  address => 1, blockquote => 1, center => 1, dir => 1,  
1774                  div => 1, dl => 1, fieldset => 1, listing => 1,          ## NOTE: As if in body, but insert into the foster parent element.
1775                  menu => 1, ol => 1, p => 1, ul => 1,          $reconstruct_active_formatting_elements->($insert_to_foster);
1776                  pre => 1,              
1777                 }->{$token->{tag_name}}) {          if ($self->{open_elements}->[-1]->[1] & TABLE_ROWS_EL) {
1778          ## has a p element in scope            # MUST
1779          INSCOPE: for (reverse @{$self->{open_elements}}) {            my $foster_parent_element;
1780            if ($_->[1] eq 'p') {            my $next_sibling;
1781              !!!back-token;            #my $prev_sibling;
1782              $token = {type => 'end tag', tag_name => 'p'};            OE: for (reverse 0..$#{$self->{open_elements}}) {
1783              return;              if ($self->{open_elements}->[$_]->[1] == TABLE_EL) {
1784            } elsif ({                my $parent = $self->{open_elements}->[$_]->[0]->parent_node;
1785                      table => 1, caption => 1, td => 1, th => 1,                if (defined $parent and $parent->node_type == 1) {
1786                      button => 1, marquee => 1, object => 1, html => 1,                  $foster_parent_element = $parent;
1787                     }->{$_->[1]}) {                  !!!cp ('t196');
1788              last INSCOPE;                  $next_sibling = $self->{open_elements}->[$_]->[0];
1789            }            #      $prev_sibling = $next_sibling->previous_sibling;
1790          } # INSCOPE                  #
1791                            } else {
1792          !!!insert-element-t ($token->{tag_name}, $token->{attributes});                  !!!cp ('t197');
1793          if ($token->{tag_name} eq 'pre') {                  $foster_parent_element = $self->{open_elements}->[$_ - 1]->[0];
1794            !!!next-token;            #      $prev_sibling = $foster_parent_element->last_child;
1795            if ($token->{type} eq 'character') {                  #
1796              $token->{data} =~ s/^\x0A//;                }
1797              unless (length $token->{data}) {                last OE;
1798                !!!next-token;              }
1799              }            } # OE
1800            }            $foster_parent_element = $self->{open_elements}->[0]->[0] #and
1801          } else {            #$prev_sibling = $foster_parent_element->last_child
1802            !!!next-token;                unless defined $foster_parent_element;
1803              #undef $prev_sibling unless $open_tables->[-1]->[2]; # ~node inserted
1804              #if (defined $prev_sibling and
1805              #    $prev_sibling->node_type == 3) {
1806              #  !!! cp ('t198');
1807              #  $prev_sibling->manakai_append_text ($s);
1808              #} else {
1809                !!!cp ('t199');
1810                $foster_parent_element->insert_before
1811                    ($self->{document}->create_text_node ($s), $next_sibling);
1812              #}
1813              $open_tables->[-1]->[1] = 1; # tainted
1814              $open_tables->[-1]->[2] = 1; # ~node inserted
1815            } else {
1816              ## NOTE: Fragment case or in a foster parent'ed element
1817              ## (e.g. |<table><span>a|).  In fragment case, whether the
1818              ## character is appended to existing node or a new node is
1819              ## created is irrelevant, since the foster parent'ed nodes
1820              ## are discarded and fragment parsing does not invoke any
1821              ## script.
1822              !!!cp ('t200');
1823              $self->{open_elements}->[-1]->[0]->manakai_append_text ($s);
1824            }
1825          } # C
1826        } # TABLE_IMS
1827    
1828        if ($token->{type} == DOCTYPE_TOKEN) {
1829          !!!cp ('t73');
1830          !!!parse-error (type => 'in html:#DOCTYPE', token => $token);
1831          ## Ignore the token
1832          ## Stay in the phase
1833          !!!next-token;
1834          next B;
1835        } elsif ($token->{type} == START_TAG_TOKEN and
1836                 $token->{tag_name} eq 'html') {
1837          if ($self->{insertion_mode} == AFTER_HTML_BODY_IM) {
1838            !!!cp ('t79');
1839            !!!parse-error (type => 'after html', text => 'html', token => $token);
1840            $self->{insertion_mode} = AFTER_BODY_IM;
1841          } elsif ($self->{insertion_mode} == AFTER_HTML_FRAMESET_IM) {
1842            !!!cp ('t80');
1843            !!!parse-error (type => 'after html', text => 'html', token => $token);
1844            $self->{insertion_mode} = AFTER_FRAMESET_IM;
1845          } else {
1846            !!!cp ('t81');
1847          }
1848    
1849          !!!cp ('t82');
1850          !!!parse-error (type => 'not first start tag', token => $token);
1851          my $top_el = $self->{open_elements}->[0]->[0];
1852          for my $attr_name (keys %{$token->{attributes}}) {
1853            unless ($top_el->has_attribute_ns (undef, $attr_name)) {
1854              !!!cp ('t84');
1855              $top_el->set_attribute_ns
1856                (undef, [undef, $attr_name],
1857                 $token->{attributes}->{$attr_name}->{value});
1858          }          }
1859          return;        }
1860        } elsif ($token->{tag_name} eq 'form') {        !!!nack ('t84.1');
1861          if (defined $self->{form_element}) {        !!!next-token;
1862            !!!parse-error (type => 'in form:form');        next B;
1863            ## Ignore the token      } elsif ($token->{type} == COMMENT_TOKEN) {
1864            !!!next-token;        my $comment = $self->{document}->create_comment ($token->{data});
1865            return;        if ($self->{insertion_mode} & AFTER_HTML_IMS) {
1866            !!!cp ('t85');
1867            $self->{document}->append_child ($comment);
1868          } elsif ($self->{insertion_mode} == AFTER_BODY_IM) {
1869            !!!cp ('t86');
1870            $self->{open_elements}->[0]->[0]->append_child ($comment);
1871          } else {
1872            !!!cp ('t87');
1873            $self->{open_elements}->[-1]->[0]->append_child ($comment);
1874            $open_tables->[-1]->[2] = 0 if @$open_tables; # ~node inserted
1875          }
1876          !!!next-token;
1877          next B;
1878        } elsif ($self->{insertion_mode} & IN_CDATA_RCDATA_IM) {
1879          if ($token->{type} == CHARACTER_TOKEN) {
1880            $token->{data} =~ s/^\x0A// if $self->{ignore_newline};
1881            delete $self->{ignore_newline};
1882    
1883            if (length $token->{data}) {
1884              !!!cp ('t43');
1885              $self->{open_elements}->[-1]->[0]->manakai_append_text
1886                  ($token->{data});
1887          } else {          } else {
1888            ## has a p element in scope            !!!cp ('t43.1');
           INSCOPE: for (reverse @{$self->{open_elements}}) {  
             if ($_->[1] eq 'p') {  
               !!!back-token;  
               $token = {type => 'end tag', tag_name => 'p'};  
               return;  
             } elsif ({  
                       table => 1, caption => 1, td => 1, th => 1,  
                       button => 1, marquee => 1, object => 1, html => 1,  
                      }->{$_->[1]}) {  
               last INSCOPE;  
             }  
           } # INSCOPE  
               
           !!!insert-element-t ($token->{tag_name}, $token->{attributes});  
           $self->{form_element} = $self->{open_elements}->[-1]->[0];  
           !!!next-token;  
           return;  
1889          }          }
       } elsif ($token->{tag_name} eq 'li') {  
         ## has a p element in scope  
         INSCOPE: for (reverse @{$self->{open_elements}}) {  
           if ($_->[1] eq 'p') {  
             !!!back-token;  
             $token = {type => 'end tag', tag_name => 'p'};  
             return;  
           } elsif ({  
                     table => 1, caption => 1, td => 1, th => 1,  
                     button => 1, marquee => 1, object => 1, html => 1,  
                    }->{$_->[1]}) {  
             last INSCOPE;  
           }  
         } # INSCOPE  
             
         ## Step 1  
         my $i = -1;  
         my $node = $self->{open_elements}->[$i];  
         LI: {  
           ## Step 2  
           if ($node->[1] eq 'li') {  
             if ($i != -1) {  
               !!!parse-error (type => 'end tag missing:'.  
                               $self->{open_elements}->[-1]->[1]);  
               ## TODO: test  
             }  
             splice @{$self->{open_elements}}, $i;  
             last LI;  
           }  
             
           ## Step 3  
           if (not $formatting_category->{$node->[1]} and  
               #not $phrasing_category->{$node->[1]} and  
               ($special_category->{$node->[1]} or  
                $scoping_category->{$node->[1]}) and  
               $node->[1] ne 'address' and $node->[1] ne 'div') {  
             last LI;  
           }  
             
           ## Step 4  
           $i--;  
           $node = $self->{open_elements}->[$i];  
           redo LI;  
         } # LI  
             
         !!!insert-element-t ($token->{tag_name}, $token->{attributes});  
         !!!next-token;  
         return;  
       } elsif ($token->{tag_name} eq 'dd' or $token->{tag_name} eq 'dt') {  
         ## has a p element in scope  
         INSCOPE: for (reverse @{$self->{open_elements}}) {  
           if ($_->[1] eq 'p') {  
             !!!back-token;  
             $token = {type => 'end tag', tag_name => 'p'};  
             return;  
           } elsif ({  
                     table => 1, caption => 1, td => 1, th => 1,  
                     button => 1, marquee => 1, object => 1, html => 1,  
                    }->{$_->[1]}) {  
             last INSCOPE;  
           }  
         } # INSCOPE  
             
         ## Step 1  
         my $i = -1;  
         my $node = $self->{open_elements}->[$i];  
         LI: {  
           ## Step 2  
           if ($node->[1] eq 'dt' or $node->[1] eq 'dd') {  
             if ($i != -1) {  
               !!!parse-error (type => 'end tag missing:'.  
                               $self->{open_elements}->[-1]->[1]);  
               ## TODO: test  
             }  
             splice @{$self->{open_elements}}, $i;  
             last LI;  
           }  
             
           ## Step 3  
           if (not $formatting_category->{$node->[1]} and  
               #not $phrasing_category->{$node->[1]} and  
               ($special_category->{$node->[1]} or  
                $scoping_category->{$node->[1]}) and  
               $node->[1] ne 'address' and $node->[1] ne 'div') {  
             last LI;  
           }  
             
           ## Step 4  
           $i--;  
           $node = $self->{open_elements}->[$i];  
           redo LI;  
         } # LI  
             
         !!!insert-element-t ($token->{tag_name}, $token->{attributes});  
         !!!next-token;  
         return;  
       } elsif ($token->{tag_name} eq 'plaintext') {  
         ## has a p element in scope  
         INSCOPE: for (reverse @{$self->{open_elements}}) {  
           if ($_->[1] eq 'p') {  
             !!!back-token;  
             $token = {type => 'end tag', tag_name => 'p'};  
             return;  
           } elsif ({  
                     table => 1, caption => 1, td => 1, th => 1,  
                     button => 1, marquee => 1, object => 1, html => 1,  
                    }->{$_->[1]}) {  
             last INSCOPE;  
           }  
         } # INSCOPE  
             
         !!!insert-element-t ($token->{tag_name}, $token->{attributes});  
             
         $self->{content_model_flag} = 'PLAINTEXT';  
             
1890          !!!next-token;          !!!next-token;
1891          return;          next B;
1892        } elsif ({        } elsif ($token->{type} == END_TAG_TOKEN) {
1893                  h1 => 1, h2 => 1, h3 => 1, h4 => 1, h5 => 1, h6 => 1,          delete $self->{ignore_newline};
1894                 }->{$token->{tag_name}}) {  
1895          ## has a p element in scope          if ($token->{tag_name} eq 'script') {
1896          INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {            !!!cp ('t50');
           my $node = $self->{open_elements}->[$_];  
           if ($node->[1] eq 'p') {  
             !!!back-token;  
             $token = {type => 'end tag', tag_name => 'p'};  
             return;  
           } elsif ({  
                     table => 1, caption => 1, td => 1, th => 1,  
                     button => 1, marquee => 1, object => 1, html => 1,  
                    }->{$node->[1]}) {  
             last INSCOPE;  
           }  
         } # INSCOPE  
             
         ## has an element in scope  
         my $i;  
         INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {  
           my $node = $self->{open_elements}->[$_];  
           if ({  
                h1 => 1, h2 => 1, h3 => 1, h4 => 1, h5 => 1, h6 => 1,  
               }->{$node->[1]}) {  
             $i = $_;  
             last INSCOPE;  
           } elsif ({  
                     table => 1, caption => 1, td => 1, th => 1,  
                     button => 1, marquee => 1, object => 1, html => 1,  
                    }->{$node->[1]}) {  
             last INSCOPE;  
           }  
         } # INSCOPE  
             
         if (defined $i) {  
           !!!parse-error (type => 'in hn:hn');  
           splice @{$self->{open_elements}}, $i;  
         }  
             
         !!!insert-element-t ($token->{tag_name}, $token->{attributes});  
1897                        
1898          !!!next-token;            ## Para 1-2
1899          return;            my $script = pop @{$self->{open_elements}};
       } elsif ($token->{tag_name} eq 'a') {  
         AFE: for my $i (reverse 0..$#$active_formatting_elements) {  
           my $node = $active_formatting_elements->[$i];  
           if ($node->[1] eq 'a') {  
             !!!parse-error (type => 'in a:a');  
               
             !!!back-token;  
             $token = {type => 'end tag', tag_name => 'a'};  
             $formatting_end_tag->($token->{tag_name});  
               
             AFE2: for (reverse 0..$#$active_formatting_elements) {  
               if ($active_formatting_elements->[$_]->[0] eq $node->[0]) {  
                 splice @$active_formatting_elements, $_, 1;  
                 last AFE2;  
               }  
             } # AFE2  
             OE: for (reverse 0..$#{$self->{open_elements}}) {  
               if ($self->{open_elements}->[$_]->[0] eq $node->[0]) {  
                 splice @{$self->{open_elements}}, $_, 1;  
                 last OE;  
               }  
             } # OE  
             last AFE;  
           } elsif ($node->[0] eq '#marker') {  
             last AFE;  
           }  
         } # AFE  
1900                        
1901          $reconstruct_active_formatting_elements->($insert_to_current);            ## Para 3
1902              $self->{insertion_mode} &= ~ IN_CDATA_RCDATA_IM;
1903    
1904          !!!insert-element-t ($token->{tag_name}, $token->{attributes});            ## Para 4
1905          push @$active_formatting_elements, $self->{open_elements}->[-1];            ## TODO: $old_insertion_point = $current_insertion_point;
1906              ## TODO: $current_insertion_point = just before $self->{nc};
1907    
1908              ## Para 5
1909              ## TODO: Run the $script->[0].
1910    
1911              ## Para 6
1912              ## TODO: $current_insertion_point = $old_insertion_point;
1913    
1914              ## Para 7
1915              ## TODO: if ($pending_external_script) {
1916                ## TODO: ...
1917              ## TODO: }
1918    
1919          !!!next-token;            !!!next-token;
1920          return;            next B;
1921        } elsif ({          } else {
1922                  b => 1, big => 1, em => 1, font => 1, i => 1,            !!!cp ('t42');
1923                  nobr => 1, s => 1, small => 1, strile => 1,  
1924                  strong => 1, tt => 1, u => 1,            pop @{$self->{open_elements}};
                }->{$token->{tag_name}}) {  
         $reconstruct_active_formatting_elements->($insert_to_current);  
           
         !!!insert-element-t ($token->{tag_name}, $token->{attributes});  
         push @$active_formatting_elements, $self->{open_elements}->[-1];  
           
         !!!next-token;  
         return;  
       } elsif ($token->{tag_name} eq 'button') {  
         ## has a button element in scope  
         INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {  
           my $node = $self->{open_elements}->[$_];  
           if ($node->[1] eq 'button') {  
             !!!parse-error (type => 'in button:button');  
             !!!back-token;  
             $token = {type => 'end tag', tag_name => 'button'};  
             return;  
           } elsif ({  
                     table => 1, caption => 1, td => 1, th => 1,  
                     button => 1, marquee => 1, object => 1, html => 1,  
                    }->{$node->[1]}) {  
             last INSCOPE;  
           }  
         } # INSCOPE  
             
         $reconstruct_active_formatting_elements->($insert_to_current);  
             
         !!!insert-element-t ($token->{tag_name}, $token->{attributes});  
         push @$active_formatting_elements, ['#marker', ''];  
1925    
1926          !!!next-token;            $self->{insertion_mode} &= ~ IN_CDATA_RCDATA_IM;
1927          return;            !!!next-token;
1928        } elsif ($token->{tag_name} eq 'marquee' or            next B;
                $token->{tag_name} eq 'object') {  
         $reconstruct_active_formatting_elements->($insert_to_current);  
           
         !!!insert-element-t ($token->{tag_name}, $token->{attributes});  
         push @$active_formatting_elements, ['#marker', ''];  
           
         !!!next-token;  
         return;  
       } elsif ($token->{tag_name} eq 'xmp') {  
         $reconstruct_active_formatting_elements->($insert_to_current);  
           
         !!!insert-element-t ($token->{tag_name}, $token->{attributes});  
           
         $self->{content_model_flag} = 'CDATA';  
         delete $self->{escape}; # MUST  
           
         !!!next-token;  
         return;  
       } elsif ($token->{tag_name} eq 'table') {  
         ## has a p element in scope  
         INSCOPE: for (reverse @{$self->{open_elements}}) {  
           if ($_->[1] eq 'p') {  
             !!!back-token;  
             $token = {type => 'end tag', tag_name => 'p'};  
             return;  
           } elsif ({  
                     table => 1, caption => 1, td => 1, th => 1,  
                     button => 1, marquee => 1, object => 1, html => 1,  
                    }->{$_->[1]}) {  
             last INSCOPE;  
           }  
         } # INSCOPE  
             
         !!!insert-element-t ($token->{tag_name}, $token->{attributes});  
             
         $self->{insertion_mode} = 'in table';  
             
         !!!next-token;  
         return;  
       } elsif ({  
                 area => 1, basefont => 1, bgsound => 1, br => 1,  
                 embed => 1, img => 1, param => 1, spacer => 1, wbr => 1,  
                 image => 1,  
                }->{$token->{tag_name}}) {  
         if ($token->{tag_name} eq 'image') {  
           !!!parse-error (type => 'image');  
           $token->{tag_name} = 'img';  
1929          }          }
1930                  } elsif ($token->{type} == END_OF_FILE_TOKEN) {
1931          $reconstruct_active_formatting_elements->($insert_to_current);          delete $self->{ignore_newline};
1932            
1933          !!!insert-element-t ($token->{tag_name}, $token->{attributes});          !!!cp ('t44');
1934            !!!parse-error (type => 'not closed',
1935                            text => $self->{open_elements}->[-1]->[0]
1936                                ->manakai_local_name,
1937                            token => $token);
1938    
1939            #if ($self->{open_elements}->[-1]->[1] == SCRIPT_EL) {
1940            #  ## TODO: Mark as "already executed"
1941            #}
1942    
1943          pop @{$self->{open_elements}};          pop @{$self->{open_elements}};
1944            
1945            $self->{insertion_mode} &= ~ IN_CDATA_RCDATA_IM;
1946            ## Reprocess.
1947            next B;
1948          } else {
1949            die "$0: $token->{type}: In CDATA/RCDATA: Unknown token type";        
1950          }
1951        } elsif ($self->{insertion_mode} & IN_FOREIGN_CONTENT_IM) {
1952          if ($token->{type} == CHARACTER_TOKEN) {
1953            !!!cp ('t87.1');
1954            $self->{open_elements}->[-1]->[0]->manakai_append_text ($token->{data});
1955          !!!next-token;          !!!next-token;
1956          return;          next B;
1957        } elsif ($token->{tag_name} eq 'hr') {        } elsif ($token->{type} == START_TAG_TOKEN) {
1958          ## has a p element in scope          if ((not {mglyph => 1, malignmark => 1}->{$token->{tag_name}} and
1959          INSCOPE: for (reverse @{$self->{open_elements}}) {               $self->{open_elements}->[-1]->[1] & FOREIGN_FLOW_CONTENT_EL) or
1960            if ($_->[1] eq 'p') {              not ($self->{open_elements}->[-1]->[1] & FOREIGN_EL) or
1961              !!!back-token;              ($token->{tag_name} eq 'svg' and
1962              $token = {type => 'end tag', tag_name => 'p'};               $self->{open_elements}->[-1]->[1] == MML_AXML_EL)) {
1963              return;            ## NOTE: "using the rules for secondary insertion mode"then"continue"
1964            } elsif ({            !!!cp ('t87.2');
1965                      table => 1, caption => 1, td => 1, th => 1,            #
1966                      button => 1, marquee => 1, object => 1, html => 1,          } elsif ({
1967                     }->{$_->[1]}) {                    b => 1, big => 1, blockquote => 1, body => 1, br => 1,
1968              last INSCOPE;                    center => 1, code => 1, dd => 1, div => 1, dl => 1, dt => 1,
1969                      em => 1, embed => 1, h1 => 1, h2 => 1, h3 => 1,
1970                      h4 => 1, h5 => 1, h6 => 1, head => 1, hr => 1, i => 1,
1971                      img => 1, li => 1, listing => 1, menu => 1, meta => 1,
1972                      nobr => 1, ol => 1, p => 1, pre => 1, ruby => 1, s => 1,
1973                      small => 1, span => 1, strong => 1, strike => 1, sub => 1,
1974                      sup => 1, table => 1, tt => 1, u => 1, ul => 1, var => 1,
1975                     }->{$token->{tag_name}} or
1976                     ($token->{tag_name} eq 'font' and
1977                      ($token->{attributes}->{color} or
1978                       $token->{attributes}->{face} or
1979                       $token->{attributes}->{size}))) {
1980              !!!cp ('t87.2');
1981              !!!parse-error (type => 'not closed',
1982                              text => $self->{open_elements}->[-1]->[0]
1983                                  ->manakai_local_name,
1984                              token => $token);
1985    
1986              pop @{$self->{open_elements}}
1987                  while $self->{open_elements}->[-1]->[1] & FOREIGN_EL;
1988    
1989              $self->{insertion_mode} &= ~ IN_FOREIGN_CONTENT_IM;
1990              ## Reprocess.
1991              next B;
1992            } else {
1993              my $nsuri = $self->{open_elements}->[-1]->[0]->namespace_uri;
1994              my $tag_name = $token->{tag_name};
1995              if ($nsuri eq $SVG_NS) {
1996                $tag_name = {
1997                   altglyph => 'altGlyph',
1998                   altglyphdef => 'altGlyphDef',
1999                   altglyphitem => 'altGlyphItem',
2000                   animatecolor => 'animateColor',
2001                   animatemotion => 'animateMotion',
2002                   animatetransform => 'animateTransform',
2003                   clippath => 'clipPath',
2004                   feblend => 'feBlend',
2005                   fecolormatrix => 'feColorMatrix',
2006                   fecomponenttransfer => 'feComponentTransfer',
2007                   fecomposite => 'feComposite',
2008                   feconvolvematrix => 'feConvolveMatrix',
2009                   fediffuselighting => 'feDiffuseLighting',
2010                   fedisplacementmap => 'feDisplacementMap',
2011                   fedistantlight => 'feDistantLight',
2012                   feflood => 'feFlood',
2013                   fefunca => 'feFuncA',
2014                   fefuncb => 'feFuncB',
2015                   fefuncg => 'feFuncG',
2016                   fefuncr => 'feFuncR',
2017                   fegaussianblur => 'feGaussianBlur',
2018                   feimage => 'feImage',
2019                   femerge => 'feMerge',
2020                   femergenode => 'feMergeNode',
2021                   femorphology => 'feMorphology',
2022                   feoffset => 'feOffset',
2023                   fepointlight => 'fePointLight',
2024                   fespecularlighting => 'feSpecularLighting',
2025                   fespotlight => 'feSpotLight',
2026                   fetile => 'feTile',
2027                   feturbulence => 'feTurbulence',
2028                   foreignobject => 'foreignObject',
2029                   glyphref => 'glyphRef',
2030                   lineargradient => 'linearGradient',
2031                   radialgradient => 'radialGradient',
2032                   #solidcolor => 'solidColor', ## NOTE: Commented in spec (SVG1.2)
2033                   textpath => 'textPath',  
2034                }->{$tag_name} || $tag_name;
2035            }            }
2036          } # INSCOPE  
2037                        ## "adjust SVG attributes" (SVG only) - done in insert-element-f
2038          !!!insert-element-t ($token->{tag_name}, $token->{attributes});  
2039          pop @{$self->{open_elements}};            ## "adjust foreign attributes" - done in insert-element-f
2040              
2041          !!!next-token;            !!!insert-element-f ($nsuri, $tag_name, $token->{attributes}, $token);
2042          return;  
2043        } elsif ($token->{tag_name} eq 'input') {            if ($self->{self_closing}) {
2044          $reconstruct_active_formatting_elements->($insert_to_current);              pop @{$self->{open_elements}};
2045                        !!!ack ('t87.3');
2046          !!!insert-element-t ($token->{tag_name}, $token->{attributes});            } else {
2047          ## TODO: associate with $self->{form_element} if defined              !!!cp ('t87.4');
         pop @{$self->{open_elements}};  
           
         !!!next-token;  
         return;  
       } elsif ($token->{tag_name} eq 'isindex') {  
         !!!parse-error (type => 'isindex');  
           
         if (defined $self->{form_element}) {  
           ## Ignore the token  
           !!!next-token;  
           return;  
         } else {  
           my $at = $token->{attributes};  
           $at->{name} = {name => 'name', value => 'isindex'};  
           my @tokens = (  
                         {type => 'start tag', tag_name => 'form'},  
                         {type => 'start tag', tag_name => 'hr'},  
                         {type => 'start tag', tag_name => 'p'},  
                         {type => 'start tag', tag_name => 'label'},  
                         {type => 'character',  
                          data => 'This is a searchable index. Insert your search keywords here: '}, # SHOULD  
                         ## TODO: make this configurable  
                         {type => 'start tag', tag_name => 'input', attributes => $at},  
                         #{type => 'character', data => ''}, # SHOULD  
                         {type => 'end tag', tag_name => 'label'},  
                         {type => 'end tag', tag_name => 'p'},  
                         {type => 'start tag', tag_name => 'hr'},  
                         {type => 'end tag', tag_name => 'form'},  
                        );  
           $token = shift @tokens;  
           !!!back-token (@tokens);  
           return;  
         }  
       } elsif ({  
                 textarea => 1,  
                 iframe => 1,  
                 noembed => 1,  
                 noframes => 1,  
                 noscript => 0, ## TODO: 1 if scripting is enabled  
                }->{$token->{tag_name}}) {  
         my $tag_name = $token->{tag_name};  
         my $el;  
         !!!create-element ($el, $token->{tag_name}, $token->{attributes});  
           
         if ($token->{tag_name} eq 'textarea') {  
           ## TODO: $self->{form_element} if defined  
           $self->{content_model_flag} = 'RCDATA';  
         } else {  
           $self->{content_model_flag} = 'CDATA';  
         }  
         delete $self->{escape}; # MUST  
           
         $insert->($el);  
           
         my $text = '';  
         if ($token->{tag_name} eq 'textarea') {  
           !!!next-token;  
           if ($token->{type} eq 'character') {  
             $token->{data} =~ s/^\x0A//;  
             unless (length $token->{data}) {  
               !!!next-token;  
             }  
2048            }            }
2049          } else {  
           !!!next-token;  
         }  
         while ($token->{type} eq 'character') {  
           $text .= $token->{data};  
2050            !!!next-token;            !!!next-token;
2051              next B;
2052          }          }
2053          if (length $text) {        } elsif ($token->{type} == END_TAG_TOKEN) {
2054            $el->manakai_append_text ($text);          ## NOTE: "using the rules for secondary insertion mode" then "continue"
2055          }          if ($token->{tag_name} eq 'script') {
2056                      !!!cp ('t87.41');
2057          $self->{content_model_flag} = 'PCDATA';            #
2058                      ## XXXscript: Execute script here.
         if ($token->{type} eq 'end tag' and  
             $token->{tag_name} eq $tag_name) {  
           ## Ignore the token  
2059          } else {          } else {
2060            if ($token->{tag_name} eq 'textarea') {            !!!cp ('t87.5');
2061              !!!parse-error (type => 'in RCDATA:#'.$token->{type});            #
           } else {  
             !!!parse-error (type => 'in CDATA:#'.$token->{type});  
           }  
           ## ISSUE: And ignore?  
2062          }          }
2063          !!!next-token;        } elsif ($token->{type} == END_OF_FILE_TOKEN) {
2064          return;          !!!cp ('t87.6');
2065        } elsif ($token->{tag_name} eq 'select') {          !!!parse-error (type => 'not closed',
2066          $reconstruct_active_formatting_elements->($insert_to_current);                          text => $self->{open_elements}->[-1]->[0]
2067                                        ->manakai_local_name,
2068          !!!insert-element-t ($token->{tag_name}, $token->{attributes});                          token => $token);
2069            
2070          $self->{insertion_mode} = 'in select';          pop @{$self->{open_elements}}
2071          !!!next-token;              while $self->{open_elements}->[-1]->[1] & FOREIGN_EL;
2072          return;  
2073        } elsif ({          ## NOTE: |<span><svg>| ... two parse errors, |<svg>| ... a parse error.
2074                  caption => 1, col => 1, colgroup => 1, frame => 1,  
2075                  frameset => 1, head => 1, option => 1, optgroup => 1,          $self->{insertion_mode} &= ~ IN_FOREIGN_CONTENT_IM;
2076                  tbody => 1, td => 1, tfoot => 1, th => 1,          ## Reprocess.
2077                  thead => 1, tr => 1,          next B;
                }->{$token->{tag_name}}) {  
         !!!parse-error (type => 'in body:'.$token->{tag_name});  
         ## Ignore the token  
         !!!next-token;  
         return;  
           
         ## ISSUE: An issue on HTML5 new elements in the spec.  
2078        } else {        } else {
2079          $reconstruct_active_formatting_elements->($insert_to_current);          die "$0: $token->{type}: Unknown token type";        
           
         !!!insert-element-t ($token->{tag_name}, $token->{attributes});  
           
         !!!next-token;  
         return;  
2080        }        }
2081      } elsif ($token->{type} eq 'end tag') {      }
2082        if ($token->{tag_name} eq 'body') {  
2083          if (@{$self->{open_elements}} > 1 and $self->{open_elements}->[1]->[1] eq 'body') {      if ($self->{insertion_mode} & HEAD_IMS) {
2084            ## ISSUE: There is an issue in the spec.        if ($token->{type} == CHARACTER_TOKEN) {
2085            if ($self->{open_elements}->[-1]->[1] ne 'body') {          if ($token->{data} =~ s/^([\x09\x0A\x0C\x20]+)//) {
2086              !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);            unless ($self->{insertion_mode} == BEFORE_HEAD_IM) {
2087            }              if ($self->{head_element_inserted}) {
2088            $self->{insertion_mode} = 'after body';                !!!cp ('t88.3');
2089            !!!next-token;                $self->{open_elements}->[-1]->[0]->append_child
2090            return;                  ($self->{document}->create_text_node ($1));
2091          } else {                delete $self->{head_element_inserted};
2092            !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});                ## NOTE: |</head> <link> |
2093            ## Ignore the token                #
2094            !!!next-token;              } else {
2095            return;                !!!cp ('t88.2');
2096          }                $self->{open_elements}->[-1]->[0]->manakai_append_text ($1);
2097        } elsif ($token->{tag_name} eq 'html') {                ## NOTE: |</head> &#x20;|
2098          if (@{$self->{open_elements}} > 1 and $self->{open_elements}->[1]->[1] eq 'body') {                #
           ## ISSUE: There is an issue in the spec.  
           if ($self->{open_elements}->[-1]->[1] ne 'body') {  
             !!!parse-error (type => 'not closed:'.$self->{open_elements}->[1]->[1]);  
           }  
           $self->{insertion_mode} = 'after body';  
           ## reprocess  
           return;  
         } else {  
           !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
           ## Ignore the token  
           !!!next-token;  
           return;  
         }  
       } elsif ({  
                 address => 1, blockquote => 1, center => 1, dir => 1,  
                 div => 1, dl => 1, fieldset => 1, listing => 1,  
                 menu => 1, ol => 1, pre => 1, ul => 1,  
                 p => 1,  
                 dd => 1, dt => 1, li => 1,  
                 button => 1, marquee => 1, object => 1,  
                }->{$token->{tag_name}}) {  
         ## has an element in scope  
         my $i;  
         INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {  
           my $node = $self->{open_elements}->[$_];  
           if ($node->[1] eq $token->{tag_name}) {  
             ## generate implied end tags  
             if ({  
                  dd => ($token->{tag_name} ne 'dd'),  
                  dt => ($token->{tag_name} ne 'dt'),  
                  li => ($token->{tag_name} ne 'li'),  
                  p => ($token->{tag_name} ne 'p'),  
                  td => 1, th => 1, tr => 1,  
                 }->{$self->{open_elements}->[-1]->[1]}) {  
               !!!back-token;  
               $token = {type => 'end tag',  
                         tag_name => $self->{open_elements}->[-1]->[1]}; # MUST  
               return;  
2099              }              }
2100              $i = $_;            } else {
2101              last INSCOPE unless $token->{tag_name} eq 'p';              !!!cp ('t88.1');
2102            } elsif ({              ## Ignore the token.
2103                      table => 1, caption => 1, td => 1, th => 1,              #
                     button => 1, marquee => 1, object => 1, html => 1,  
                    }->{$node->[1]}) {  
             last INSCOPE;  
2104            }            }
2105          } # INSCOPE            unless (length $token->{data}) {
2106                        !!!cp ('t88');
2107          if ($self->{open_elements}->[-1]->[1] ne $token->{tag_name}) {              !!!next-token;
2108            !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);              next B;
         }  
           
         splice @{$self->{open_elements}}, $i if defined $i;  
         $clear_up_to_marker->()  
           if {  
             button => 1, marquee => 1, object => 1,  
           }->{$token->{tag_name}};  
         !!!next-token;  
         return;  
       } elsif ($token->{tag_name} eq 'form') {  
         ## has an element in scope  
         INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {  
           my $node = $self->{open_elements}->[$_];  
           if ($node->[1] eq $token->{tag_name}) {  
             ## generate implied end tags  
             if ({  
                  dd => 1, dt => 1, li => 1, p => 1,  
                  td => 1, th => 1, tr => 1,  
                 }->{$self->{open_elements}->[-1]->[1]}) {  
               !!!back-token;  
               $token = {type => 'end tag',  
                         tag_name => $self->{open_elements}->[-1]->[1]}; # MUST  
               return;  
             }  
             last INSCOPE;  
           } elsif ({  
                     table => 1, caption => 1, td => 1, th => 1,  
                     button => 1, marquee => 1, object => 1, html => 1,  
                    }->{$node->[1]}) {  
             last INSCOPE;  
2109            }            }
2110          } # INSCOPE  ## TODO: set $token->{column} appropriately
           
         if ($self->{open_elements}->[-1]->[1] eq $token->{tag_name}) {  
           pop @{$self->{open_elements}};  
         } else {  
           !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);  
2111          }          }
2112    
2113          undef $self->{form_element};          if ($self->{insertion_mode} == BEFORE_HEAD_IM) {
2114          !!!next-token;            !!!cp ('t89');
2115          return;            ## As if <head>
2116        } elsif ({            !!!create-element ($self->{head_element}, $HTML_NS, 'head',, $token);
2117                  h1 => 1, h2 => 1, h3 => 1, h4 => 1, h5 => 1, h6 => 1,            $self->{open_elements}->[-1]->[0]->append_child ($self->{head_element});
2118                 }->{$token->{tag_name}}) {            push @{$self->{open_elements}},
2119          ## has an element in scope                [$self->{head_element}, $el_category->{head}];
         my $i;  
         INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {  
           my $node = $self->{open_elements}->[$_];  
           if ({  
                h1 => 1, h2 => 1, h3 => 1, h4 => 1, h5 => 1, h6 => 1,  
               }->{$node->[1]}) {  
             ## generate implied end tags  
             if ({  
                  dd => 1, dt => 1, li => 1, p => 1,  
                  td => 1, th => 1, tr => 1,  
                 }->{$self->{open_elements}->[-1]->[1]}) {  
               !!!back-token;  
               $token = {type => 'end tag',  
                         tag_name => $self->{open_elements}->[-1]->[1]}; # MUST  
               return;  
             }  
             $i = $_;  
             last INSCOPE;  
           } elsif ({  
                     table => 1, caption => 1, td => 1, th => 1,  
                     button => 1, marquee => 1, object => 1, html => 1,  
                    }->{$node->[1]}) {  
             last INSCOPE;  
           }  
         } # INSCOPE  
           
         if ($self->{open_elements}->[-1]->[1] ne $token->{tag_name}) {  
           !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);  
         }  
           
         splice @{$self->{open_elements}}, $i if defined $i;  
         !!!next-token;  
         return;  
       } elsif ({  
                 a => 1,  
                 b => 1, big => 1, em => 1, font => 1, i => 1,  
                 nobr => 1, s => 1, small => 1, strile => 1,  
                 strong => 1, tt => 1, u => 1,  
                }->{$token->{tag_name}}) {  
         $formatting_end_tag->($token->{tag_name});  
 ## TODO: <http://html5.org/tools/web-apps-tracker?from=883&to=884>  
         return;  
       } elsif ({  
                 caption => 1, col => 1, colgroup => 1, frame => 1,  
                 frameset => 1, head => 1, option => 1, optgroup => 1,  
                 tbody => 1, td => 1, tfoot => 1, th => 1,  
                 thead => 1, tr => 1,  
                 area => 1, basefont => 1, bgsound => 1, br => 1,  
                 embed => 1, hr => 1, iframe => 1, image => 1,  
                 img => 1, input => 1, isindex => 1, noembed => 1,  
                 noframes => 1, param => 1, select => 1, spacer => 1,  
                 table => 1, textarea => 1, wbr => 1,  
                 noscript => 0, ## TODO: if scripting is enabled  
                }->{$token->{tag_name}}) {  
         !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
         ## Ignore the token  
         !!!next-token;  
         return;  
           
         ## ISSUE: Issue on HTML5 new elements in spec  
           
       } else {  
         ## Step 1  
         my $node_i = -1;  
         my $node = $self->{open_elements}->[$node_i];  
2120    
2121          ## Step 2            ## Reprocess in the "in head" insertion mode...
2122          S2: {            pop @{$self->{open_elements}};
           if ($node->[1] eq $token->{tag_name}) {  
             ## Step 1  
             ## generate implied end tags  
             if ({  
                  dd => 1, dt => 1, li => 1, p => 1,  
                  td => 1, th => 1, tr => 1,  
                 }->{$self->{open_elements}->[-1]->[1]}) {  
               !!!back-token;  
               $token = {type => 'end tag',  
                         tag_name => $self->{open_elements}->[-1]->[1]}; # MUST  
               return;  
             }  
           
             ## Step 2  
             if ($token->{tag_name} ne $self->{open_elements}->[-1]->[1]) {  
               !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);  
             }  
               
             ## Step 3  
             splice @{$self->{open_elements}}, $node_i;  
2123    
2124              !!!next-token;            ## Reprocess in the "after head" insertion mode...
2125              last S2;          } elsif ($self->{insertion_mode} == IN_HEAD_NOSCRIPT_IM) {
2126            } else {            !!!cp ('t90');
2127              ## Step 3            ## As if </noscript>
2128              if (not $formatting_category->{$node->[1]} and            pop @{$self->{open_elements}};
2129                  #not $phrasing_category->{$node->[1]} and            !!!parse-error (type => 'in noscript:#text', token => $token);
                 ($special_category->{$node->[1]} or  
                  $scoping_category->{$node->[1]})) {  
               !!!parse-error (type => 'not closed:'.$node->[1]);  
               ## Ignore the token  
               !!!next-token;  
               last S2;  
             }  
           }  
             
           ## Step 4  
           $node_i--;  
           $node = $self->{open_elements}->[$node_i];  
2130                        
2131            ## Step 5;            ## Reprocess in the "in head" insertion mode...
2132            redo S2;            ## As if </head>
2133          } # S2            pop @{$self->{open_elements}};
         return;  
       }  
     }  
   }; # $in_body  
2134    
2135    B: {            ## Reprocess in the "after head" insertion mode...
2136      if ($phase eq 'main') {          } elsif ($self->{insertion_mode} == IN_HEAD_IM) {
2137        if ($token->{type} eq 'DOCTYPE') {            !!!cp ('t91');
2138          !!!parse-error (type => 'in html:#DOCTYPE');            pop @{$self->{open_elements}};
         ## Ignore the token  
         ## Stay in the phase  
         !!!next-token;  
         redo B;  
       } elsif ($token->{type} eq 'start tag' and  
                $token->{tag_name} eq 'html') {  
         ## TODO: unless it is the first start tag token, parse-error  
         my $top_el = $self->{open_elements}->[0]->[0];  
         for my $attr_name (keys %{$token->{attributes}}) {  
           unless ($top_el->has_attribute_ns (undef, $attr_name)) {  
             $top_el->set_attribute_ns  
               (undef, [undef, $attr_name],  
                $token->{attributes}->{$attr_name}->{value});  
           }  
         }  
         !!!next-token;  
         redo B;  
       } elsif ($token->{type} eq 'end-of-file') {  
         ## Generate implied end tags  
         if ({  
              dd => 1, dt => 1, li => 1, p => 1, td => 1, th => 1, tr => 1,  
             }->{$self->{open_elements}->[-1]->[1]}) {  
           !!!back-token;  
           $token = {type => 'end tag', tag_name => $self->{open_elements}->[-1]->[1]};  
           redo B;  
         }  
           
         if (@{$self->{open_elements}} > 2 or  
             (@{$self->{open_elements}} == 2 and $self->{open_elements}->[1]->[1] ne 'body')) {  
           !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);  
         } elsif (defined $self->{inner_html_node} and  
                  @{$self->{open_elements}} > 1 and  
                  $self->{open_elements}->[1]->[1] ne 'body') {  
           !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);  
         }  
2139    
2140          ## Stop parsing            ## Reprocess in the "after head" insertion mode...
2141          last B;          } else {
2142              !!!cp ('t92');
2143            }
2144    
2145          ## ISSUE: There is an issue in the spec.          ## "after head" insertion mode
2146        } else {          ## As if <body>
2147          if ($self->{insertion_mode} eq 'before head') {          !!!insert-element ('body',, $token);
2148            if ($token->{type} eq 'character') {          $self->{insertion_mode} = IN_BODY_IM;
2149              if ($token->{data} =~ s/^([\x09\x0A\x0B\x0C\x20]+)//) {          ## reprocess
2150                $self->{open_elements}->[-1]->[0]->manakai_append_text ($1);          next B;
2151                unless (length $token->{data}) {        } elsif ($token->{type} == START_TAG_TOKEN) {
2152                  !!!next-token;          if ($token->{tag_name} eq 'head') {
2153                  redo B;            if ($self->{insertion_mode} == BEFORE_HEAD_IM) {
2154                }              !!!cp ('t93');
2155              }              !!!create-element ($self->{head_element}, $HTML_NS, $token->{tag_name}, $token->{attributes}, $token);
2156              ## As if <head>              $self->{open_elements}->[-1]->[0]->append_child
2157              !!!create-element ($self->{head_element}, 'head');                  ($self->{head_element});
2158              $self->{open_elements}->[-1]->[0]->append_child ($self->{head_element});              push @{$self->{open_elements}},
2159              push @{$self->{open_elements}}, [$self->{head_element}, 'head'];                  [$self->{head_element}, $el_category->{head}];
2160              $self->{insertion_mode} = 'in head';              $self->{insertion_mode} = IN_HEAD_IM;
2161              ## reprocess              !!!nack ('t93.1');
             redo B;  
           } elsif ($token->{type} eq 'comment') {  
             my $comment = $self->{document}->create_comment ($token->{data});  
             $self->{open_elements}->[-1]->[0]->append_child ($comment);  
2162              !!!next-token;              !!!next-token;
2163              redo B;              next B;
2164            } elsif ($token->{type} eq 'start tag') {            } elsif ($self->{insertion_mode} == AFTER_HEAD_IM) {
2165              my $attr = $token->{tag_name} eq 'head' ? $token->{attributes} : {};              !!!cp ('t93.2');
2166              !!!create-element ($self->{head_element}, 'head', $attr);              !!!parse-error (type => 'after head', text => 'head',
2167              $self->{open_elements}->[-1]->[0]->append_child ($self->{head_element});                              token => $token);
2168              push @{$self->{open_elements}}, [$self->{head_element}, 'head'];              ## Ignore the token
2169              $self->{insertion_mode} = 'in head';              !!!nack ('t93.3');
2170              if ($token->{tag_name} eq 'head') {              !!!next-token;
2171                !!!next-token;              next B;
             #} elsif ({  
             #          base => 1, link => 1, meta => 1,  
             #          script => 1, style => 1, title => 1,  
             #         }->{$token->{tag_name}}) {  
             #  ## reprocess  
             } else {  
               ## reprocess  
             }  
             redo B;  
           } elsif ($token->{type} eq 'end tag') {  
             if ($token->{tag_name} eq 'html') {  
               ## As if <head>  
               !!!create-element ($self->{head_element}, 'head');  
               $self->{open_elements}->[-1]->[0]->append_child ($self->{head_element});  
               push @{$self->{open_elements}}, [$self->{head_element}, 'head'];  
               $self->{insertion_mode} = 'in head';  
               ## reprocess  
               redo B;  
             } else {  
               !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
               ## Ignore the token  
               !!!next-token;  
               redo B;  
             }  
2172            } else {            } else {
2173              die "$0: $token->{type}: Unknown type";              !!!cp ('t95');
2174            }              !!!parse-error (type => 'in head:head',
2175          } elsif ($self->{insertion_mode} eq 'in head') {                              token => $token); # or in head noscript
2176            if ($token->{type} eq 'character') {              ## Ignore the token
2177              if ($token->{data} =~ s/^([\x09\x0A\x0B\x0C\x20]+)//) {              !!!nack ('t95.1');
               $self->{open_elements}->[-1]->[0]->manakai_append_text ($1);  
               unless (length $token->{data}) {  
                 !!!next-token;  
                 redo B;  
               }  
             }  
               
             #  
           } elsif ($token->{type} eq 'comment') {  
             my $comment = $self->{document}->create_comment ($token->{data});  
             $self->{open_elements}->[-1]->[0]->append_child ($comment);  
2178              !!!next-token;              !!!next-token;
2179              redo B;              next B;
2180            } elsif ($token->{type} eq 'start tag') {            }
2181              if ($token->{tag_name} eq 'title') {          } elsif ($self->{insertion_mode} == BEFORE_HEAD_IM) {
2182                ## NOTE: There is an "as if in head" code clone            !!!cp ('t96');
2183                my $title_el;            ## As if <head>
2184                !!!create-element ($title_el, 'title', $token->{attributes});            !!!create-element ($self->{head_element}, $HTML_NS, 'head',, $token);
2185                (defined $self->{head_element} ? $self->{head_element} : $self->{open_elements}->[-1]->[0])            $self->{open_elements}->[-1]->[0]->append_child ($self->{head_element});
2186                  ->append_child ($title_el);            push @{$self->{open_elements}},
2187                $self->{content_model_flag} = 'RCDATA';                [$self->{head_element}, $el_category->{head}];
2188                delete $self->{escape}; # MUST  
2189              $self->{insertion_mode} = IN_HEAD_IM;
2190                my $text = '';            ## Reprocess in the "in head" insertion mode...
2191                !!!next-token;          } else {
2192                while ($token->{type} eq 'character') {            !!!cp ('t97');
2193                  $text .= $token->{data};          }
2194                  !!!next-token;  
2195                }          if ($token->{tag_name} eq 'base') {
2196                if (length $text) {            if ($self->{insertion_mode} == IN_HEAD_NOSCRIPT_IM) {
2197                  $title_el->manakai_append_text ($text);              !!!cp ('t98');
2198                }              ## As if </noscript>
2199                              pop @{$self->{open_elements}};
2200                $self->{content_model_flag} = 'PCDATA';              !!!parse-error (type => 'in noscript', text => 'base',
2201                                              token => $token);
2202                if ($token->{type} eq 'end tag' and            
2203                    $token->{tag_name} eq 'title') {              $self->{insertion_mode} = IN_HEAD_IM;
2204                  ## Ignore the token              ## Reprocess in the "in head" insertion mode...
               } else {  
                 !!!parse-error (type => 'in RCDATA:#'.$token->{type});  
                 ## ISSUE: And ignore?  
               }  
               !!!next-token;  
               redo B;  
             } elsif ($token->{tag_name} eq 'style') {  
               $style_start_tag->();  
               redo B;  
             } elsif ($token->{tag_name} eq 'script') {  
               $script_start_tag->();  
               redo B;  
             } elsif ({base => 1, link => 1, meta => 1}->{$token->{tag_name}}) {  
               ## NOTE: There are "as if in head" code clones  
               my $el;  
               !!!create-element ($el, $token->{tag_name}, $token->{attributes});  
               (defined $self->{head_element} ? $self->{head_element} : $self->{open_elements}->[-1]->[0])  
                 ->append_child ($el);  
   
               !!!next-token;  
               redo B;  
             } elsif ($token->{tag_name} eq 'head') {  
               !!!parse-error (type => 'in head:head');  
               ## Ignore the token  
               !!!next-token;  
               redo B;  
             } else {  
               #  
             }  
           } elsif ($token->{type} eq 'end tag') {  
             if ($token->{tag_name} eq 'head') {  
               if ($self->{open_elements}->[-1]->[1] eq 'head') {  
                 pop @{$self->{open_elements}};  
               } else {  
                 !!!parse-error (type => 'unmatched end tag:head');  
               }  
               $self->{insertion_mode} = 'after head';  
               !!!next-token;  
               redo B;  
             } elsif ($token->{tag_name} eq 'html') {  
               #  
             } else {  
               !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
               ## Ignore the token  
               !!!next-token;  
               redo B;  
             }  
2205            } else {            } else {
2206              #              !!!cp ('t99');
2207            }            }
2208    
2209            if ($self->{open_elements}->[-1]->[1] eq 'head') {            ## NOTE: There is a "as if in head" code clone.
2210              ## As if </head>            if ($self->{insertion_mode} == AFTER_HEAD_IM) {
2211              pop @{$self->{open_elements}};              !!!cp ('t100');
2212                !!!parse-error (type => 'after head',
2213                                text => $token->{tag_name}, token => $token);
2214                push @{$self->{open_elements}},
2215                    [$self->{head_element}, $el_category->{head}];
2216                $self->{head_element_inserted} = 1;
2217              } else {
2218                !!!cp ('t101');
2219            }            }
2220            $self->{insertion_mode} = 'after head';            !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
2221            ## reprocess            pop @{$self->{open_elements}};
2222            redo B;            pop @{$self->{open_elements}} # <head>
2223                  if $self->{insertion_mode} == AFTER_HEAD_IM;
2224              !!!nack ('t101.1');
2225              !!!next-token;
2226              next B;
2227            } elsif ($token->{tag_name} eq 'link') {
2228              ## NOTE: There is a "as if in head" code clone.
2229              if ($self->{insertion_mode} == AFTER_HEAD_IM) {
2230                !!!cp ('t102');
2231                !!!parse-error (type => 'after head',
2232                                text => $token->{tag_name}, token => $token);
2233                push @{$self->{open_elements}},
2234                    [$self->{head_element}, $el_category->{head}];
2235                $self->{head_element_inserted} = 1;
2236              } else {
2237                !!!cp ('t103');
2238              }
2239              !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
2240              pop @{$self->{open_elements}};
2241              pop @{$self->{open_elements}} # <head>
2242                  if $self->{insertion_mode} == AFTER_HEAD_IM;
2243              !!!ack ('t103.1');
2244              !!!next-token;
2245              next B;
2246            } elsif ($token->{tag_name} eq 'command') {
2247              if ($self->{insertion_mode} == IN_HEAD_IM) {
2248                ## NOTE: If the insertion mode at the time of the emission
2249                ## of the token was "before head", $self->{insertion_mode}
2250                ## is already changed to |IN_HEAD_IM|.
2251    
2252            ## ISSUE: An issue in the spec.              ## NOTE: There is a "as if in head" code clone.
2253          } elsif ($self->{insertion_mode} eq 'after head') {              !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
2254            if ($token->{type} eq 'character') {              pop @{$self->{open_elements}};
2255              if ($token->{data} =~ s/^([\x09\x0A\x0B\x0C\x20]+)//) {              pop @{$self->{open_elements}} # <head>
2256                $self->{open_elements}->[-1]->[0]->manakai_append_text ($1);                  if $self->{insertion_mode} == AFTER_HEAD_IM;
2257                unless (length $token->{data}) {              !!!ack ('t103.2');
                 !!!next-token;  
                 redo B;  
               }  
             }  
               
             #  
           } elsif ($token->{type} eq 'comment') {  
             my $comment = $self->{document}->create_comment ($token->{data});  
             $self->{open_elements}->[-1]->[0]->append_child ($comment);  
2258              !!!next-token;              !!!next-token;
2259              redo B;              next B;
           } elsif ($token->{type} eq 'start tag') {  
             if ($token->{tag_name} eq 'body') {  
               !!!insert-element ('body', $token->{attributes});  
               $self->{insertion_mode} = 'in body';  
               !!!next-token;  
               redo B;  
             } elsif ($token->{tag_name} eq 'frameset') {  
               !!!insert-element ('frameset', $token->{attributes});  
               $self->{insertion_mode} = 'in frameset';  
               !!!next-token;  
               redo B;  
             } elsif ({  
                       base => 1, link => 1, meta => 1,  
                       script => 1, style => 1, title => 1,  
                      }->{$token->{tag_name}}) {  
               !!!parse-error (type => 'after head:'.$token->{tag_name});  
               $self->{insertion_mode} = 'in head';  
               ## reprocess  
               redo B;  
             } else {  
               #  
             }  
2260            } else {            } else {
2261                ## NOTE: "in head noscript" or "after head" insertion mode
2262                ## - in these cases, these tags are treated as same as
2263                ## normal in-body tags.
2264                !!!cp ('t103.3');
2265              #              #
2266            }            }
2267                      } elsif ($token->{tag_name} eq 'meta') {
2268            ## As if <body>            ## NOTE: There is a "as if in head" code clone.
2269            !!!insert-element ('body');            if ($self->{insertion_mode} == AFTER_HEAD_IM) {
2270            $self->{insertion_mode} = 'in body';              !!!cp ('t104');
2271            ## reprocess              !!!parse-error (type => 'after head',
2272            redo B;                              text => $token->{tag_name}, token => $token);
2273          } elsif ($self->{insertion_mode} eq 'in body') {              push @{$self->{open_elements}},
2274            if ($token->{type} eq 'character') {                  [$self->{head_element}, $el_category->{head}];
2275              ## NOTE: There is a code clone of "character in body".              $self->{head_element_inserted} = 1;
             $reconstruct_active_formatting_elements->($insert_to_current);  
               
             $self->{open_elements}->[-1]->[0]->manakai_append_text ($token->{data});  
   
             !!!next-token;  
             redo B;  
           } elsif ($token->{type} eq 'comment') {  
             ## NOTE: There is a code clone of "comment in body".  
             my $comment = $self->{document}->create_comment ($token->{data});  
             $self->{open_elements}->[-1]->[0]->append_child ($comment);  
             !!!next-token;  
             redo B;  
2276            } else {            } else {
2277              $in_body->($insert_to_current);              !!!cp ('t105');
             redo B;  
2278            }            }
2279          } elsif ($self->{insertion_mode} eq 'in table') {            !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
2280            if ($token->{type} eq 'character') {            my $meta_el = pop @{$self->{open_elements}};
             ## NOTE: There are "character in table" code clones.  
             if ($token->{data} =~ s/^([\x09\x0A\x0B\x0C\x20]+)//) {  
               $self->{open_elements}->[-1]->[0]->manakai_append_text ($1);  
                 
               unless (length $token->{data}) {  
                 !!!next-token;  
                 redo B;  
               }  
             }  
   
             !!!parse-error (type => 'in table:#character');  
2281    
2282              ## As if in body, but insert into foster parent element                unless ($self->{confident}) {
2283              ## ISSUE: Spec says that "whenever a node would be inserted                  if ($token->{attributes}->{charset}) {
2284              ## into the current node" while characters might not be                    !!!cp ('t106');
2285              ## result in a new Text node.                    ## NOTE: Whether the encoding is supported or not is handled
2286              $reconstruct_active_formatting_elements->($insert_to_foster);                    ## in the {change_encoding} callback.
2287                                  $self->{change_encoding}
2288              if ({                        ->($self, $token->{attributes}->{charset}->{value},
2289                   table => 1, tbody => 1, tfoot => 1,                           $token);
2290                   thead => 1, tr => 1,                    
2291                  }->{$self->{open_elements}->[-1]->[1]}) {                    $meta_el->[0]->get_attribute_node_ns (undef, 'charset')
2292                # MUST                        ->set_user_data (manakai_has_reference =>
2293                my $foster_parent_element;                                             $token->{attributes}->{charset}
2294                my $next_sibling;                                                 ->{has_reference});
2295                my $prev_sibling;                  } elsif ($token->{attributes}->{content}) {
2296                OE: for (reverse 0..$#{$self->{open_elements}}) {                    if ($token->{attributes}->{content}->{value}
2297                  if ($self->{open_elements}->[$_]->[1] eq 'table') {                        =~ /[Cc][Hh][Aa][Rr][Ss][Ee][Tt]
2298                    my $parent = $self->{open_elements}->[$_]->[0]->parent_node;                            [\x09\x0A\x0C\x0D\x20]*=
2299                    if (defined $parent and $parent->node_type == 1) {                            [\x09\x0A\x0C\x0D\x20]*(?>"([^"]*)"|'([^']*)'|
2300                      $foster_parent_element = $parent;                            ([^"'\x09\x0A\x0C\x0D\x20]
2301                      $next_sibling = $self->{open_elements}->[$_]->[0];                             [^\x09\x0A\x0C\x0D\x20\x3B]*))/x) {
2302                      $prev_sibling = $next_sibling->previous_sibling;                      !!!cp ('t107');
2303                        ## NOTE: Whether the encoding is supported or not is handled
2304                        ## in the {change_encoding} callback.
2305                        $self->{change_encoding}
2306                            ->($self, defined $1 ? $1 : defined $2 ? $2 : $3,
2307                               $token);
2308                        $meta_el->[0]->get_attribute_node_ns (undef, 'content')
2309                            ->set_user_data (manakai_has_reference =>
2310                                                 $token->{attributes}->{content}
2311                                                       ->{has_reference});
2312                    } else {                    } else {
2313                      $foster_parent_element = $self->{open_elements}->[$_ - 1]->[0];                      !!!cp ('t108');
                     $prev_sibling = $foster_parent_element->last_child;  
2314                    }                    }
                   last OE;  
2315                  }                  }
               } # OE  
               $foster_parent_element = $self->{open_elements}->[0]->[0] and  
               $prev_sibling = $foster_parent_element->last_child  
                 unless defined $foster_parent_element;  
               if (defined $prev_sibling and  
                   $prev_sibling->node_type == 3) {  
                 $prev_sibling->manakai_append_text ($token->{data});  
2316                } else {                } else {
2317                  $foster_parent_element->insert_before                  if ($token->{attributes}->{charset}) {
2318                    ($self->{document}->create_text_node ($token->{data}),                    !!!cp ('t109');
2319                     $next_sibling);                    $meta_el->[0]->get_attribute_node_ns (undef, 'charset')
2320                }                        ->set_user_data (manakai_has_reference =>
2321              } else {                                             $token->{attributes}->{charset}
2322                $self->{open_elements}->[-1]->[0]->manakai_append_text ($token->{data});                                                 ->{has_reference});
2323              }                  }
2324                                if ($token->{attributes}->{content}) {
2325              !!!next-token;                    !!!cp ('t110');
2326              redo B;                    $meta_el->[0]->get_attribute_node_ns (undef, 'content')
2327            } elsif ($token->{type} eq 'comment') {                        ->set_user_data (manakai_has_reference =>
2328              my $comment = $self->{document}->create_comment ($token->{data});                                             $token->{attributes}->{content}
2329              $self->{open_elements}->[-1]->[0]->append_child ($comment);                                                 ->{has_reference});
2330              !!!next-token;                  }
             redo B;  
           } elsif ($token->{type} eq 'start tag') {  
             if ({  
                  caption => 1,  
                  colgroup => 1,  
                  tbody => 1, tfoot => 1, thead => 1,  
                 }->{$token->{tag_name}}) {  
               ## Clear back to table context  
               while ($self->{open_elements}->[-1]->[1] ne 'table' and  
                      $self->{open_elements}->[-1]->[1] ne 'html') {  
                 !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);  
                 pop @{$self->{open_elements}};  
2331                }                }
2332    
2333                push @$active_formatting_elements, ['#marker', '']                pop @{$self->{open_elements}} # <head>
2334                  if $token->{tag_name} eq 'caption';                    if $self->{insertion_mode} == AFTER_HEAD_IM;
2335                  !!!ack ('t110.1');
               !!!insert-element ($token->{tag_name}, $token->{attributes});  
               $self->{insertion_mode} = {  
                                  caption => 'in caption',  
                                  colgroup => 'in column group',  
                                  tbody => 'in table body',  
                                  tfoot => 'in table body',  
                                  thead => 'in table body',  
                                 }->{$token->{tag_name}};  
2336                !!!next-token;                !!!next-token;
2337                redo B;                next B;
2338              } elsif ({          } elsif ($token->{tag_name} eq 'title') {
2339                        col => 1,            if ($self->{insertion_mode} == IN_HEAD_NOSCRIPT_IM) {
2340                        td => 1, th => 1, tr => 1,              !!!cp ('t111');
2341                       }->{$token->{tag_name}}) {              ## As if </noscript>
2342                ## Clear back to table context              pop @{$self->{open_elements}};
2343                while ($self->{open_elements}->[-1]->[1] ne 'table' and              !!!parse-error (type => 'in noscript', text => 'title',
2344                       $self->{open_elements}->[-1]->[1] ne 'html') {                              token => $token);
2345                  !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);            
2346                  pop @{$self->{open_elements}};              $self->{insertion_mode} = IN_HEAD_IM;
2347                }              ## Reprocess in the "in head" insertion mode...
2348              } elsif ($self->{insertion_mode} == AFTER_HEAD_IM) {
2349                !!!cp ('t112');
2350                !!!parse-error (type => 'after head',
2351                                text => $token->{tag_name}, token => $token);
2352                push @{$self->{open_elements}},
2353                    [$self->{head_element}, $el_category->{head}];
2354                $self->{head_element_inserted} = 1;
2355              } else {
2356                !!!cp ('t113');
2357              }
2358    
2359                !!!insert-element ($token->{tag_name} eq 'col' ? 'colgroup' : 'tbody');            ## NOTE: There is a "as if in head" code clone.
2360                $self->{insertion_mode} = $token->{tag_name} eq 'col'            $parse_rcdata->(RCDATA_CONTENT_MODEL);
                 ? 'in column group' : 'in table body';  
               ## reprocess  
               redo B;  
             } elsif ($token->{tag_name} eq 'table') {  
               ## NOTE: There are code clones for this "table in table"  
               !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);  
2361    
2362                ## As if </table>            ## NOTE: At this point the stack of open elements contain
2363                ## have a table element in table scope            ## the |head| element (index == -2) and the |script| element
2364                my $i;            ## (index == -1).  In the "after head" insertion mode the
2365                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {            ## |head| element is inserted only for the purpose of
2366                  my $node = $self->{open_elements}->[$_];            ## providing the context for the |script| element, and
2367                  if ($node->[1] eq 'table') {            ## therefore we can now and have to remove the element from
2368                    $i = $_;            ## the stack.
2369                    last INSCOPE;            splice @{$self->{open_elements}}, -2, 1, () # <head>
2370                  } elsif ({                if ($self->{insertion_mode} & IM_MASK) == AFTER_HEAD_IM;
2371                            table => 1, html => 1,            next B;
2372                           }->{$node->[1]}) {          } elsif ($token->{tag_name} eq 'style' or
2373                    last INSCOPE;                   $token->{tag_name} eq 'noframes') {
2374                  }            ## NOTE: Or (scripting is enabled and tag_name eq 'noscript' and
2375                } # INSCOPE            ## insertion mode IN_HEAD_IM)
2376                unless (defined $i) {            ## NOTE: There is a "as if in head" code clone.
2377                  !!!parse-error (type => 'unmatched end tag:table');            if ($self->{insertion_mode} == AFTER_HEAD_IM) {
2378                  ## Ignore tokens </table><table>              !!!cp ('t114');
2379                !!!parse-error (type => 'after head',
2380                                text => $token->{tag_name}, token => $token);
2381                push @{$self->{open_elements}},
2382                    [$self->{head_element}, $el_category->{head}];
2383                $self->{head_element_inserted} = 1;
2384              } else {
2385                !!!cp ('t115');
2386              }
2387              $parse_rcdata->(CDATA_CONTENT_MODEL);
2388              ## ISSUE: A spec bug [Bug 6038]
2389              splice @{$self->{open_elements}}, -2, 1, () # <head>
2390                  if ($self->{insertion_mode} & IM_MASK) == AFTER_HEAD_IM;
2391              next B;
2392            } elsif ($token->{tag_name} eq 'noscript') {
2393                  if ($self->{insertion_mode} == IN_HEAD_IM) {
2394                    !!!cp ('t116');
2395                    ## NOTE: and scripting is disalbed
2396                    !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
2397                    $self->{insertion_mode} = IN_HEAD_NOSCRIPT_IM;
2398                    !!!nack ('t116.1');
2399                    !!!next-token;
2400                    next B;
2401                  } elsif ($self->{insertion_mode} == IN_HEAD_NOSCRIPT_IM) {
2402                    !!!cp ('t117');
2403                    !!!parse-error (type => 'in noscript', text => 'noscript',
2404                                    token => $token);
2405                    ## Ignore the token
2406                    !!!nack ('t117.1');
2407                  !!!next-token;                  !!!next-token;
2408                  redo B;                  next B;
2409                  } else {
2410                    !!!cp ('t118');
2411                    #
2412                }                }
2413                          } elsif ($token->{tag_name} eq 'script') {
2414                ## generate implied end tags            if ($self->{insertion_mode} == IN_HEAD_NOSCRIPT_IM) {
2415                if ({              !!!cp ('t119');
2416                     dd => 1, dt => 1, li => 1, p => 1,              ## As if </noscript>
2417                     td => 1, th => 1, tr => 1,              pop @{$self->{open_elements}};
2418                    }->{$self->{open_elements}->[-1]->[1]}) {              !!!parse-error (type => 'in noscript', text => 'script',
2419                  !!!back-token; # <table>                              token => $token);
2420                  $token = {type => 'end tag', tag_name => 'table'};            
2421                  !!!back-token;              $self->{insertion_mode} = IN_HEAD_IM;
2422                  $token = {type => 'end tag',              ## Reprocess in the "in head" insertion mode...
2423                            tag_name => $self->{open_elements}->[-1]->[1]}; # MUST            } elsif ($self->{insertion_mode} == AFTER_HEAD_IM) {
2424                  redo B;              !!!cp ('t120');
2425                !!!parse-error (type => 'after head',
2426                                text => $token->{tag_name}, token => $token);
2427                push @{$self->{open_elements}},
2428                    [$self->{head_element}, $el_category->{head}];
2429                $self->{head_element_inserted} = 1;
2430              } else {
2431                !!!cp ('t121');
2432              }
2433    
2434              ## NOTE: There is a "as if in head" code clone.
2435              $script_start_tag->();
2436              ## ISSUE: A spec bug  [Bug 6038]
2437              splice @{$self->{open_elements}}, -2, 1 # <head>
2438                  if ($self->{insertion_mode} & IM_MASK) == AFTER_HEAD_IM;
2439              next B;
2440            } elsif ($token->{tag_name} eq 'body' or
2441                     $token->{tag_name} eq 'frameset') {
2442                  if ($self->{insertion_mode} == IN_HEAD_NOSCRIPT_IM) {
2443                    !!!cp ('t122');
2444                    ## As if </noscript>
2445                    pop @{$self->{open_elements}};
2446                    !!!parse-error (type => 'in noscript',
2447                                    text => $token->{tag_name}, token => $token);
2448                    
2449                    ## Reprocess in the "in head" insertion mode...
2450                    ## As if </head>
2451                    pop @{$self->{open_elements}};
2452                    
2453                    ## Reprocess in the "after head" insertion mode...
2454                  } elsif ($self->{insertion_mode} == IN_HEAD_IM) {
2455                    !!!cp ('t124');
2456                    pop @{$self->{open_elements}};
2457                    
2458                    ## Reprocess in the "after head" insertion mode...
2459                  } else {
2460                    !!!cp ('t125');
2461                }                }
2462    
2463                if ($self->{open_elements}->[-1]->[1] ne 'table') {                ## "after head" insertion mode
2464                  !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);                !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
2465                  if ($token->{tag_name} eq 'body') {
2466                    !!!cp ('t126');
2467                    $self->{insertion_mode} = IN_BODY_IM;
2468                  } elsif ($token->{tag_name} eq 'frameset') {
2469                    !!!cp ('t127');
2470                    $self->{insertion_mode} = IN_FRAMESET_IM;
2471                  } else {
2472                    die "$0: tag name: $self->{tag_name}";
2473                }                }
2474                  !!!nack ('t127.1');
2475                  !!!next-token;
2476                  next B;
2477                } else {
2478                  !!!cp ('t128');
2479                  #
2480                }
2481    
2482                splice @{$self->{open_elements}}, $i;              if ($self->{insertion_mode} == IN_HEAD_NOSCRIPT_IM) {
2483                  !!!cp ('t129');
2484                  ## As if </noscript>
2485                  pop @{$self->{open_elements}};
2486                  !!!parse-error (type => 'in noscript:/',
2487                                  text => $token->{tag_name}, token => $token);
2488                  
2489                  ## Reprocess in the "in head" insertion mode...
2490                  ## As if </head>
2491                  pop @{$self->{open_elements}};
2492    
2493                $self->_reset_insertion_mode;                ## Reprocess in the "after head" insertion mode...
2494                } elsif ($self->{insertion_mode} == IN_HEAD_IM) {
2495                  !!!cp ('t130');
2496                  ## As if </head>
2497                  pop @{$self->{open_elements}};
2498    
2499                ## reprocess                ## Reprocess in the "after head" insertion mode...
               redo B;  
2500              } else {              } else {
2501                #                !!!cp ('t131');
2502              }              }
2503            } elsif ($token->{type} eq 'end tag') {  
2504              if ($token->{tag_name} eq 'table') {              ## "after head" insertion mode
2505                ## have a table element in table scope              ## As if <body>
2506                my $i;              !!!insert-element ('body',, $token);
2507                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {              $self->{insertion_mode} = IN_BODY_IM;
2508                  my $node = $self->{open_elements}->[$_];              ## reprocess
2509                  if ($node->[1] eq $token->{tag_name}) {              !!!ack-later;
2510                    $i = $_;              next B;
2511                    last INSCOPE;            } elsif ($token->{type} == END_TAG_TOKEN) {
2512                  } elsif ({              if ($token->{tag_name} eq 'head') {
2513                            table => 1, html => 1,                if ($self->{insertion_mode} == BEFORE_HEAD_IM) {
2514                           }->{$node->[1]}) {                  !!!cp ('t132');
2515                    last INSCOPE;                  ## As if <head>
2516                  }                  !!!create-element ($self->{head_element}, $HTML_NS, 'head',, $token);
2517                } # INSCOPE                  $self->{open_elements}->[-1]->[0]->append_child ($self->{head_element});
2518                unless (defined $i) {                  push @{$self->{open_elements}},
2519                  !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});                      [$self->{head_element}, $el_category->{head}];
2520    
2521                    ## Reprocess in the "in head" insertion mode...
2522                    pop @{$self->{open_elements}};
2523                    $self->{insertion_mode} = AFTER_HEAD_IM;
2524                    !!!next-token;
2525                    next B;
2526                  } elsif ($self->{insertion_mode} == IN_HEAD_NOSCRIPT_IM) {
2527                    !!!cp ('t133');
2528                    ## As if </noscript>
2529                    pop @{$self->{open_elements}};
2530                    !!!parse-error (type => 'in noscript:/',
2531                                    text => 'head', token => $token);
2532                    
2533                    ## Reprocess in the "in head" insertion mode...
2534                    pop @{$self->{open_elements}};
2535                    $self->{insertion_mode} = AFTER_HEAD_IM;
2536                    !!!next-token;
2537                    next B;
2538                  } elsif ($self->{insertion_mode} == IN_HEAD_IM) {
2539                    !!!cp ('t134');
2540                    pop @{$self->{open_elements}};
2541                    $self->{insertion_mode} = AFTER_HEAD_IM;
2542                    !!!next-token;
2543                    next B;
2544                  } elsif ($self->{insertion_mode} == AFTER_HEAD_IM) {
2545                    !!!cp ('t134.1');
2546                    !!!parse-error (type => 'unmatched end tag', text => 'head',
2547                                    token => $token);
2548                  ## Ignore the token                  ## Ignore the token
2549                  !!!next-token;                  !!!next-token;
2550                  redo B;                  next B;
2551                  } else {
2552                    die "$0: $self->{insertion_mode}: Unknown insertion mode";
2553                }                }
2554                              } elsif ($token->{tag_name} eq 'noscript') {
2555                ## generate implied end tags                if ($self->{insertion_mode} == IN_HEAD_NOSCRIPT_IM) {
2556                if ({                  !!!cp ('t136');
2557                     dd => 1, dt => 1, li => 1, p => 1,                  pop @{$self->{open_elements}};
2558                     td => 1, th => 1, tr => 1,                  $self->{insertion_mode} = IN_HEAD_IM;
2559                    }->{$self->{open_elements}->[-1]->[1]}) {                  !!!next-token;
2560                  !!!back-token;                  next B;
2561                  $token = {type => 'end tag',                } elsif ($self->{insertion_mode} == BEFORE_HEAD_IM or
2562                            tag_name => $self->{open_elements}->[-1]->[1]}; # MUST                         $self->{insertion_mode} == AFTER_HEAD_IM) {
2563                  redo B;                  !!!cp ('t137');
2564                    !!!parse-error (type => 'unmatched end tag',
2565                                    text => 'noscript', token => $token);
2566                    ## Ignore the token ## ISSUE: An issue in the spec.
2567                    !!!next-token;
2568                    next B;
2569                  } else {
2570                    !!!cp ('t138');
2571                    #
2572                }                }
2573                } elsif ({
2574                if ($self->{open_elements}->[-1]->[1] ne 'table') {                        body => 1, html => 1,
2575                  !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);                       }->{$token->{tag_name}}) {
2576                  ## TODO: This branch is entirely redundant.
2577                  if ($self->{insertion_mode} == BEFORE_HEAD_IM or
2578                      $self->{insertion_mode} == IN_HEAD_IM or
2579                      $self->{insertion_mode} == IN_HEAD_NOSCRIPT_IM) {
2580                    !!!cp ('t140');
2581                    !!!parse-error (type => 'unmatched end tag',
2582                                    text => $token->{tag_name}, token => $token);
2583                    ## Ignore the token
2584                    !!!next-token;
2585                    next B;
2586                  } elsif ($self->{insertion_mode} == AFTER_HEAD_IM) {
2587                    !!!cp ('t140.1');
2588                    !!!parse-error (type => 'unmatched end tag',
2589                                    text => $token->{tag_name}, token => $token);
2590                    ## Ignore the token
2591                    !!!next-token;
2592                    next B;
2593                  } else {
2594                    die "$0: $self->{insertion_mode}: Unknown insertion mode";
2595                }                }
2596                } elsif ($token->{tag_name} eq 'p') {
2597                  !!!cp ('t142');
2598                  !!!parse-error (type => 'unmatched end tag',
2599                                  text => $token->{tag_name}, token => $token);
2600                  ## Ignore the token
2601                  !!!next-token;
2602                  next B;
2603            } elsif ($token->{tag_name} eq 'br') {
2604              if ($self->{insertion_mode} == BEFORE_HEAD_IM) {
2605                !!!cp ('t142.2');
2606                ## (before head) as if <head>, (in head) as if </head>
2607                !!!create-element ($self->{head_element}, $HTML_NS, 'head',, $token);
2608                $self->{open_elements}->[-1]->[0]->append_child ($self->{head_element});
2609                $self->{insertion_mode} = AFTER_HEAD_IM;
2610      
2611                ## Reprocess in the "after head" insertion mode...
2612              } elsif ($self->{insertion_mode} == IN_HEAD_IM) {
2613                !!!cp ('t143.2');
2614                ## As if </head>
2615                pop @{$self->{open_elements}};
2616                $self->{insertion_mode} = AFTER_HEAD_IM;
2617      
2618                ## Reprocess in the "after head" insertion mode...
2619              } elsif ($self->{insertion_mode} == IN_HEAD_NOSCRIPT_IM) {
2620                !!!cp ('t143.3');
2621                ## NOTE: Two parse errors for <head><noscript></br>
2622                !!!parse-error (type => 'unmatched end tag',
2623                                text => 'br', token => $token);
2624                ## As if </noscript>
2625                pop @{$self->{open_elements}};
2626                $self->{insertion_mode} = IN_HEAD_IM;
2627    
2628                splice @{$self->{open_elements}}, $i;              ## Reprocess in the "in head" insertion mode...
2629                ## As if </head>
2630                pop @{$self->{open_elements}};
2631                $self->{insertion_mode} = AFTER_HEAD_IM;
2632    
2633                $self->_reset_insertion_mode;              ## Reprocess in the "after head" insertion mode...
2634              } elsif ($self->{insertion_mode} == AFTER_HEAD_IM) {
2635                !!!cp ('t143.4');
2636                #
2637              } else {
2638                die "$0: $self->{insertion_mode}: Unknown insertion mode";
2639              }
2640    
2641                !!!next-token;            #
2642                redo B;          } else { ## Other end tags
2643              } elsif ({                !!!cp ('t145');
2644                        body => 1, caption => 1, col => 1, colgroup => 1,                !!!parse-error (type => 'unmatched end tag',
2645                        html => 1, tbody => 1, td => 1, tfoot => 1, th => 1,                                text => $token->{tag_name}, token => $token);
                       thead => 1, tr => 1,  
                      }->{$token->{tag_name}}) {  
               !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
2646                ## Ignore the token                ## Ignore the token
2647                !!!next-token;                !!!next-token;
2648                redo B;                next B;
2649                }
2650    
2651                if ($self->{insertion_mode} == IN_HEAD_NOSCRIPT_IM) {
2652                  !!!cp ('t146');
2653                  ## As if </noscript>
2654                  pop @{$self->{open_elements}};
2655                  !!!parse-error (type => 'in noscript:/',
2656                                  text => $token->{tag_name}, token => $token);
2657                  
2658                  ## Reprocess in the "in head" insertion mode...
2659                  ## As if </head>
2660                  pop @{$self->{open_elements}};
2661    
2662                  ## Reprocess in the "after head" insertion mode...
2663                } elsif ($self->{insertion_mode} == IN_HEAD_IM) {
2664                  !!!cp ('t147');
2665                  ## As if </head>
2666                  pop @{$self->{open_elements}};
2667    
2668                  ## Reprocess in the "after head" insertion mode...
2669                } elsif ($self->{insertion_mode} == BEFORE_HEAD_IM) {
2670    ## ISSUE: This case cannot be reached?
2671                  !!!cp ('t148');
2672                  !!!parse-error (type => 'unmatched end tag',
2673                                  text => $token->{tag_name}, token => $token);
2674                  ## Ignore the token ## ISSUE: An issue in the spec.
2675                  !!!next-token;
2676                  next B;
2677              } else {              } else {
2678                #                !!!cp ('t149');
2679              }              }
           } else {  
             #  
           }  
2680    
2681            !!!parse-error (type => 'in table:'.$token->{tag_name});              ## "after head" insertion mode
2682            $in_body->($insert_to_foster);              ## As if <body>
2683            redo B;              !!!insert-element ('body',, $token);
2684          } elsif ($self->{insertion_mode} eq 'in caption') {              $self->{insertion_mode} = IN_BODY_IM;
2685            if ($token->{type} eq 'character') {              ## reprocess
2686              ## NOTE: This is a code clone of "character in body".          next B;
2687          } elsif ($token->{type} == END_OF_FILE_TOKEN) {
2688            if ($self->{insertion_mode} == BEFORE_HEAD_IM) {
2689              !!!cp ('t149.1');
2690    
2691              ## NOTE: As if <head>
2692              !!!create-element ($self->{head_element}, $HTML_NS, 'head',, $token);
2693              $self->{open_elements}->[-1]->[0]->append_child
2694                  ($self->{head_element});
2695              #push @{$self->{open_elements}},
2696              #    [$self->{head_element}, $el_category->{head}];
2697              #$self->{insertion_mode} = IN_HEAD_IM;
2698              ## NOTE: Reprocess.
2699    
2700              ## NOTE: As if </head>
2701              #pop @{$self->{open_elements}};
2702              #$self->{insertion_mode} = IN_AFTER_HEAD_IM;
2703              ## NOTE: Reprocess.
2704              
2705              #
2706            } elsif ($self->{insertion_mode} == IN_HEAD_IM) {
2707              !!!cp ('t149.2');
2708    
2709              ## NOTE: As if </head>
2710              pop @{$self->{open_elements}};
2711              #$self->{insertion_mode} = IN_AFTER_HEAD_IM;
2712              ## NOTE: Reprocess.
2713    
2714              #
2715            } elsif ($self->{insertion_mode} == IN_HEAD_NOSCRIPT_IM) {
2716              !!!cp ('t149.3');
2717    
2718              !!!parse-error (type => 'in noscript:#eof', token => $token);
2719    
2720              ## As if </noscript>
2721              pop @{$self->{open_elements}};
2722              #$self->{insertion_mode} = IN_HEAD_IM;
2723              ## NOTE: Reprocess.
2724    
2725              ## NOTE: As if </head>
2726              pop @{$self->{open_elements}};
2727              #$self->{insertion_mode} = IN_AFTER_HEAD_IM;
2728              ## NOTE: Reprocess.
2729    
2730              #
2731            } else {
2732              !!!cp ('t149.4');
2733              #
2734            }
2735    
2736            ## NOTE: As if <body>
2737            !!!insert-element ('body',, $token);
2738            $self->{insertion_mode} = IN_BODY_IM;
2739            ## NOTE: Reprocess.
2740            next B;
2741          } else {
2742            die "$0: $token->{type}: Unknown token type";
2743          }
2744        } elsif ($self->{insertion_mode} & BODY_IMS) {
2745              if ($token->{type} == CHARACTER_TOKEN) {
2746                !!!cp ('t150');
2747                ## NOTE: There is a code clone of "character in body".
2748              $reconstruct_active_formatting_elements->($insert_to_current);              $reconstruct_active_formatting_elements->($insert_to_current);
2749                            
2750              $self->{open_elements}->[-1]->[0]->manakai_append_text ($token->{data});              $self->{open_elements}->[-1]->[0]->manakai_append_text ($token->{data});
2751    
2752              !!!next-token;              !!!next-token;
2753              redo B;              next B;
2754            } elsif ($token->{type} eq 'comment') {            } elsif ($token->{type} == START_TAG_TOKEN) {
             ## NOTE: This is a code clone of "comment in body".  
             my $comment = $self->{document}->create_comment ($token->{data});  
             $self->{open_elements}->[-1]->[0]->append_child ($comment);  
             !!!next-token;  
             redo B;  
           } elsif ($token->{type} eq 'start tag') {  
2755              if ({              if ({
2756                   caption => 1, col => 1, colgroup => 1, tbody => 1,                   caption => 1, col => 1, colgroup => 1, tbody => 1,
2757                   td => 1, tfoot => 1, th => 1, thead => 1, tr => 1,                   td => 1, tfoot => 1, th => 1, thead => 1, tr => 1,
2758                  }->{$token->{tag_name}}) {                  }->{$token->{tag_name}}) {
2759                !!!parse-error (type => 'not closed:caption');                if (($self->{insertion_mode} & IM_MASK) == IN_CELL_IM) {
2760                    ## have an element in table scope
2761                ## As if </caption>                  for (reverse 0..$#{$self->{open_elements}}) {
2762                ## have a table element in table scope                    my $node = $self->{open_elements}->[$_];
2763                my $i;                    if ($node->[1] == TABLE_CELL_EL) {
2764                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {                      !!!cp ('t151');
2765                  my $node = $self->{open_elements}->[$_];  
2766                  if ($node->[1] eq 'caption') {                      ## Close the cell
2767                    $i = $_;                      !!!back-token; # <x>
2768                    last INSCOPE;                      $token = {type => END_TAG_TOKEN,
2769                  } elsif ({                                tag_name => $node->[0]->manakai_local_name,
2770                            table => 1, html => 1,                                line => $token->{line},
2771                           }->{$node->[1]}) {                                column => $token->{column}};
2772                    last INSCOPE;                      next B;
2773                      } elsif ($node->[1] & TABLE_SCOPING_EL) {
2774                        !!!cp ('t152');
2775                        ## ISSUE: This case can never be reached, maybe.
2776                        last;
2777                      }
2778                  }                  }
2779                } # INSCOPE  
2780                unless (defined $i) {                  !!!cp ('t153');
2781                  !!!parse-error (type => 'unmatched end tag:caption');                  !!!parse-error (type => 'start tag not allowed',
2782                        text => $token->{tag_name}, token => $token);
2783                  ## Ignore the token                  ## Ignore the token
2784                    !!!nack ('t153.1');
2785                  !!!next-token;                  !!!next-token;
2786                  redo B;                  next B;
2787                }                } elsif (($self->{insertion_mode} & IM_MASK) == IN_CAPTION_IM) {
2788                                  !!!parse-error (type => 'not closed', text => 'caption',
2789                ## generate implied end tags                                  token => $token);
2790                if ({                  
2791                     dd => 1, dt => 1, li => 1, p => 1,                  ## NOTE: As if </caption>.
2792                     td => 1, th => 1, tr => 1,                  ## have a table element in table scope
2793                    }->{$self->{open_elements}->[-1]->[1]}) {                  my $i;
2794                  !!!back-token; # <?>                  INSCOPE: {
2795                  $token = {type => 'end tag', tag_name => 'caption'};                    for (reverse 0..$#{$self->{open_elements}}) {
2796                  !!!back-token;                      my $node = $self->{open_elements}->[$_];
2797                  $token = {type => 'end tag',                      if ($node->[1] == CAPTION_EL) {
2798                            tag_name => $self->{open_elements}->[-1]->[1]}; # MUST                        !!!cp ('t155');
2799                  redo B;                        $i = $_;
2800                }                        last INSCOPE;
2801                        } elsif ($node->[1] & TABLE_SCOPING_EL) {
2802                if ($self->{open_elements}->[-1]->[1] ne 'caption') {                        !!!cp ('t156');
2803                  !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);                        last;
2804                }                      }
2805                      }
               splice @{$self->{open_elements}}, $i;  
   
               $clear_up_to_marker->();  
2806    
2807                $self->{insertion_mode} = 'in table';                    !!!cp ('t157');
2808                      !!!parse-error (type => 'start tag not allowed',
2809                                      text => $token->{tag_name}, token => $token);
2810                      ## Ignore the token
2811                      !!!nack ('t157.1');
2812                      !!!next-token;
2813                      next B;
2814                    } # INSCOPE
2815                    
2816                    ## generate implied end tags
2817                    while ($self->{open_elements}->[-1]->[1]
2818                               & END_TAG_OPTIONAL_EL) {
2819                      !!!cp ('t158');
2820                      pop @{$self->{open_elements}};
2821                    }
2822    
2823                ## reprocess                  unless ($self->{open_elements}->[-1]->[1] == CAPTION_EL) {
2824                redo B;                    !!!cp ('t159');
2825                      !!!parse-error (type => 'not closed',
2826                                      text => $self->{open_elements}->[-1]->[0]
2827                                          ->manakai_local_name,
2828                                      token => $token);
2829                    } else {
2830                      !!!cp ('t160');
2831                    }
2832                    
2833                    splice @{$self->{open_elements}}, $i;
2834                    
2835                    $clear_up_to_marker->();
2836                    
2837                    $self->{insertion_mode} = IN_TABLE_IM;
2838                    
2839                    ## reprocess
2840                    !!!ack-later;
2841                    next B;
2842                  } else {
2843                    !!!cp ('t161');
2844                    #
2845                  }
2846              } else {              } else {
2847                  !!!cp ('t162');
2848                #                #
2849              }              }
2850            } elsif ($token->{type} eq 'end tag') {            } elsif ($token->{type} == END_TAG_TOKEN) {
2851              if ($token->{tag_name} eq 'caption') {              if ($token->{tag_name} eq 'td' or $token->{tag_name} eq 'th') {
2852                ## have a table element in table scope                if (($self->{insertion_mode} & IM_MASK) == IN_CELL_IM) {
2853                my $i;                  ## have an element in table scope
2854                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {                  my $i;
2855                  my $node = $self->{open_elements}->[$_];                  INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
2856                  if ($node->[1] eq $token->{tag_name}) {                    my $node = $self->{open_elements}->[$_];
2857                    $i = $_;                    if ($node->[0]->manakai_local_name eq $token->{tag_name}) {
2858                    last INSCOPE;                      !!!cp ('t163');
2859                  } elsif ({                      $i = $_;
2860                            table => 1, html => 1,                      last INSCOPE;
2861                           }->{$node->[1]}) {                    } elsif ($node->[1] & TABLE_SCOPING_EL) {
2862                    last INSCOPE;                      !!!cp ('t164');
2863                        last INSCOPE;
2864                      }
2865                    } # INSCOPE
2866                      unless (defined $i) {
2867                        !!!cp ('t165');
2868                        !!!parse-error (type => 'unmatched end tag',
2869                                        text => $token->{tag_name},
2870                                        token => $token);
2871                        ## Ignore the token
2872                        !!!next-token;
2873                        next B;
2874                      }
2875                    
2876                    ## generate implied end tags
2877                    while ($self->{open_elements}->[-1]->[1]
2878                               & END_TAG_OPTIONAL_EL) {
2879                      !!!cp ('t166');
2880                      pop @{$self->{open_elements}};
2881                  }                  }
2882                } # INSCOPE  
2883                unless (defined $i) {                  if ($self->{open_elements}->[-1]->[0]->manakai_local_name
2884                  !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});                          ne $token->{tag_name}) {
2885                      !!!cp ('t167');
2886                      !!!parse-error (type => 'not closed',
2887                                      text => $self->{open_elements}->[-1]->[0]
2888                                          ->manakai_local_name,
2889                                      token => $token);
2890                    } else {
2891                      !!!cp ('t168');
2892                    }
2893                    
2894                    splice @{$self->{open_elements}}, $i;
2895                    
2896                    $clear_up_to_marker->();
2897                    
2898                    $self->{insertion_mode} = IN_ROW_IM;
2899                    
2900                    !!!next-token;
2901                    next B;
2902                  } elsif (($self->{insertion_mode} & IM_MASK) == IN_CAPTION_IM) {
2903                    !!!cp ('t169');
2904                    !!!parse-error (type => 'unmatched end tag',
2905                                    text => $token->{tag_name}, token => $token);
2906                  ## Ignore the token                  ## Ignore the token
2907                  !!!next-token;                  !!!next-token;
2908                  redo B;                  next B;
2909                }                } else {
2910                                  !!!cp ('t170');
2911                ## generate implied end tags                  #
               if ({  
                    dd => 1, dt => 1, li => 1, p => 1,  
                    td => 1, th => 1, tr => 1,  
                   }->{$self->{open_elements}->[-1]->[1]}) {  
                 !!!back-token;  
                 $token = {type => 'end tag',  
                           tag_name => $self->{open_elements}->[-1]->[1]}; # MUST  
                 redo B;  
2912                }                }
2913                } elsif ($token->{tag_name} eq 'caption') {
2914                  if (($self->{insertion_mode} & IM_MASK) == IN_CAPTION_IM) {
2915                    ## have a table element in table scope
2916                    my $i;
2917                    INSCOPE: {
2918                      for (reverse 0..$#{$self->{open_elements}}) {
2919                        my $node = $self->{open_elements}->[$_];
2920                        if ($node->[1] == CAPTION_EL) {
2921                          !!!cp ('t171');
2922                          $i = $_;
2923                          last INSCOPE;
2924                        } elsif ($node->[1] & TABLE_SCOPING_EL) {
2925                          !!!cp ('t172');
2926                          last;
2927                        }
2928                      }
2929    
2930                if ($self->{open_elements}->[-1]->[1] ne 'caption') {                    !!!cp ('t173');
2931                  !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);                    !!!parse-error (type => 'unmatched end tag',
2932                                      text => $token->{tag_name}, token => $token);
2933                      ## Ignore the token
2934                      !!!next-token;
2935                      next B;
2936                    } # INSCOPE
2937                    
2938                    ## generate implied end tags
2939                    while ($self->{open_elements}->[-1]->[1]
2940                               & END_TAG_OPTIONAL_EL) {
2941                      !!!cp ('t174');
2942                      pop @{$self->{open_elements}};
2943                    }
2944                    
2945                    unless ($self->{open_elements}->[-1]->[1] == CAPTION_EL) {
2946                      !!!cp ('t175');
2947                      !!!parse-error (type => 'not closed',
2948                                      text => $self->{open_elements}->[-1]->[0]
2949                                          ->manakai_local_name,
2950                                      token => $token);
2951                    } else {
2952                      !!!cp ('t176');
2953                    }
2954                    
2955                    splice @{$self->{open_elements}}, $i;
2956                    
2957                    $clear_up_to_marker->();
2958                    
2959                    $self->{insertion_mode} = IN_TABLE_IM;
2960                    
2961                    !!!next-token;
2962                    next B;
2963                  } elsif (($self->{insertion_mode} & IM_MASK) == IN_CELL_IM) {
2964                    !!!cp ('t177');
2965                    !!!parse-error (type => 'unmatched end tag',
2966                                    text => $token->{tag_name}, token => $token);
2967                    ## Ignore the token
2968                    !!!next-token;
2969                    next B;
2970                  } else {
2971                    !!!cp ('t178');
2972                    #
2973                }                }
2974                } elsif ({
2975                          table => 1, tbody => 1, tfoot => 1,
2976                          thead => 1, tr => 1,
2977                         }->{$token->{tag_name}} and
2978                         ($self->{insertion_mode} & IM_MASK) == IN_CELL_IM) {
2979                  ## have an element in table scope
2980                  my $i;
2981                  my $tn;
2982                  INSCOPE: {
2983                    for (reverse 0..$#{$self->{open_elements}}) {
2984                      my $node = $self->{open_elements}->[$_];
2985                      if ($node->[0]->manakai_local_name eq $token->{tag_name}) {
2986                        !!!cp ('t179');
2987                        $i = $_;
2988    
2989                        ## Close the cell
2990                        !!!back-token; # </x>
2991                        $token = {type => END_TAG_TOKEN, tag_name => $tn,
2992                                  line => $token->{line},
2993                                  column => $token->{column}};
2994                        next B;
2995                      } elsif ($node->[1] == TABLE_CELL_EL) {
2996                        !!!cp ('t180');
2997                        $tn = $node->[0]->manakai_local_name;
2998                        ## NOTE: There is exactly one |td| or |th| element
2999                        ## in scope in the stack of open elements by definition.
3000                      } elsif ($node->[1] & TABLE_SCOPING_EL) {
3001                        ## ISSUE: Can this be reached?
3002                        !!!cp ('t181');
3003                        last;
3004                      }
3005                    }
3006    
3007                splice @{$self->{open_elements}}, $i;                  !!!cp ('t182');
3008                    !!!parse-error (type => 'unmatched end tag',
3009                $clear_up_to_marker->();                      text => $token->{tag_name}, token => $token);
3010                    ## Ignore the token
3011                $self->{insertion_mode} = 'in table';                  !!!next-token;
3012                    next B;
3013                !!!next-token;                } # INSCOPE
3014                redo B;              } elsif ($token->{tag_name} eq 'table' and
3015              } elsif ($token->{tag_name} eq 'table') {                       ($self->{insertion_mode} & IM_MASK) == IN_CAPTION_IM) {
3016                !!!parse-error (type => 'not closed:caption');                !!!parse-error (type => 'not closed', text => 'caption',
3017                                  token => $token);
3018    
3019                ## As if </caption>                ## As if </caption>
3020                ## have a table element in table scope                ## have a table element in table scope
3021                my $i;                my $i;
3022                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
3023                  my $node = $self->{open_elements}->[$_];                  my $node = $self->{open_elements}->[$_];
3024                  if ($node->[1] eq 'caption') {                  if ($node->[1] == CAPTION_EL) {
3025                      !!!cp ('t184');
3026                    $i = $_;                    $i = $_;
3027                    last INSCOPE;                    last INSCOPE;
3028                  } elsif ({                  } elsif ($node->[1] & TABLE_SCOPING_EL) {
3029                            table => 1, html => 1,                    !!!cp ('t185');
                          }->{$node->[1]}) {  
3030                    last INSCOPE;                    last INSCOPE;
3031                  }                  }
3032                } # INSCOPE                } # INSCOPE
3033                unless (defined $i) {                unless (defined $i) {
3034                  !!!parse-error (type => 'unmatched end tag:caption');                  !!!cp ('t186');
3035            ## TODO: Wrong error type?
3036                    !!!parse-error (type => 'unmatched end tag',
3037                                    text => 'caption', token => $token);
3038                  ## Ignore the token                  ## Ignore the token
3039                  !!!next-token;                  !!!next-token;
3040                  redo B;                  next B;
3041                }                }
3042                                
3043                ## generate implied end tags                ## generate implied end tags
3044                if ({                while ($self->{open_elements}->[-1]->[1] & END_TAG_OPTIONAL_EL) {
3045                     dd => 1, dt => 1, li => 1, p => 1,                  !!!cp ('t187');
3046                     td => 1, th => 1, tr => 1,                  pop @{$self->{open_elements}};
                   }->{$self->{open_elements}->[-1]->[1]}) {  
                 !!!back-token; # </table>  
                 $token = {type => 'end tag', tag_name => 'caption'};  
                 !!!back-token;  
                 $token = {type => 'end tag',  
                           tag_name => $self->{open_elements}->[-1]->[1]}; # MUST  
                 redo B;  
3047                }                }
3048    
3049                if ($self->{open_elements}->[-1]->[1] ne 'caption') {                unless ($self->{open_elements}->[-1]->[1] == CAPTION_EL) {
3050                  !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);                  !!!cp ('t188');
3051                    !!!parse-error (type => 'not closed',
3052                                    text => $self->{open_elements}->[-1]->[0]
3053                                        ->manakai_local_name,
3054                                    token => $token);
3055                  } else {
3056                    !!!cp ('t189');
3057                }                }
3058    
3059                splice @{$self->{open_elements}}, $i;                splice @{$self->{open_elements}}, $i;
3060    
3061                $clear_up_to_marker->();                $clear_up_to_marker->();
3062    
3063                $self->{insertion_mode} = 'in table';                $self->{insertion_mode} = IN_TABLE_IM;
3064    
3065                ## reprocess                ## reprocess
3066                redo B;                next B;
3067              } elsif ({              } elsif ({
3068                        body => 1, col => 1, colgroup => 1,                        body => 1, col => 1, colgroup => 1, html => 1,
                       html => 1, tbody => 1, td => 1, tfoot => 1,  
                       th => 1, thead => 1, tr => 1,  
3069                       }->{$token->{tag_name}}) {                       }->{$token->{tag_name}}) {
3070                !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});                if ($self->{insertion_mode} & BODY_TABLE_IMS) {
3071                ## Ignore the token                  !!!cp ('t190');
3072                redo B;                  !!!parse-error (type => 'unmatched end tag',
3073              } else {                                  text => $token->{tag_name}, token => $token);
3074                #                  ## Ignore the token
             }  
           } else {  
             #  
           }  
                 
           $in_body->($insert_to_current);  
           redo B;  
         } elsif ($self->{insertion_mode} eq 'in column group') {  
           if ($token->{type} eq 'character') {  
             if ($token->{data} =~ s/^([\x09\x0A\x0B\x0C\x20]+)//) {  
               $self->{open_elements}->[-1]->[0]->manakai_append_text ($1);  
               unless (length $token->{data}) {  
3075                  !!!next-token;                  !!!next-token;
3076                  redo B;                  next B;
3077                  } else {
3078                    !!!cp ('t191');
3079                    #
3080                }                }
3081            } elsif ({
3082                      tbody => 1, tfoot => 1,
3083                      thead => 1, tr => 1,
3084                     }->{$token->{tag_name}} and
3085                     ($self->{insertion_mode} & IM_MASK) == IN_CAPTION_IM) {
3086              !!!cp ('t192');
3087              !!!parse-error (type => 'unmatched end tag',
3088                              text => $token->{tag_name}, token => $token);
3089              ## Ignore the token
3090              !!!next-token;
3091              next B;
3092            } else {
3093              !!!cp ('t193');
3094              #
3095            }
3096          } elsif ($token->{type} == END_OF_FILE_TOKEN) {
3097            for my $entry (@{$self->{open_elements}}) {
3098              unless ($entry->[1] & ALL_END_TAG_OPTIONAL_EL) {
3099                !!!cp ('t75');
3100                !!!parse-error (type => 'in body:#eof', token => $token);
3101                last;
3102              }
3103            }
3104    
3105            ## Stop parsing.
3106            last B;
3107          } else {
3108            die "$0: $token->{type}: Unknown token type";
3109          }
3110    
3111          $insert = $insert_to_current;
3112          #
3113        } elsif ($self->{insertion_mode} & TABLE_IMS) {
3114          if ($token->{type} == START_TAG_TOKEN) {
3115            if ({
3116                 tr => (($self->{insertion_mode} & IM_MASK) != IN_ROW_IM),
3117                 th => 1, td => 1,
3118                }->{$token->{tag_name}}) {
3119              if (($self->{insertion_mode} & IM_MASK) == IN_TABLE_IM) {
3120                ## Clear back to table context
3121                while (not ($self->{open_elements}->[-1]->[1]
3122                                & TABLE_SCOPING_EL)) {
3123                  !!!cp ('t201');
3124                  pop @{$self->{open_elements}};
3125              }              }
3126                            
3127              #              !!!insert-element ('tbody',, $token);
3128            } elsif ($token->{type} eq 'comment') {              $self->{insertion_mode} = IN_TABLE_BODY_IM;
3129              my $comment = $self->{document}->create_comment ($token->{data});              ## reprocess in the "in table body" insertion mode...
3130              $self->{open_elements}->[-1]->[0]->append_child ($comment);            }
3131              !!!next-token;            
3132              redo B;            if (($self->{insertion_mode} & IM_MASK) == IN_TABLE_BODY_IM) {
3133            } elsif ($token->{type} eq 'start tag') {              unless ($token->{tag_name} eq 'tr') {
3134              if ($token->{tag_name} eq 'col') {                !!!cp ('t202');
3135                !!!insert-element ($token->{tag_name}, $token->{attributes});                !!!parse-error (type => 'missing start tag:tr', token => $token);
3136                }
3137                    
3138                ## Clear back to table body context
3139                while (not ($self->{open_elements}->[-1]->[1]
3140                                & TABLE_ROWS_SCOPING_EL)) {
3141                  !!!cp ('t203');
3142                  ## ISSUE: Can this case be reached?
3143                pop @{$self->{open_elements}};                pop @{$self->{open_elements}};
               !!!next-token;  
               redo B;  
             } else {  
               #  
3144              }              }
3145            } elsif ($token->{type} eq 'end tag') {                  
3146              if ($token->{tag_name} eq 'colgroup') {              $self->{insertion_mode} = IN_ROW_IM;
3147                if ($self->{open_elements}->[-1]->[1] eq 'html') {              if ($token->{tag_name} eq 'tr') {
3148                  !!!parse-error (type => 'unmatched end tag:colgroup');                !!!cp ('t204');
3149                  ## Ignore the token                !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
3150                  !!!next-token;                $open_tables->[-1]->[2] = 0 if @$open_tables; # ~node inserted
3151                  redo B;                !!!nack ('t204');
               } else {  
                 pop @{$self->{open_elements}}; # colgroup  
                 $self->{insertion_mode} = 'in table';  
                 !!!next-token;  
                 redo B;              
               }  
             } elsif ($token->{tag_name} eq 'col') {  
               !!!parse-error (type => 'unmatched end tag:col');  
               ## Ignore the token  
3152                !!!next-token;                !!!next-token;
3153                redo B;                next B;
3154              } else {              } else {
3155                #                !!!cp ('t205');
3156                  !!!insert-element ('tr',, $token);
3157                  ## reprocess in the "in row" insertion mode
3158              }              }
3159            } else {            } else {
3160              #              !!!cp ('t206');
3161            }            }
3162    
3163            ## As if </colgroup>                ## Clear back to table row context
3164            if ($self->{open_elements}->[-1]->[1] eq 'html') {                while (not ($self->{open_elements}->[-1]->[1]
3165              !!!parse-error (type => 'unmatched end tag:colgroup');                                & TABLE_ROW_SCOPING_EL)) {
3166              ## Ignore the token                  !!!cp ('t207');
3167              !!!next-token;                  pop @{$self->{open_elements}};
             redo B;  
           } else {  
             pop @{$self->{open_elements}}; # colgroup  
             $self->{insertion_mode} = 'in table';  
             ## reprocess  
             redo B;  
           }  
         } elsif ($self->{insertion_mode} eq 'in table body') {  
           if ($token->{type} eq 'character') {  
             ## NOTE: This is a "character in table" code clone.  
             if ($token->{data} =~ s/^([\x09\x0A\x0B\x0C\x20]+)//) {  
               $self->{open_elements}->[-1]->[0]->manakai_append_text ($1);  
                 
               unless (length $token->{data}) {  
                 !!!next-token;  
                 redo B;  
3168                }                }
3169              }                
3170              !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
3171              !!!parse-error (type => 'in table:#character');            $open_tables->[-1]->[2] = 0 if @$open_tables; # ~node inserted
3172              $self->{insertion_mode} = IN_CELL_IM;
             ## As if in body, but insert into foster parent element  
             ## ISSUE: Spec says that "whenever a node would be inserted  
             ## into the current node" while characters might not be  
             ## result in a new Text node.  
             $reconstruct_active_formatting_elements->($insert_to_foster);  
3173    
3174              if ({            push @$active_formatting_elements, ['#marker', ''];
3175                   table => 1, tbody => 1, tfoot => 1,                
3176                   thead => 1, tr => 1,            !!!nack ('t207.1');
3177                  }->{$self->{open_elements}->[-1]->[1]}) {            !!!next-token;
3178                # MUST            next B;
3179                my $foster_parent_element;          } elsif ({
3180                my $next_sibling;                    caption => 1, col => 1, colgroup => 1,
3181                my $prev_sibling;                    tbody => 1, tfoot => 1, thead => 1,
3182                OE: for (reverse 0..$#{$self->{open_elements}}) {                    tr => 1, # $self->{insertion_mode} == IN_ROW_IM
3183                  if ($self->{open_elements}->[$_]->[1] eq 'table') {                   }->{$token->{tag_name}}) {
3184                    my $parent = $self->{open_elements}->[$_]->[0]->parent_node;            if (($self->{insertion_mode} & IM_MASK) == IN_ROW_IM) {
3185                    if (defined $parent and $parent->node_type == 1) {              ## As if </tr>
3186                      $foster_parent_element = $parent;              ## have an element in table scope
3187                      $next_sibling = $self->{open_elements}->[$_]->[0];              my $i;
3188                      $prev_sibling = $next_sibling->previous_sibling;              INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
3189                    } else {                my $node = $self->{open_elements}->[$_];
3190                      $foster_parent_element = $self->{open_elements}->[$_ - 1]->[0];                if ($node->[1] == TABLE_ROW_EL) {
3191                      $prev_sibling = $foster_parent_element->last_child;                  !!!cp ('t208');
3192                    }                  $i = $_;
3193                    last OE;                  last INSCOPE;
3194                  }                } elsif ($node->[1] & TABLE_SCOPING_EL) {
3195                } # OE                  !!!cp ('t209');
3196                $foster_parent_element = $self->{open_elements}->[0]->[0] and                  last INSCOPE;
3197                $prev_sibling = $foster_parent_element->last_child                }
3198                  unless defined $foster_parent_element;              } # INSCOPE
3199                if (defined $prev_sibling and              unless (defined $i) {
3200                    $prev_sibling->node_type == 3) {                !!!cp ('t210');
3201                  $prev_sibling->manakai_append_text ($token->{data});                ## TODO: This type is wrong.
3202                } else {                !!!parse-error (type => 'unmacthed end tag',
3203                  $foster_parent_element->insert_before                                text => $token->{tag_name}, token => $token);
3204                    ($self->{document}->create_text_node ($token->{data}),                ## Ignore the token
3205                     $next_sibling);                !!!nack ('t210.1');
3206                }                !!!next-token;
3207              } else {                next B;
               $self->{open_elements}->[-1]->[0]->manakai_append_text ($token->{data});  
3208              }              }
3209                                
3210              !!!next-token;                  ## Clear back to table row context
3211              redo B;                  while (not ($self->{open_elements}->[-1]->[1]
3212            } elsif ($token->{type} eq 'comment') {                                  & TABLE_ROW_SCOPING_EL)) {
3213              ## Copied from 'in table'                    !!!cp ('t211');
3214              my $comment = $self->{document}->create_comment ($token->{data});                    ## ISSUE: Can this case be reached?
3215              $self->{open_elements}->[-1]->[0]->append_child ($comment);                    pop @{$self->{open_elements}};
3216              !!!next-token;                  }
3217              redo B;                  
3218            } elsif ($token->{type} eq 'start tag') {                  pop @{$self->{open_elements}}; # tr
3219              if ({                  $self->{insertion_mode} = IN_TABLE_BODY_IM;
3220                   tr => 1,                  if ($token->{tag_name} eq 'tr') {
3221                   th => 1, td => 1,                    !!!cp ('t212');
3222                  }->{$token->{tag_name}}) {                    ## reprocess
3223                unless ($token->{tag_name} eq 'tr') {                    !!!ack-later;
3224                  !!!parse-error (type => 'missing start tag:tr');                    next B;
3225                    } else {
3226                      !!!cp ('t213');
3227                      ## reprocess in the "in table body" insertion mode...
3228                    }
3229                }                }
3230    
3231                ## Clear back to table body context                if (($self->{insertion_mode} & IM_MASK) == IN_TABLE_BODY_IM) {
3232                while (not {                  ## have an element in table scope
3233                  tbody => 1, tfoot => 1, thead => 1, html => 1,                  my $i;
3234                }->{$self->{open_elements}->[-1]->[1]}) {                  INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
3235                  !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);                    my $node = $self->{open_elements}->[$_];
3236                  pop @{$self->{open_elements}};                    if ($node->[1] == TABLE_ROW_GROUP_EL) {
3237                }                      !!!cp ('t214');
3238                                      $i = $_;
3239                $self->{insertion_mode} = 'in row';                      last INSCOPE;
3240                if ($token->{tag_name} eq 'tr') {                    } elsif ($node->[1] & TABLE_SCOPING_EL) {
3241                  !!!insert-element ($token->{tag_name}, $token->{attributes});                      !!!cp ('t215');
3242                  !!!next-token;                      last INSCOPE;
3243                } else {                    }
3244                  !!!insert-element ('tr');                  } # INSCOPE
3245                  ## reprocess                  unless (defined $i) {
3246                }                    !!!cp ('t216');
3247                redo B;  ## TODO: This erorr type is wrong.
3248              } elsif ({                    !!!parse-error (type => 'unmatched end tag',
3249                        caption => 1, col => 1, colgroup => 1,                                    text => $token->{tag_name}, token => $token);
3250                        tbody => 1, tfoot => 1, thead => 1,                    ## Ignore the token
3251                       }->{$token->{tag_name}}) {                    !!!nack ('t216.1');
3252                ## have an element in table scope                    !!!next-token;
3253                my $i;                    next B;
               INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {  
                 my $node = $self->{open_elements}->[$_];  
                 if ({  
                      tbody => 1, thead => 1, tfoot => 1,  
                     }->{$node->[1]}) {  
                   $i = $_;  
                   last INSCOPE;  
                 } elsif ({  
                           table => 1, html => 1,  
                          }->{$node->[1]}) {  
                   last INSCOPE;  
3254                  }                  }
               } # INSCOPE  
               unless (defined $i) {  
                 !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
                 ## Ignore the token  
                 !!!next-token;  
                 redo B;  
               }  
3255    
3256                ## Clear back to table body context                  ## Clear back to table body context
3257                while (not {                  while (not ($self->{open_elements}->[-1]->[1]
3258                  tbody => 1, tfoot => 1, thead => 1, html => 1,                                  & TABLE_ROWS_SCOPING_EL)) {
3259                }->{$self->{open_elements}->[-1]->[1]}) {                    !!!cp ('t217');
3260                  !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);                    ## ISSUE: Can this state be reached?
3261                      pop @{$self->{open_elements}};
3262                    }
3263                    
3264                    ## As if <{current node}>
3265                    ## have an element in table scope
3266                    ## true by definition
3267                    
3268                    ## Clear back to table body context
3269                    ## nop by definition
3270                    
3271                  pop @{$self->{open_elements}};                  pop @{$self->{open_elements}};
3272                    $self->{insertion_mode} = IN_TABLE_IM;
3273                    ## reprocess in "in table" insertion mode...
3274                  } else {
3275                    !!!cp ('t218');
3276                }                }
3277    
3278                ## As if <{current node}>            if ($token->{tag_name} eq 'col') {
3279                ## have an element in table scope              ## Clear back to table context
3280                ## true by definition              while (not ($self->{open_elements}->[-1]->[1]
3281                                & TABLE_SCOPING_EL)) {
3282                ## Clear back to table body context                !!!cp ('t219');
3283                ## nop by definition                ## ISSUE: Can this state be reached?
   
3284                pop @{$self->{open_elements}};                pop @{$self->{open_elements}};
3285                $self->{insertion_mode} = 'in table';              }
3286                ## reprocess              
3287                redo B;              !!!insert-element ('colgroup',, $token);
3288                $self->{insertion_mode} = IN_COLUMN_GROUP_IM;
3289                ## reprocess
3290                $open_tables->[-1]->[2] = 0 if @$open_tables; # ~node inserted
3291                !!!ack-later;
3292                next B;
3293              } elsif ({
3294                        caption => 1,
3295                        colgroup => 1,
3296                        tbody => 1, tfoot => 1, thead => 1,
3297                       }->{$token->{tag_name}}) {
3298                ## Clear back to table context
3299                    while (not ($self->{open_elements}->[-1]->[1]
3300                                    & TABLE_SCOPING_EL)) {
3301                      !!!cp ('t220');
3302                      ## ISSUE: Can this state be reached?
3303                      pop @{$self->{open_elements}};
3304                    }
3305                    
3306                push @$active_formatting_elements, ['#marker', '']
3307                    if $token->{tag_name} eq 'caption';
3308                    
3309                !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
3310                $open_tables->[-1]->[2] = 0 if @$open_tables; # ~node inserted
3311                $self->{insertion_mode} = {
3312                                           caption => IN_CAPTION_IM,
3313                                           colgroup => IN_COLUMN_GROUP_IM,
3314                                           tbody => IN_TABLE_BODY_IM,
3315                                           tfoot => IN_TABLE_BODY_IM,
3316                                           thead => IN_TABLE_BODY_IM,
3317                                          }->{$token->{tag_name}};
3318                !!!next-token;
3319                !!!nack ('t220.1');
3320                next B;
3321              } else {
3322                die "$0: in table: <>: $token->{tag_name}";
3323              }
3324              } elsif ($token->{tag_name} eq 'table') {              } elsif ($token->{tag_name} eq 'table') {
3325                ## NOTE: This is a code clone of "table in table"                !!!parse-error (type => 'not closed',
3326                !!!parse-error (type => 'not closed:table');                                text => $self->{open_elements}->[-1]->[0]
3327                                      ->manakai_local_name,
3328                                  token => $token);
3329    
3330                ## As if </table>                ## As if </table>
3331                ## have a table element in table scope                ## have a table element in table scope
3332                my $i;                my $i;
3333                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
3334                  my $node = $self->{open_elements}->[$_];                  my $node = $self->{open_elements}->[$_];
3335                  if ($node->[1] eq 'table') {                  if ($node->[1] == TABLE_EL) {
3336                      !!!cp ('t221');
3337                    $i = $_;                    $i = $_;
3338                    last INSCOPE;                    last INSCOPE;
3339                  } elsif ({                  } elsif ($node->[1] & TABLE_SCOPING_EL) {
3340                            table => 1, html => 1,                    !!!cp ('t222');
                          }->{$node->[1]}) {  
3341                    last INSCOPE;                    last INSCOPE;
3342                  }                  }
3343                } # INSCOPE                } # INSCOPE
3344                unless (defined $i) {                unless (defined $i) {
3345                  !!!parse-error (type => 'unmatched end tag:table');                  !!!cp ('t223');
3346    ## TODO: The following is wrong, maybe.
3347                    !!!parse-error (type => 'unmatched end tag', text => 'table',
3348                                    token => $token);
3349                  ## Ignore tokens </table><table>                  ## Ignore tokens </table><table>
3350                    !!!nack ('t223.1');
3351                  !!!next-token;                  !!!next-token;
3352                  redo B;                  next B;
3353                }                }
3354                                
3355    ## TODO: Followings are removed from the latest spec.
3356                ## generate implied end tags                ## generate implied end tags
3357                if ({                while ($self->{open_elements}->[-1]->[1] & END_TAG_OPTIONAL_EL) {
3358                     dd => 1, dt => 1, li => 1, p => 1,                  !!!cp ('t224');
3359                     td => 1, th => 1, tr => 1,                  pop @{$self->{open_elements}};
                   }->{$self->{open_elements}->[-1]->[1]}) {  
                 !!!back-token; # <table>  
                 $token = {type => 'end tag', tag_name => 'table'};  
                 !!!back-token;  
                 $token = {type => 'end tag',  
                           tag_name => $self->{open_elements}->[-1]->[1]}; # MUST  
                 redo B;  
3360                }                }
3361    
3362                if ($self->{open_elements}->[-1]->[1] ne 'table') {                unless ($self->{open_elements}->[-1]->[1] == TABLE_EL) {
3363                  !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);                  !!!cp ('t225');
3364                    ## NOTE: |<table><tr><table>|
3365                    !!!parse-error (type => 'not closed',
3366                                    text => $self->{open_elements}->[-1]->[0]
3367                                        ->manakai_local_name,
3368                                    token => $token);
3369                  } else {
3370                    !!!cp ('t226');
3371                }                }
3372    
3373                splice @{$self->{open_elements}}, $i;                splice @{$self->{open_elements}}, $i;
3374                  pop @{$open_tables};
3375    
3376                $self->_reset_insertion_mode;                $self->_reset_insertion_mode;
   
               ## reprocess  
               redo B;  
             } else {  
               #  
             }  
           } elsif ($token->{type} eq 'end tag') {  
             if ({  
                  tbody => 1, tfoot => 1, thead => 1,  
                 }->{$token->{tag_name}}) {  
               ## have an element in table scope  
               my $i;  
               INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {  
                 my $node = $self->{open_elements}->[$_];  
                 if ($node->[1] eq $token->{tag_name}) {  
                   $i = $_;  
                   last INSCOPE;  
                 } elsif ({  
                           table => 1, html => 1,  
                          }->{$node->[1]}) {  
                   last INSCOPE;  
                 }  
               } # INSCOPE  
               unless (defined $i) {  
                 !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
                 ## Ignore the token  
                 !!!next-token;  
                 redo B;  
               }  
   
               ## Clear back to table body context  
               while (not {  
                 tbody => 1, tfoot => 1, thead => 1, html => 1,  
               }->{$self->{open_elements}->[-1]->[1]}) {  
                 !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);  
                 pop @{$self->{open_elements}};  
               }  
   
               pop @{$self->{open_elements}};  
               $self->{insertion_mode} = 'in table';  
               !!!next-token;  
               redo B;  
             } elsif ($token->{tag_name} eq 'table') {  
               ## have an element in table scope  
               my $i;  
               INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {  
                 my $node = $self->{open_elements}->[$_];  
                 if ({  
                      tbody => 1, thead => 1, tfoot => 1,  
                     }->{$node->[1]}) {  
                   $i = $_;  
                   last INSCOPE;  
                 } elsif ({  
                           table => 1, html => 1,  
                          }->{$node->[1]}) {  
                   last INSCOPE;  
                 }  
               } # INSCOPE  
               unless (defined $i) {  
                 !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
                 ## Ignore the token  
                 !!!next-token;  
                 redo B;  
               }  
3377    
3378                ## Clear back to table body context            ## reprocess
3379                while (not {            !!!ack-later;
3380                  tbody => 1, tfoot => 1, thead => 1, html => 1,            next B;
3381                }->{$self->{open_elements}->[-1]->[1]}) {          } elsif ($token->{tag_name} eq 'style') {
3382                  !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);            !!!cp ('t227.8');
3383                  pop @{$self->{open_elements}};            ## NOTE: This is a "as if in head" code clone.
3384                }            $parse_rcdata->(CDATA_CONTENT_MODEL);
3385              $open_tables->[-1]->[2] = 0 if @$open_tables; # ~node inserted
3386              next B;
3387            } elsif ($token->{tag_name} eq 'script') {
3388              !!!cp ('t227.6');
3389              ## NOTE: This is a "as if in head" code clone.
3390              $script_start_tag->();
3391              $open_tables->[-1]->[2] = 0 if @$open_tables; # ~node inserted
3392              next B;
3393            } elsif ($token->{tag_name} eq 'input') {
3394              if ($token->{attributes}->{type}) {
3395                my $type = $token->{attributes}->{type}->{value};
3396                $type =~ tr/A-Z/a-z/; ## ASCII case-insensitive.
3397                if ($type eq 'hidden') {
3398                  !!!cp ('t227.3');
3399                  !!!parse-error (type => 'in table',
3400                                  text => $token->{tag_name}, token => $token);
3401    
3402                ## As if <{current node}>                !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
3403                ## have an element in table scope                $open_tables->[-1]->[2] = 0 if @$open_tables; # ~node inserted
               ## true by definition  
3404    
3405                ## Clear back to table body context                ## TODO: form element pointer
               ## nop by definition  
3406    
3407                pop @{$self->{open_elements}};                pop @{$self->{open_elements}};
3408                $self->{insertion_mode} = 'in table';  
               ## reprocess  
               redo B;  
             } elsif ({  
                       body => 1, caption => 1, col => 1, colgroup => 1,  
                       html => 1, td => 1, th => 1, tr => 1,  
                      }->{$token->{tag_name}}) {  
               !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
               ## Ignore the token  
3409                !!!next-token;                !!!next-token;
3410                redo B;                !!!ack ('t227.2.1');
3411                  next B;
3412              } else {              } else {
3413                  !!!cp ('t227.1');
3414                #                #
3415              }              }
3416            } else {            } else {
3417                !!!cp ('t227.4');
3418              #              #
3419            }            }
3420                      } else {
3421            ## As if in table            !!!cp ('t227');
3422            !!!parse-error (type => 'in table:'.$token->{tag_name});            #
3423            $in_body->($insert_to_foster);          }
           redo B;  
         } elsif ($self->{insertion_mode} eq 'in row') {  
           if ($token->{type} eq 'character') {  
             ## NOTE: This is a "character in table" code clone.  
             if ($token->{data} =~ s/^([\x09\x0A\x0B\x0C\x20]+)//) {  
               $self->{open_elements}->[-1]->[0]->manakai_append_text ($1);  
                 
               unless (length $token->{data}) {  
                 !!!next-token;  
                 redo B;  
               }  
             }  
   
             !!!parse-error (type => 'in table:#character');  
3424    
3425              ## As if in body, but insert into foster parent element          !!!parse-error (type => 'in table', text => $token->{tag_name},
3426              ## ISSUE: Spec says that "whenever a node would be inserted                          token => $token);
             ## into the current node" while characters might not be  
             ## result in a new Text node.  
             $reconstruct_active_formatting_elements->($insert_to_foster);  
               
             if ({  
                  table => 1, tbody => 1, tfoot => 1,  
                  thead => 1, tr => 1,  
                 }->{$self->{open_elements}->[-1]->[1]}) {  
               # MUST  
               my $foster_parent_element;  
               my $next_sibling;  
               my $prev_sibling;  
               OE: for (reverse 0..$#{$self->{open_elements}}) {  
                 if ($self->{open_elements}->[$_]->[1] eq 'table') {  
                   my $parent = $self->{open_elements}->[$_]->[0]->parent_node;  
                   if (defined $parent and $parent->node_type == 1) {  
                     $foster_parent_element = $parent;  
                     $next_sibling = $self->{open_elements}->[$_]->[0];  
                     $prev_sibling = $next_sibling->previous_sibling;  
                   } else {  
                     $foster_parent_element = $self->{open_elements}->[$_ - 1]->[0];  
                     $prev_sibling = $foster_parent_element->last_child;  
                   }  
                   last OE;  
                 }  
               } # OE  
               $foster_parent_element = $self->{open_elements}->[0]->[0] and  
               $prev_sibling = $foster_parent_element->last_child  
                 unless defined $foster_parent_element;  
               if (defined $prev_sibling and  
                   $prev_sibling->node_type == 3) {  
                 $prev_sibling->manakai_append_text ($token->{data});  
               } else {  
                 $foster_parent_element->insert_before  
                   ($self->{document}->create_text_node ($token->{data}),  
                    $next_sibling);  
               }  
             } else {  
               $self->{open_elements}->[-1]->[0]->manakai_append_text ($token->{data});  
             }  
               
             !!!next-token;  
             redo B;  
           } elsif ($token->{type} eq 'comment') {  
             ## Copied from 'in table'  
             my $comment = $self->{document}->create_comment ($token->{data});  
             $self->{open_elements}->[-1]->[0]->append_child ($comment);  
             !!!next-token;  
             redo B;  
           } elsif ($token->{type} eq 'start tag') {  
             if ($token->{tag_name} eq 'th' or  
                 $token->{tag_name} eq 'td') {  
               ## Clear back to table row context  
               while (not {  
                 tr => 1, html => 1,  
               }->{$self->{open_elements}->[-1]->[1]}) {  
                 !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);  
                 pop @{$self->{open_elements}};  
               }  
                 
               !!!insert-element ($token->{tag_name}, $token->{attributes});  
               $self->{insertion_mode} = 'in cell';  
3427    
3428                push @$active_formatting_elements, ['#marker', ''];          $insert = $insert_to_foster;
3429                          #
3430                !!!next-token;        } elsif ($token->{type} == END_TAG_TOKEN) {
3431                redo B;          if ($token->{tag_name} eq 'tr' and
3432              } elsif ({              ($self->{insertion_mode} & IM_MASK) == IN_ROW_IM) {
3433                        caption => 1, col => 1, colgroup => 1,            ## have an element in table scope
                       tbody => 1, tfoot => 1, thead => 1, tr => 1,  
                      }->{$token->{tag_name}}) {  
               ## As if </tr>  
               ## have an element in table scope  
3434                my $i;                my $i;
3435                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
3436                  my $node = $self->{open_elements}->[$_];                  my $node = $self->{open_elements}->[$_];
3437                  if ($node->[1] eq 'tr') {                  if ($node->[1] == TABLE_ROW_EL) {
3438                      !!!cp ('t228');
3439                    $i = $_;                    $i = $_;
3440                    last INSCOPE;                    last INSCOPE;
3441                  } elsif ({                  } elsif ($node->[1] & TABLE_SCOPING_EL) {
3442                            table => 1, html => 1,                    !!!cp ('t229');
                          }->{$node->[1]}) {  
3443                    last INSCOPE;                    last INSCOPE;
3444                  }                  }
3445                } # INSCOPE                } # INSCOPE
3446                unless (defined $i) {                unless (defined $i) {
3447                  !!!parse-error (type => 'unmacthed end tag:'.$token->{tag_name});                  !!!cp ('t230');
3448                    !!!parse-error (type => 'unmatched end tag',
3449                                    text => $token->{tag_name}, token => $token);
3450                  ## Ignore the token                  ## Ignore the token
3451                    !!!nack ('t230.1');
3452                  !!!next-token;                  !!!next-token;
3453                  redo B;                  next B;
3454                  } else {
3455                    !!!cp ('t232');
3456                }                }
3457    
3458                ## Clear back to table row context                ## Clear back to table row context
3459                while (not {                while (not ($self->{open_elements}->[-1]->[1]
3460                  tr => 1, html => 1,                                & TABLE_ROW_SCOPING_EL)) {
3461                }->{$self->{open_elements}->[-1]->[1]}) {                  !!!cp ('t231');
3462                  !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);  ## ISSUE: Can this state be reached?
3463                  pop @{$self->{open_elements}};                  pop @{$self->{open_elements}};
3464                }                }
3465    
3466                pop @{$self->{open_elements}}; # tr                pop @{$self->{open_elements}}; # tr
3467                $self->{insertion_mode} = 'in table body';                $self->{insertion_mode} = IN_TABLE_BODY_IM;
3468                ## reprocess                !!!next-token;
3469                redo B;                !!!nack ('t231.1');
3470                  next B;
3471              } elsif ($token->{tag_name} eq 'table') {              } elsif ($token->{tag_name} eq 'table') {
3472                ## NOTE: This is a code clone of "table in table"                if (($self->{insertion_mode} & IM_MASK) == IN_ROW_IM) {
3473                !!!parse-error (type => 'not closed:table');                  ## As if </tr>
3474                    ## have an element in table scope
3475                ## As if </table>                  my $i;
3476                ## have a table element in table scope                  INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
3477                my $i;                    my $node = $self->{open_elements}->[$_];
3478                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {                    if ($node->[1] == TABLE_ROW_EL) {
3479                  my $node = $self->{open_elements}->[$_];                      !!!cp ('t233');
3480                  if ($node->[1] eq 'table') {                      $i = $_;
3481                    $i = $_;                      last INSCOPE;
3482                    last INSCOPE;                    } elsif ($node->[1] & TABLE_SCOPING_EL) {
3483                  } elsif ({                      !!!cp ('t234');
3484                            table => 1, html => 1,                      last INSCOPE;
3485                           }->{$node->[1]}) {                    }
3486                    last INSCOPE;                  } # INSCOPE
3487                    unless (defined $i) {
3488                      !!!cp ('t235');
3489    ## TODO: The following is wrong.
3490                      !!!parse-error (type => 'unmatched end tag',
3491                                      text => $token->{type}, token => $token);
3492                      ## Ignore the token
3493                      !!!nack ('t236.1');
3494                      !!!next-token;
3495                      next B;
3496                  }                  }
3497                } # INSCOPE                  
3498                unless (defined $i) {                  ## Clear back to table row context
3499                  !!!parse-error (type => 'unmatched end tag:table');                  while (not ($self->{open_elements}->[-1]->[1]
3500                  ## Ignore tokens </table><table>                                  & TABLE_ROW_SCOPING_EL)) {
3501                  !!!next-token;                    !!!cp ('t236');
3502                  redo B;  ## ISSUE: Can this state be reached?
3503                }                    pop @{$self->{open_elements}};
3504                                  }
3505                ## generate implied end tags                  
3506                if ({                  pop @{$self->{open_elements}}; # tr
3507                     dd => 1, dt => 1, li => 1, p => 1,                  $self->{insertion_mode} = IN_TABLE_BODY_IM;
3508                     td => 1, th => 1, tr => 1,                  ## reprocess in the "in table body" insertion mode...
3509                    }->{$self->{open_elements}->[-1]->[1]}) {                }
3510                  !!!back-token; # <table>  
3511                  $token = {type => 'end tag', tag_name => 'table'};                if (($self->{insertion_mode} & IM_MASK) == IN_TABLE_BODY_IM) {
3512                  !!!back-token;                  ## have an element in table scope
3513                  $token = {type => 'end tag',                  my $i;
3514                            tag_name => $self->{open_elements}->[-1]->[1]}; # MUST                  INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
3515                  redo B;                    my $node = $self->{open_elements}->[$_];
3516                }                    if ($node->[1] == TABLE_ROW_GROUP_EL) {
3517                        !!!cp ('t237');
3518                if ($self->{open_elements}->[-1]->[1] ne 'table') {                      $i = $_;
3519                  !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);                      last INSCOPE;
3520                      } elsif ($node->[1] & TABLE_SCOPING_EL) {
3521                        !!!cp ('t238');
3522                        last INSCOPE;
3523                      }
3524                    } # INSCOPE
3525                    unless (defined $i) {
3526                      !!!cp ('t239');
3527                      !!!parse-error (type => 'unmatched end tag',
3528                                      text => $token->{tag_name}, token => $token);
3529                      ## Ignore the token
3530                      !!!nack ('t239.1');
3531                      !!!next-token;
3532                      next B;
3533                    }
3534                    
3535                    ## Clear back to table body context
3536                    while (not ($self->{open_elements}->[-1]->[1]
3537                                    & TABLE_ROWS_SCOPING_EL)) {
3538                      !!!cp ('t240');
3539                      pop @{$self->{open_elements}};
3540                    }
3541                    
3542                    ## As if <{current node}>
3543                    ## have an element in table scope
3544                    ## true by definition
3545                    
3546                    ## Clear back to table body context
3547                    ## nop by definition
3548                    
3549                    pop @{$self->{open_elements}};
3550                    $self->{insertion_mode} = IN_TABLE_IM;
3551                    ## reprocess in the "in table" insertion mode...
3552                }                }
3553    
3554                splice @{$self->{open_elements}}, $i;                ## NOTE: </table> in the "in table" insertion mode.
3555                  ## When you edit the code fragment below, please ensure that
3556                  ## the code for <table> in the "in table" insertion mode
3557                  ## is synced with it.
3558    
3559                $self->_reset_insertion_mode;                ## have a table element in table scope
   
               ## reprocess  
               redo B;  
             } else {  
               #  
             }  
           } elsif ($token->{type} eq 'end tag') {  
             if ($token->{tag_name} eq 'tr') {  
               ## have an element in table scope  
3560                my $i;                my $i;
3561                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
3562                  my $node = $self->{open_elements}->[$_];                  my $node = $self->{open_elements}->[$_];
3563                  if ($node->[1] eq $token->{tag_name}) {                  if ($node->[1] == TABLE_EL) {
3564                      !!!cp ('t241');
3565                    $i = $_;                    $i = $_;
3566                    last INSCOPE;                    last INSCOPE;
3567                  } elsif ({                  } elsif ($node->[1] & TABLE_SCOPING_EL) {
3568                            table => 1, html => 1,                    !!!cp ('t242');
                          }->{$node->[1]}) {  
3569                    last INSCOPE;                    last INSCOPE;
3570                  }                  }
3571                } # INSCOPE                } # INSCOPE
3572                unless (defined $i) {                unless (defined $i) {
3573                  !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});                  !!!cp ('t243');
3574                    !!!parse-error (type => 'unmatched end tag',
3575                                    text => $token->{tag_name}, token => $token);
3576                  ## Ignore the token                  ## Ignore the token
3577                    !!!nack ('t243.1');
3578                  !!!next-token;                  !!!next-token;
3579                  redo B;                  next B;
3580                }                }
3581                    
3582                ## Clear back to table row context                splice @{$self->{open_elements}}, $i;
3583                while (not {                pop @{$open_tables};
3584                  tr => 1, html => 1,                
3585                }->{$self->{open_elements}->[-1]->[1]}) {                $self->_reset_insertion_mode;
3586                  !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);                
3587                  pop @{$self->{open_elements}};                !!!next-token;
3588                  next B;
3589                } elsif ({
3590                          tbody => 1, tfoot => 1, thead => 1,
3591                         }->{$token->{tag_name}} and
3592                         $self->{insertion_mode} & ROW_IMS) {
3593                  if (($self->{insertion_mode} & IM_MASK) == IN_ROW_IM) {
3594                    ## have an element in table scope
3595                    my $i;
3596                    INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
3597                      my $node = $self->{open_elements}->[$_];
3598                      if ($node->[0]->manakai_local_name eq $token->{tag_name}) {
3599                        !!!cp ('t247');
3600                        $i = $_;
3601                        last INSCOPE;
3602                      } elsif ($node->[1] & TABLE_SCOPING_EL) {
3603                        !!!cp ('t248');
3604                        last INSCOPE;
3605                      }
3606                    } # INSCOPE
3607                      unless (defined $i) {
3608                        !!!cp ('t249');
3609                        !!!parse-error (type => 'unmatched end tag',
3610                                        text => $token->{tag_name}, token => $token);
3611                        ## Ignore the token
3612                        !!!nack ('t249.1');
3613                        !!!next-token;
3614                        next B;
3615                      }
3616                    
3617                    ## As if </tr>
3618                    ## have an element in table scope
3619                    my $i;
3620                    INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
3621                      my $node = $self->{open_elements}->[$_];
3622                      if ($node->[1] == TABLE_ROW_EL) {
3623                        !!!cp ('t250');
3624                        $i = $_;
3625                        last INSCOPE;
3626                      } elsif ($node->[1] & TABLE_SCOPING_EL) {
3627                        !!!cp ('t251');
3628                        last INSCOPE;
3629                      }
3630                    } # INSCOPE
3631                      unless (defined $i) {
3632                        !!!cp ('t252');
3633                        !!!parse-error (type => 'unmatched end tag',
3634                                        text => 'tr', token => $token);
3635                        ## Ignore the token
3636                        !!!nack ('t252.1');
3637                        !!!next-token;
3638                        next B;
3639                      }
3640                    
3641                    ## Clear back to table row context
3642                    while (not ($self->{open_elements}->[-1]->[1]
3643                                    & TABLE_ROW_SCOPING_EL)) {
3644                      !!!cp ('t253');
3645    ## ISSUE: Can this case be reached?
3646                      pop @{$self->{open_elements}};
3647                    }
3648                    
3649                    pop @{$self->{open_elements}}; # tr
3650                    $self->{insertion_mode} = IN_TABLE_BODY_IM;
3651                    ## reprocess in the "in table body" insertion mode...
3652                }                }
3653    
               pop @{$self->{open_elements}}; # tr  
               $self->{insertion_mode} = 'in table body';  
               !!!next-token;  
               redo B;  
             } elsif ($token->{tag_name} eq 'table') {  
               ## As if </tr>  
3654                ## have an element in table scope                ## have an element in table scope
3655                my $i;                my $i;
3656                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
3657                  my $node = $self->{open_elements}->[$_];                  my $node = $self->{open_elements}->[$_];
3658                  if ($node->[1] eq 'tr') {                  if ($node->[0]->manakai_local_name eq $token->{tag_name}) {
3659                      !!!cp ('t254');
3660                    $i = $_;                    $i = $_;
3661                    last INSCOPE;                    last INSCOPE;
3662                  } elsif ({                  } elsif ($node->[1] & TABLE_SCOPING_EL) {
3663                            table => 1, html => 1,                    !!!cp ('t255');
                          }->{$node->[1]}) {  
3664                    last INSCOPE;                    last INSCOPE;
3665                  }                  }
3666                } # INSCOPE                } # INSCOPE
3667                unless (defined $i) {                unless (defined $i) {
3668                  !!!parse-error (type => 'unmatched end tag:'.$token->{type});                  !!!cp ('t256');
3669                    !!!parse-error (type => 'unmatched end tag',
3670                                    text => $token->{tag_name}, token => $token);
3671                  ## Ignore the token                  ## Ignore the token
3672                    !!!nack ('t256.1');
3673                  !!!next-token;                  !!!next-token;
3674                  redo B;                  next B;
3675                }                }
3676    
3677                ## Clear back to table row context                ## Clear back to table body context
3678                while (not {                while (not ($self->{open_elements}->[-1]->[1]
3679                  tr => 1, html => 1,                                & TABLE_ROWS_SCOPING_EL)) {
3680                }->{$self->{open_elements}->[-1]->[1]}) {                  !!!cp ('t257');
3681                  !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);  ## ISSUE: Can this case be reached?
3682                  pop @{$self->{open_elements}};                  pop @{$self->{open_elements}};
3683                }                }
3684    
3685                pop @{$self->{open_elements}}; # tr                pop @{$self->{open_elements}};
3686                $self->{insertion_mode} = 'in table body';                $self->{insertion_mode} = IN_TABLE_IM;
3687                ## reprocess                !!!nack ('t257.1');
3688                redo B;                !!!next-token;
3689                  next B;
3690              } elsif ({              } elsif ({
3691                        tbody => 1, tfoot => 1, thead => 1,                        body => 1, caption => 1, col => 1, colgroup => 1,
3692                          html => 1, td => 1, th => 1,
3693                          tr => 1, # $self->{insertion_mode} == IN_ROW_IM
3694                          tbody => 1, tfoot => 1, thead => 1, # $self->{insertion_mode} == IN_TABLE_IM
3695                       }->{$token->{tag_name}}) {                       }->{$token->{tag_name}}) {
3696                ## have an element in table scope            !!!cp ('t258');
3697                my $i;            !!!parse-error (type => 'unmatched end tag',
3698                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {                            text => $token->{tag_name}, token => $token);
3699                  my $node = $self->{open_elements}->[$_];            ## Ignore the token
3700                  if ($node->[1] eq $token->{tag_name}) {            !!!nack ('t258.1');
3701                    $i = $_;             !!!next-token;
3702                    last INSCOPE;            next B;
3703                  } elsif ({          } else {
3704                            table => 1, html => 1,            !!!cp ('t259');
3705                           }->{$node->[1]}) {            !!!parse-error (type => 'in table:/',
3706                    last INSCOPE;                            text => $token->{tag_name}, token => $token);
3707                  }  
3708                } # INSCOPE            $insert = $insert_to_foster;
3709                unless (defined $i) {            #
3710                  !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});          }
3711                  ## Ignore the token        } elsif ($token->{type} == END_OF_FILE_TOKEN) {
3712            unless ($self->{open_elements}->[-1]->[1] == HTML_EL and
3713                    @{$self->{open_elements}} == 1) { # redundant, maybe
3714              !!!parse-error (type => 'in body:#eof', token => $token);
3715              !!!cp ('t259.1');
3716              #
3717            } else {
3718              !!!cp ('t259.2');
3719              #
3720            }
3721    
3722            ## Stop parsing
3723            last B;
3724          } else {
3725            die "$0: $token->{type}: Unknown token type";
3726          }
3727        } elsif (($self->{insertion_mode} & IM_MASK) == IN_COLUMN_GROUP_IM) {
3728              if ($token->{type} == CHARACTER_TOKEN) {
3729                if ($token->{data} =~ s/^([\x09\x0A\x0C\x20]+)//) {
3730                  $self->{open_elements}->[-1]->[0]->manakai_append_text ($1);
3731                  unless (length $token->{data}) {
3732                    !!!cp ('t260');
3733                  !!!next-token;                  !!!next-token;
3734                  redo B;                  next B;
3735                }                }
3736                }
3737                ## As if </tr>              
3738                ## have an element in table scope              !!!cp ('t261');
3739                my $i;              #
3740                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {            } elsif ($token->{type} == START_TAG_TOKEN) {
3741                  my $node = $self->{open_elements}->[$_];              if ($token->{tag_name} eq 'col') {
3742                  if ($node->[1] eq 'tr') {                !!!cp ('t262');
3743                    $i = $_;                !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
3744                    last INSCOPE;                pop @{$self->{open_elements}};
3745                  } elsif ({                !!!ack ('t262.1');
3746                            table => 1, html => 1,                !!!next-token;
3747                           }->{$node->[1]}) {                next B;
3748                    last INSCOPE;              } else {
3749                  }                !!!cp ('t263');
3750                } # INSCOPE                #
3751                unless (defined $i) {              }
3752                  !!!parse-error (type => 'unmatched end tag:tr');            } elsif ($token->{type} == END_TAG_TOKEN) {
3753                if ($token->{tag_name} eq 'colgroup') {
3754                  if ($self->{open_elements}->[-1]->[1] == HTML_EL) {
3755                    !!!cp ('t264');
3756                    !!!parse-error (type => 'unmatched end tag',
3757                                    text => 'colgroup', token => $token);
3758                  ## Ignore the token                  ## Ignore the token
3759                  !!!next-token;                  !!!next-token;
3760                  redo B;                  next B;
3761                }                } else {
3762                    !!!cp ('t265');
3763                ## Clear back to table row context                  pop @{$self->{open_elements}}; # colgroup
3764                while (not {                  $self->{insertion_mode} = IN_TABLE_IM;
3765                  tr => 1, html => 1,                  !!!next-token;
3766                }->{$self->{open_elements}->[-1]->[1]}) {                  next B;            
                 !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);  
                 pop @{$self->{open_elements}};  
3767                }                }
3768                } elsif ($token->{tag_name} eq 'col') {
3769                pop @{$self->{open_elements}}; # tr                !!!cp ('t266');
3770                $self->{insertion_mode} = 'in table body';                !!!parse-error (type => 'unmatched end tag',
3771                ## reprocess                                text => 'col', token => $token);
               redo B;  
             } elsif ({  
                       body => 1, caption => 1, col => 1,  
                       colgroup => 1, html => 1, td => 1, th => 1,  
                      }->{$token->{tag_name}}) {  
               !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
3772                ## Ignore the token                ## Ignore the token
3773                !!!next-token;                !!!next-token;
3774                redo B;                next B;
3775              } else {              } else {
3776                #                !!!cp ('t267');
3777                  #
3778              }              }
3779          } elsif ($token->{type} == END_OF_FILE_TOKEN) {
3780            if ($self->{open_elements}->[-1]->[1] == HTML_EL and
3781                @{$self->{open_elements}} == 1) { # redundant, maybe
3782              !!!cp ('t270.2');
3783              ## Stop parsing.
3784              last B;
3785            } else {
3786              ## NOTE: As if </colgroup>.
3787              !!!cp ('t270.1');
3788              pop @{$self->{open_elements}}; # colgroup
3789              $self->{insertion_mode} = IN_TABLE_IM;
3790              ## Reprocess.
3791              next B;
3792            }
3793          } else {
3794            die "$0: $token->{type}: Unknown token type";
3795          }
3796    
3797              ## As if </colgroup>
3798              if ($self->{open_elements}->[-1]->[1] == HTML_EL) {
3799                !!!cp ('t269');
3800    ## TODO: Wrong error type?
3801                !!!parse-error (type => 'unmatched end tag',
3802                                text => 'colgroup', token => $token);
3803                ## Ignore the token
3804                !!!nack ('t269.1');
3805                !!!next-token;
3806                next B;
3807            } else {            } else {
3808              #              !!!cp ('t270');
3809                pop @{$self->{open_elements}}; # colgroup
3810                $self->{insertion_mode} = IN_TABLE_IM;
3811                !!!ack-later;
3812                ## reprocess
3813                next B;
3814              }
3815        } elsif ($self->{insertion_mode} & SELECT_IMS) {
3816          if ($token->{type} == CHARACTER_TOKEN) {
3817            !!!cp ('t271');
3818            $self->{open_elements}->[-1]->[0]->manakai_append_text ($token->{data});
3819            !!!next-token;
3820            next B;
3821          } elsif ($token->{type} == START_TAG_TOKEN) {
3822            if ($token->{tag_name} eq 'option') {
3823              if ($self->{open_elements}->[-1]->[1] == OPTION_EL) {
3824                !!!cp ('t272');
3825                ## As if </option>
3826                pop @{$self->{open_elements}};
3827              } else {
3828                !!!cp ('t273');
3829            }            }
3830    
3831            ## As if in table            !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
3832            !!!parse-error (type => 'in table:'.$token->{tag_name});            !!!nack ('t273.1');
3833            $in_body->($insert_to_foster);            !!!next-token;
3834            redo B;            next B;
3835          } elsif ($self->{insertion_mode} eq 'in cell') {          } elsif ($token->{tag_name} eq 'optgroup') {
3836            if ($token->{type} eq 'character') {            if ($self->{open_elements}->[-1]->[1] == OPTION_EL) {
3837              ## NOTE: This is a code clone of "character in body".              !!!cp ('t274');
3838              $reconstruct_active_formatting_elements->($insert_to_current);              ## As if </option>
3839                            pop @{$self->{open_elements}};
3840              $self->{open_elements}->[-1]->[0]->manakai_append_text ($token->{data});            } else {
3841                !!!cp ('t275');
3842              }
3843    
3844              if ($self->{open_elements}->[-1]->[1] == OPTGROUP_EL) {
3845                !!!cp ('t276');
3846                ## As if </optgroup>
3847                pop @{$self->{open_elements}};
3848              } else {
3849                !!!cp ('t277');
3850              }
3851    
3852              !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
3853              !!!nack ('t277.1');
3854              !!!next-token;
3855              next B;
3856            } elsif ({
3857                       select => 1, input => 1, textarea => 1, keygen => 1,
3858                     }->{$token->{tag_name}} or
3859                     (($self->{insertion_mode} & IM_MASK)
3860                          == IN_SELECT_IN_TABLE_IM and
3861                      {
3862                       caption => 1, table => 1,
3863                       tbody => 1, tfoot => 1, thead => 1,
3864                       tr => 1, td => 1, th => 1,
3865                      }->{$token->{tag_name}})) {
3866    
3867              ## 1. Parse error.
3868              if ($token->{tag_name} eq 'select') {
3869                  !!!parse-error (type => 'select in select', ## XXX: documentation
3870                                  token => $token);
3871              } else {
3872                !!!parse-error (type => 'not closed', text => 'select',
3873                                token => $token);
3874              }
3875    
3876              ## 2./<select>-1. Unless "have an element in table scope" (select):
3877              my $i;
3878              INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
3879                my $node = $self->{open_elements}->[$_];
3880                if ($node->[1] == SELECT_EL) {
3881                  !!!cp ('t278');
3882                  $i = $_;
3883                  last INSCOPE;
3884                } elsif ($node->[1] & TABLE_SCOPING_EL) {
3885                  !!!cp ('t279');
3886                  last INSCOPE;
3887                }
3888              } # INSCOPE
3889              unless (defined $i) {
3890                !!!cp ('t280');
3891                if ($token->{tag_name} eq 'select') {
3892                  ## NOTE: This error would be raised when
3893                  ## |select.innerHTML = '<select>'| is executed; in this
3894                  ## case two errors, "select in select" and "unmatched
3895                  ## end tags" are reported to the user, the latter might
3896                  ## be confusing but this is what the spec requires.
3897                  !!!parse-error (type => 'unmatched end tag',
3898                                  text => 'select',
3899                                  token => $token);
3900                }
3901                ## Ignore the token.
3902                !!!nack ('t280.1');
3903              !!!next-token;              !!!next-token;
3904              redo B;              next B;
3905            } elsif ($token->{type} eq 'comment') {            }
3906              ## NOTE: This is a code clone of "comment in body".  
3907              my $comment = $self->{document}->create_comment ($token->{data});            ## 3. Otherwise, as if there were <select>:
3908              $self->{open_elements}->[-1]->[0]->append_child ($comment);                
3909              !!!cp ('t281');
3910              splice @{$self->{open_elements}}, $i;
3911    
3912              $self->_reset_insertion_mode;
3913    
3914              if ($token->{tag_name} eq 'select') {
3915                !!!nack ('t281.2');
3916              !!!next-token;              !!!next-token;
3917              redo B;              next B;
3918            } elsif ($token->{type} eq 'start tag') {            } else {
3919              if ({              !!!cp ('t281.1');
3920                   caption => 1, col => 1, colgroup => 1,              !!!ack-later;
3921                   tbody => 1, td => 1, tfoot => 1, th => 1,              ## Reprocess the token.
3922                   thead => 1, tr => 1,              next B;
3923                  }->{$token->{tag_name}}) {            }
3924                ## have an element in table scope          } elsif ($token->{tag_name} eq 'script') {
3925                my $tn;            !!!cp ('t281.3');
3926                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {            ## NOTE: This is an "as if in head" code clone
3927                  my $node = $self->{open_elements}->[$_];            $script_start_tag->();
3928                  if ($node->[1] eq 'td' or $node->[1] eq 'th') {            next B;
3929                    $tn = $node->[1];          } else {
3930                    last INSCOPE;            !!!cp ('t282');
3931                  } elsif ({            !!!parse-error (type => 'in select',
3932                            table => 1, html => 1,                            text => $token->{tag_name}, token => $token);
3933                           }->{$node->[1]}) {            ## Ignore the token
3934                    last INSCOPE;            !!!nack ('t282.1');
3935                  }            !!!next-token;
3936                } # INSCOPE            next B;
3937                unless (defined $tn) {          }
3938                  !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});        } elsif ($token->{type} == END_TAG_TOKEN) {
3939                  ## Ignore the token          if ($token->{tag_name} eq 'optgroup') {
3940                  !!!next-token;            if ($self->{open_elements}->[-1]->[1] == OPTION_EL and
3941                  redo B;                $self->{open_elements}->[-2]->[1] == OPTGROUP_EL) {
3942                }              !!!cp ('t283');
3943                ## As if </option>
3944                splice @{$self->{open_elements}}, -2;
3945              } elsif ($self->{open_elements}->[-1]->[1] == OPTGROUP_EL) {
3946                !!!cp ('t284');
3947                pop @{$self->{open_elements}};
3948              } else {
3949                !!!cp ('t285');
3950                !!!parse-error (type => 'unmatched end tag',
3951                                text => $token->{tag_name}, token => $token);
3952                ## Ignore the token
3953              }
3954              !!!nack ('t285.1');
3955              !!!next-token;
3956              next B;
3957            } elsif ($token->{tag_name} eq 'option') {
3958              if ($self->{open_elements}->[-1]->[1] == OPTION_EL) {
3959                !!!cp ('t286');
3960                pop @{$self->{open_elements}};
3961              } else {
3962                !!!cp ('t287');
3963                !!!parse-error (type => 'unmatched end tag',
3964                                text => $token->{tag_name}, token => $token);
3965                ## Ignore the token
3966              }
3967              !!!nack ('t287.1');
3968              !!!next-token;
3969              next B;
3970            } elsif ($token->{tag_name} eq 'select') {
3971              ## have an element in table scope
3972              my $i;
3973              INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
3974                my $node = $self->{open_elements}->[$_];
3975                if ($node->[1] == SELECT_EL) {
3976                  !!!cp ('t288');
3977                  $i = $_;
3978                  last INSCOPE;
3979                } elsif ($node->[1] & TABLE_SCOPING_EL) {
3980                  !!!cp ('t289');
3981                  last INSCOPE;
3982                }
3983              } # INSCOPE
3984              unless (defined $i) {
3985                !!!cp ('t290');
3986                !!!parse-error (type => 'unmatched end tag',
3987                                text => $token->{tag_name}, token => $token);
3988                ## Ignore the token
3989                !!!nack ('t290.1');
3990                !!!next-token;
3991                next B;
3992              }
3993                  
3994              !!!cp ('t291');
3995              splice @{$self->{open_elements}}, $i;
3996    
3997                ## Close the cell            $self->_reset_insertion_mode;
3998                !!!back-token; # <?>  
3999                $token = {type => 'end tag', tag_name => $tn};            !!!nack ('t291.1');
4000                redo B;            !!!next-token;
4001              } else {            next B;
4002                #          } elsif (($self->{insertion_mode} & IM_MASK)
4003                         == IN_SELECT_IN_TABLE_IM and
4004                     {
4005                      caption => 1, table => 1, tbody => 1,
4006                      tfoot => 1, thead => 1, tr => 1, td => 1, th => 1,
4007                     }->{$token->{tag_name}}) {
4008    ## TODO: The following is wrong?
4009              !!!parse-error (type => 'unmatched end tag',
4010                              text => $token->{tag_name}, token => $token);
4011                  
4012              ## have an element in table scope
4013              my $i;
4014              INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
4015                my $node = $self->{open_elements}->[$_];
4016                if ($node->[0]->manakai_local_name eq $token->{tag_name}) {
4017                  !!!cp ('t292');
4018                  $i = $_;
4019                  last INSCOPE;
4020                } elsif ($node->[1] & TABLE_SCOPING_EL) {
4021                  !!!cp ('t293');
4022                  last INSCOPE;
4023              }              }
4024            } elsif ($token->{type} eq 'end tag') {            } # INSCOPE
4025              if ($token->{tag_name} eq 'td' or $token->{tag_name} eq 'th') {            unless (defined $i) {
4026                ## have an element in table scope              !!!cp ('t294');
4027                my $i;              ## Ignore the token
4028                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {              !!!nack ('t294.1');
4029                  my $node = $self->{open_elements}->[$_];              !!!next-token;
4030                  if ($node->[1] eq $token->{tag_name}) {              next B;
4031                    $i = $_;            }
                   last INSCOPE;  
                 } elsif ({  
                           table => 1, html => 1,  
                          }->{$node->[1]}) {  
                   last INSCOPE;  
                 }  
               } # INSCOPE  
               unless (defined $i) {  
                 !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
                 ## Ignore the token  
                 !!!next-token;  
                 redo B;  
               }  
4032                                
4033                ## generate implied end tags            ## As if </select>
4034                if ({            ## have an element in table scope
4035                     dd => 1, dt => 1, li => 1, p => 1,            undef $i;
4036                     td => ($token->{tag_name} eq 'th'),            INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
4037                     th => ($token->{tag_name} eq 'td'),              my $node = $self->{open_elements}->[$_];
4038                     tr => 1,              if ($node->[1] == SELECT_EL) {
4039                    }->{$self->{open_elements}->[-1]->[1]}) {                !!!cp ('t295');
4040                  !!!back-token;                $i = $_;
4041                  $token = {type => 'end tag',                last INSCOPE;
4042                            tag_name => $self->{open_elements}->[-1]->[1]}; # MUST              } elsif ($node->[1] & TABLE_SCOPING_EL) {
4043                  redo B;  ## ISSUE: Can this state be reached?
4044                }                !!!cp ('t296');
4045                  last INSCOPE;
4046                }
4047              } # INSCOPE
4048              unless (defined $i) {
4049                !!!cp ('t297');
4050    ## TODO: The following error type is correct?
4051                !!!parse-error (type => 'unmatched end tag',
4052                                text => 'select', token => $token);
4053                ## Ignore the </select> token
4054                !!!nack ('t297.1');
4055                !!!next-token; ## TODO: ok?
4056                next B;
4057              }
4058                  
4059              !!!cp ('t298');
4060              splice @{$self->{open_elements}}, $i;
4061    
4062                if ($self->{open_elements}->[-1]->[1] ne $token->{tag_name}) {            $self->_reset_insertion_mode;
                 !!!parse-error (type => 'not closed:'.$self->{open_elements}->[-1]->[1]);  
               }  
4063    
4064                splice @{$self->{open_elements}}, $i;            !!!ack-later;
4065              ## reprocess
4066              next B;
4067            } else {
4068              !!!cp ('t299');
4069              !!!parse-error (type => 'in select:/',
4070                              text => $token->{tag_name}, token => $token);
4071              ## Ignore the token
4072              !!!nack ('t299.3');
4073              !!!next-token;
4074              next B;
4075            }
4076          } elsif ($token->{type} == END_OF_FILE_TOKEN) {
4077            unless ($self->{open_elements}->[-1]->[1] == HTML_EL and
4078                    @{$self->{open_elements}} == 1) { # redundant, maybe
4079              !!!cp ('t299.1');
4080              !!!parse-error (type => 'in body:#eof', token => $token);
4081            } else {
4082              !!!cp ('t299.2');
4083            }
4084    
4085                $clear_up_to_marker->();          ## Stop parsing.
4086            last B;
4087          } else {
4088            die "$0: $token->{type}: Unknown token type";
4089          }
4090        } elsif ($self->{insertion_mode} & BODY_AFTER_IMS) {
4091          if ($token->{type} == CHARACTER_TOKEN) {
4092            if ($token->{data} =~ s/^([\x09\x0A\x0C\x20]+)//) {
4093              my $data = $1;
4094              ## As if in body
4095              $reconstruct_active_formatting_elements->($insert_to_current);
4096                  
4097              $self->{open_elements}->[-1]->[0]->manakai_append_text ($1);
4098              
4099              unless (length $token->{data}) {
4100                !!!cp ('t300');
4101                !!!next-token;
4102                next B;
4103              }
4104            }
4105            
4106            if ($self->{insertion_mode} == AFTER_HTML_BODY_IM) {
4107              !!!cp ('t301');
4108              !!!parse-error (type => 'after html:#text', token => $token);
4109              #
4110            } else {
4111              !!!cp ('t302');
4112              ## "after body" insertion mode
4113              !!!parse-error (type => 'after body:#text', token => $token);
4114              #
4115            }
4116    
4117                $self->{insertion_mode} = 'in row';          $self->{insertion_mode} = IN_BODY_IM;
4118            ## reprocess
4119            next B;
4120          } elsif ($token->{type} == START_TAG_TOKEN) {
4121            if ($self->{insertion_mode} == AFTER_HTML_BODY_IM) {
4122              !!!cp ('t303');
4123              !!!parse-error (type => 'after html',
4124                              text => $token->{tag_name}, token => $token);
4125              #
4126            } else {
4127              !!!cp ('t304');
4128              ## "after body" insertion mode
4129              !!!parse-error (type => 'after body',
4130                              text => $token->{tag_name}, token => $token);
4131              #
4132            }
4133    
4134                !!!next-token;          $self->{insertion_mode} = IN_BODY_IM;
4135                redo B;          !!!ack-later;
4136              } elsif ({          ## reprocess
4137                        body => 1, caption => 1, col => 1,          next B;
4138                        colgroup => 1, html => 1,        } elsif ($token->{type} == END_TAG_TOKEN) {
4139                       }->{$token->{tag_name}}) {          if ($self->{insertion_mode} == AFTER_HTML_BODY_IM) {
4140                !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});            !!!cp ('t305');
4141                ## Ignore the token            !!!parse-error (type => 'after html:/',
4142                !!!next-token;                            text => $token->{tag_name}, token => $token);
4143                redo B;            
4144              } elsif ({            $self->{insertion_mode} = IN_BODY_IM;
4145                        table => 1, tbody => 1, tfoot => 1,            ## Reprocess.
4146                        thead => 1, tr => 1,            next B;
4147                       }->{$token->{tag_name}}) {          } else {
4148                ## have an element in table scope            !!!cp ('t306');
4149                my $i;          }
               my $tn;  
               INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {  
                 my $node = $self->{open_elements}->[$_];  
                 if ($node->[1] eq $token->{tag_name}) {  
                   $i = $_;  
                   last INSCOPE;  
                 } elsif ($node->[1] eq 'td' or $node->[1] eq 'th') {  
                   $tn = $node->[1];  
                   ## NOTE: There is exactly one |td| or |th| element  
                   ## in scope in the stack of open elements by definition.  
                 } elsif ({  
                           table => 1, html => 1,  
                          }->{$node->[1]}) {  
                   last INSCOPE;  
                 }  
               } # INSCOPE  
               unless (defined $i) {  
                 !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
                 ## Ignore the token  
                 !!!next-token;  
                 redo B;  
               }  
4150    
4151                ## Close the cell          ## "after body" insertion mode
4152                !!!back-token; # </?>          if ($token->{tag_name} eq 'html') {
4153                $token = {type => 'end tag', tag_name => $tn};            if (defined $self->{inner_html_node}) {
4154                redo B;              !!!cp ('t307');
4155              } else {              !!!parse-error (type => 'unmatched end tag',
4156                #                              text => 'html', token => $token);
4157              }              ## Ignore the token
4158                !!!next-token;
4159                next B;
4160            } else {            } else {
4161              #              !!!cp ('t308');
4162                $self->{insertion_mode} = AFTER_HTML_BODY_IM;
4163                !!!next-token;
4164                next B;
4165            }            }
4166            } else {
4167              !!!cp ('t309');
4168              !!!parse-error (type => 'after body:/',
4169                              text => $token->{tag_name}, token => $token);
4170    
4171              $self->{insertion_mode} = IN_BODY_IM;
4172              ## reprocess
4173              next B;
4174            }
4175          } elsif ($token->{type} == END_OF_FILE_TOKEN) {
4176            !!!cp ('t309.2');
4177            ## Stop parsing
4178            last B;
4179          } else {
4180            die "$0: $token->{type}: Unknown token type";
4181          }
4182        } elsif ($self->{insertion_mode} & FRAME_IMS) {
4183          if ($token->{type} == CHARACTER_TOKEN) {
4184            if ($token->{data} =~ s/^([\x09\x0A\x0C\x20]+)//) {
4185              $self->{open_elements}->[-1]->[0]->manakai_append_text ($1);
4186                        
4187            $in_body->($insert_to_current);            unless (length $token->{data}) {
4188            redo B;              !!!cp ('t310');
         } elsif ($self->{insertion_mode} eq 'in select') {  
           if ($token->{type} eq 'character') {  
             $self->{open_elements}->[-1]->[0]->manakai_append_text ($token->{data});  
4189              !!!next-token;              !!!next-token;
4190              redo B;              next B;
4191            } elsif ($token->{type} eq 'comment') {            }
4192              my $comment = $self->{document}->create_comment ($token->{data});          }
4193              $self->{open_elements}->[-1]->[0]->append_child ($comment);          
4194            if ($token->{data} =~ s/^[^\x09\x0A\x0C\x20]+//) {
4195              if ($self->{insertion_mode} == IN_FRAMESET_IM) {
4196                !!!cp ('t311');
4197                !!!parse-error (type => 'in frameset:#text', token => $token);
4198              } elsif ($self->{insertion_mode} == AFTER_FRAMESET_IM) {
4199                !!!cp ('t312');
4200                !!!parse-error (type => 'after frameset:#text', token => $token);
4201              } else { # "after after frameset"
4202                !!!cp ('t313');
4203                !!!parse-error (type => 'after html:#text', token => $token);
4204              }
4205              
4206              ## Ignore the token.
4207              if (length $token->{data}) {
4208                !!!cp ('t314');
4209                ## reprocess the rest of characters
4210              } else {
4211                !!!cp ('t315');
4212              !!!next-token;              !!!next-token;
4213              redo B;            }
4214            } elsif ($token->{type} eq 'start tag') {            next B;
4215              if ($token->{tag_name} eq 'option') {          }
4216                if ($self->{open_elements}->[-1]->[1] eq 'option') {          
4217                  ## As if </option>          die qq[$0: Character "$token->{data}"];
4218                  pop @{$self->{open_elements}};        } elsif ($token->{type} == START_TAG_TOKEN) {
4219                }          if ($token->{tag_name} eq 'frameset' and
4220                $self->{insertion_mode} == IN_FRAMESET_IM) {
4221              !!!cp ('t318');
4222              !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
4223              !!!nack ('t318.1');
4224              !!!next-token;
4225              next B;
4226            } elsif ($token->{tag_name} eq 'frame' and
4227                     $self->{insertion_mode} == IN_FRAMESET_IM) {
4228              !!!cp ('t319');
4229              !!!insert-element ($token->{tag_name}, $token->{attributes}, $token);
4230              pop @{$self->{open_elements}};
4231              !!!ack ('t319.1');
4232              !!!next-token;
4233              next B;
4234            } elsif ($token->{tag_name} eq 'noframes') {
4235              !!!cp ('t320');
4236              ## NOTE: As if in head.
4237              $parse_rcdata->(CDATA_CONTENT_MODEL);
4238              next B;
4239    
4240              ## NOTE: |<!DOCTYPE HTML><frameset></frameset></html><noframes></noframes>|
4241              ## has no parse error.
4242            } else {
4243              if ($self->{insertion_mode} == IN_FRAMESET_IM) {
4244                !!!cp ('t321');
4245                !!!parse-error (type => 'in frameset',
4246                                text => $token->{tag_name}, token => $token);
4247              } elsif ($self->{insertion_mode} == AFTER_FRAMESET_IM) {
4248                !!!cp ('t322');
4249                !!!parse-error (type => 'after frameset',
4250                                text => $token->{tag_name}, token => $token);
4251              } else { # "after after frameset"
4252                !!!cp ('t322.2');
4253                !!!parse-error (type => 'after after frameset',
4254                                text => $token->{tag_name}, token => $token);
4255              }
4256              ## Ignore the token
4257              !!!nack ('t322.1');
4258              !!!next-token;
4259              next B;
4260            }
4261          } elsif ($token->{type} == END_TAG_TOKEN) {
4262            if ($token->{tag_name} eq 'frameset' and
4263                $self->{insertion_mode} == IN_FRAMESET_IM) {
4264              if ($self->{open_elements}->[-1]->[1] == HTML_EL and
4265                  @{$self->{open_elements}} == 1) {
4266                !!!cp ('t325');
4267                !!!parse-error (type => 'unmatched end tag',
4268                                text => $token->{tag_name}, token => $token);
4269                ## Ignore the token
4270                !!!next-token;
4271              } else {
4272                !!!cp ('t326');
4273                pop @{$self->{open_elements}};
4274                !!!next-token;
4275              }
4276    
4277                !!!insert-element ($token->{tag_name}, $token->{attributes});            if (not defined $self->{inner_html_node} and
4278                !!!next-token;                not ($self->{open_elements}->[-1]->[1] == FRAMESET_EL)) {
4279                redo B;              !!!cp ('t327');
4280              } elsif ($token->{tag_name} eq 'optgroup') {              $self->{insertion_mode} = AFTER_FRAMESET_IM;
4281                if ($self->{open_elements}->[-1]->[1] eq 'option') {            } else {
4282                  ## As if </option>              !!!cp ('t328');
4283                  pop @{$self->{open_elements}};            }
4284                }            next B;
4285            } elsif ($token->{tag_name} eq 'html' and
4286                     $self->{insertion_mode} == AFTER_FRAMESET_IM) {
4287              !!!cp ('t329');
4288              $self->{insertion_mode} = AFTER_HTML_FRAMESET_IM;
4289              !!!next-token;
4290              next B;
4291            } else {
4292              if ($self->{insertion_mode} == IN_FRAMESET_IM) {
4293                !!!cp ('t330');
4294                !!!parse-error (type => 'in frameset:/',
4295                                text => $token->{tag_name}, token => $token);
4296              } elsif ($self->{insertion_mode} == AFTER_FRAMESET_IM) {
4297                !!!cp ('t330.1');
4298                !!!parse-error (type => 'after frameset:/',
4299                                text => $token->{tag_name}, token => $token);
4300              } else { # "after after html"
4301                !!!cp ('t331');
4302                !!!parse-error (type => 'after after frameset:/',
4303                                text => $token->{tag_name}, token => $token);
4304              }
4305              ## Ignore the token
4306              !!!next-token;
4307              next B;
4308            }
4309          } elsif ($token->{type} == END_OF_FILE_TOKEN) {
4310            unless ($self->{open_elements}->[-1]->[1] == HTML_EL and
4311                    @{$self->{open_elements}} == 1) { # redundant, maybe
4312              !!!cp ('t331.1');
4313              !!!parse-error (type => 'in body:#eof', token => $token);
4314            } else {
4315              !!!cp ('t331.2');
4316            }
4317            
4318            ## Stop parsing
4319            last B;
4320          } else {
4321            die "$0: $token->{type}: Unknown token type";
4322          }
4323        } else {
4324          die "$0: $self->{insertion_mode}: Unknown insertion mode";
4325        }
4326    
4327                if ($self->{open_elements}->[-1]->[1] eq 'optgroup') {      ## "in body" insertion mode
4328                  ## As if </optgroup>      if ($token->{type} == START_TAG_TOKEN) {
4329                  pop @{$self->{open_elements}};        if ($token->{tag_name} eq 'script') {
4330                }          !!!cp ('t332');
4331            ## NOTE: This is an "as if in head" code clone
4332            $script_start_tag->();
4333            next B;
4334          } elsif ($token->{tag_name} eq 'style') {
4335            !!!cp ('t333');
4336            ## NOTE: This is an "as if in head" code clone
4337            $parse_rcdata->(CDATA_CONTENT_MODEL);
4338            next B;
4339          } elsif ({
4340                    base => 1, command => 1, link => 1,
4341                   }->{$token->{tag_name}}) {
4342            !!!cp ('t334');
4343            ## NOTE: This is an "as if in head" code clone, only "-t" differs
4344            !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
4345            pop @{$self->{open_elements}};
4346            !!!ack ('t334.1');
4347            !!!next-token;
4348            next B;
4349          } elsif ($token->{tag_name} eq 'meta') {
4350            ## NOTE: This is an "as if in head" code clone, only "-t" differs
4351            !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
4352            my $meta_el = pop @{$self->{open_elements}};
4353    
4354            unless ($self->{confident}) {
4355              if ($token->{attributes}->{charset}) {
4356                !!!cp ('t335');
4357                ## NOTE: Whether the encoding is supported or not is handled
4358                ## in the {change_encoding} callback.
4359                $self->{change_encoding}
4360                    ->($self, $token->{attributes}->{charset}->{value}, $token);
4361                
4362                $meta_el->[0]->get_attribute_node_ns (undef, 'charset')
4363                    ->set_user_data (manakai_has_reference =>
4364                                         $token->{attributes}->{charset}
4365                                             ->{has_reference});
4366              } elsif ($token->{attributes}->{content}) {
4367                if ($token->{attributes}->{content}->{value}
4368                    =~ /[Cc][Hh][Aa][Rr][Ss][Ee][Tt]
4369                        [\x09\x0A\x0C\x0D\x20]*=
4370                        [\x09\x0A\x0C\x0D\x20]*(?>"([^"]*)"|'([^']*)'|
4371                        ([^"'\x09\x0A\x0C\x0D\x20][^\x09\x0A\x0C\x0D\x20\x3B]*))
4372                       /x) {
4373                  !!!cp ('t336');
4374                  ## NOTE: Whether the encoding is supported or not is handled
4375                  ## in the {change_encoding} callback.
4376                  $self->{change_encoding}
4377                      ->($self, defined $1 ? $1 : defined $2 ? $2 : $3, $token);
4378                  $meta_el->[0]->get_attribute_node_ns (undef, 'content')
4379                      ->set_user_data (manakai_has_reference =>
4380                                           $token->{attributes}->{content}
4381                                                 ->{has_reference});
4382                }
4383              }
4384            } else {
4385              if ($token->{attributes}->{charset}) {
4386                !!!cp ('t337');
4387                $meta_el->[0]->get_attribute_node_ns (undef, 'charset')
4388                    ->set_user_data (manakai_has_reference =>
4389                                         $token->{attributes}->{charset}
4390                                             ->{has_reference});
4391              }
4392              if ($token->{attributes}->{content}) {
4393                !!!cp ('t338');
4394                $meta_el->[0]->get_attribute_node_ns (undef, 'content')
4395                    ->set_user_data (manakai_has_reference =>
4396                                         $token->{attributes}->{content}
4397                                             ->{has_reference});
4398              }
4399            }
4400    
4401                !!!insert-element ($token->{tag_name}, $token->{attributes});          !!!ack ('t338.1');
4402                !!!next-token;          !!!next-token;
4403                redo B;          next B;
4404              } elsif ($token->{tag_name} eq 'select') {        } elsif ($token->{tag_name} eq 'title') {
4405                !!!parse-error (type => 'not closed:select');          !!!cp ('t341');
4406                ## As if </select> instead          ## NOTE: This is an "as if in head" code clone
4407                ## have an element in table scope          $parse_rcdata->(RCDATA_CONTENT_MODEL);
4408                my $i;          next B;
4409                INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {        } elsif ($token->{tag_name} eq 'body') {
4410                  my $node = $self->{open_elements}->[$_];          !!!parse-error (type => 'in body', text => 'body', token => $token);
                 if ($node->[1] eq $token->{tag_name}) {  
                   $i = $_;  
                   last INSCOPE;  
                 } elsif ({  
                           table => 1, html => 1,  
                          }->{$node->[1]}) {  
                   last INSCOPE;  
                 }  
               } # INSCOPE  
               unless (defined $i) {  
                 !!!parse-error (type => 'unmatched end tag:select');  
                 ## Ignore the token  
                 !!!next-token;  
                 redo B;  
               }  
4411                                
4412                splice @{$self->{open_elements}}, $i;          if (@{$self->{open_elements}} == 1 or
4413                not ($self->{open_elements}->[1]->[1] == BODY_EL)) {
4414              !!!cp ('t342');
4415              ## Ignore the token
4416            } else {
4417              my $body_el = $self->{open_elements}->[1]->[0];
4418              for my $attr_name (keys %{$token->{attributes}}) {
4419                unless ($body_el->has_attribute_ns (undef, $attr_name)) {
4420                  !!!cp ('t343');
4421                  $body_el->set_attribute_ns
4422                    (undef, [undef, $attr_name],
4423                     $token->{attributes}->{$attr_name}->{value});
4424                }
4425              }
4426            }
4427            !!!nack ('t343.1');
4428            !!!next-token;
4429            next B;
4430          } elsif ({
4431                    ## NOTE: Start tags for non-phrasing flow content elements
4432    
4433                $self->_reset_insertion_mode;                  ## NOTE: The normal one
4434                    address => 1, article => 1, aside => 1, blockquote => 1,
4435                    center => 1, datagrid => 1, details => 1, dialog => 1,
4436                    dir => 1, div => 1, dl => 1, fieldset => 1, figure => 1,
4437                    footer => 1, h1 => 1, h2 => 1, h3 => 1, h4 => 1, h5 => 1,
4438                    h6 => 1, header => 1, menu => 1, nav => 1, ol => 1, p => 1,
4439                    section => 1, ul => 1,
4440                    ## NOTE: As normal, but drops leading newline
4441                    pre => 1, listing => 1,
4442                    ## NOTE: As normal, but interacts with the form element pointer
4443                    form => 1,
4444                    
4445                    table => 1,
4446                    hr => 1,
4447                   }->{$token->{tag_name}}) {
4448    
4449                !!!next-token;          ## 1. When there is an opening |form| element:
4450                redo B;          if ($token->{tag_name} eq 'form' and defined $self->{form_element}) {
4451              } else {            !!!cp ('t350');
4452                #            !!!parse-error (type => 'in form:form', token => $token);
4453              ## Ignore the token
4454              !!!nack ('t350.1');
4455              !!!next-token;
4456              next B;
4457            }
4458    
4459            ## 2. Close the |p| element, if any.
4460            if ($token->{tag_name} ne 'table' or # The Hixie Quirk
4461                $self->{document}->manakai_compat_mode ne 'quirks') {
4462              ## has a p element in scope
4463              INSCOPE: for (reverse @{$self->{open_elements}}) {
4464                if ($_->[1] == P_EL) {
4465                  !!!cp ('t344');
4466                  !!!back-token; # <form>
4467                  $token = {type => END_TAG_TOKEN, tag_name => 'p',
4468                            line => $token->{line}, column => $token->{column}};
4469                  next B;
4470                } elsif ($_->[1] & SCOPING_EL) {
4471                  !!!cp ('t345');
4472                  last INSCOPE;
4473              }              }
4474            } elsif ($token->{type} eq 'end tag') {            } # INSCOPE
4475              if ($token->{tag_name} eq 'optgroup') {          }
               if ($self->{open_elements}->[-1]->[1] eq 'option' and  
                   $self->{open_elements}->[-2]->[1] eq 'optgroup') {  
                 ## As if </option>  
                 splice @{$self->{open_elements}}, -2;  
               } elsif ($self->{open_elements}->[-1]->[1] eq 'optgroup') {  
                 pop @{$self->{open_elements}};  
               } else {  
                 !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
                 ## Ignore the token  
               }  
               !!!next-token;  
               redo B;  
             } elsif ($token->{tag_name} eq 'option') {  
               if ($self->{open_elements}->[-1]->[1] eq 'option') {  
                 pop @{$self->{open_elements}};  
               } else {  
                 !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
                 ## Ignore the token  
               }  
               !!!next-token;  
               redo B;  
             } elsif ($token->{tag_name} eq 'select') {  
               ## have an element in table scope  
               my $i;  
               INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {  
                 my $node = $self->{open_elements}->[$_];  
                 if ($node->[1] eq $token->{tag_name}) {  
                   $i = $_;  
                   last INSCOPE;  
                 } elsif ({  
                           table => 1, html => 1,  
                          }->{$node->[1]}) {  
                   last INSCOPE;  
                 }  
               } # INSCOPE  
               unless (defined $i) {  
                 !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
                 ## Ignore the token  
                 !!!next-token;  
                 redo B;  
               }  
                 
               splice @{$self->{open_elements}}, $i;  
4476    
4477                $self->_reset_insertion_mode;          ## 3. Close the opening <hn> element, if any.
4478            if ({h1 => 1, h2 => 1, h3 => 1,
4479                 h4 => 1, h5 => 1, h6 => 1}->{$token->{tag_name}}) {
4480              if ($self->{open_elements}->[-1]->[1] == HEADING_EL) {
4481                !!!parse-error (type => 'not closed',
4482                                text => $self->{open_elements}->[-1]->[0]->manakai_local_name,
4483                                token => $token);
4484                pop @{$self->{open_elements}};
4485              }
4486            }
4487    
4488            ## 4. Insertion.
4489            !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
4490            if ($token->{tag_name} eq 'pre' or $token->{tag_name} eq 'listing') {
4491              !!!nack ('t346.1');
4492              !!!next-token;
4493              if ($token->{type} == CHARACTER_TOKEN) {
4494                $token->{data} =~ s/^\x0A//;
4495                unless (length $token->{data}) {
4496                  !!!cp ('t346');
4497                !!!next-token;                !!!next-token;
               redo B;  
             } elsif ({  
                       caption => 1, table => 1, tbody => 1,  
                       tfoot => 1, thead => 1, tr => 1, td => 1, th => 1,  
                      }->{$token->{tag_name}}) {  
               !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
                 
               ## have an element in table scope  
               my $i;  
               INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {  
                 my $node = $self->{open_elements}->[$_];  
                 if ($node->[1] eq $token->{tag_name}) {  
                   $i = $_;  
                   last INSCOPE;  
                 } elsif ({  
                           table => 1, html => 1,  
                          }->{$node->[1]}) {  
                   last INSCOPE;  
                 }  
               } # INSCOPE  
               unless (defined $i) {  
                 ## Ignore the token  
                 !!!next-token;  
                 redo B;  
               }  
                 
               ## As if </select>  
               ## have an element in table scope  
               undef $i;  
               INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {  
                 my $node = $self->{open_elements}->[$_];  
                 if ($node->[1] eq 'select') {  
                   $i = $_;  
                   last INSCOPE;  
                 } elsif ({  
                           table => 1, html => 1,  
                          }->{$node->[1]}) {  
                   last INSCOPE;  
                 }  
               } # INSCOPE  
               unless (defined $i) {  
                 !!!parse-error (type => 'unmatched end tag:select');  
                 ## Ignore the </select> token  
                 !!!next-token; ## TODO: ok?  
                 redo B;  
               }  
                 
               splice @{$self->{open_elements}}, $i;  
   
               $self->_reset_insertion_mode;  
   
               ## reprocess  
               redo B;  
4498              } else {              } else {
4499                #                !!!cp ('t349');
4500              }              }
4501            } else {            } else {
4502              #              !!!cp ('t348');
4503            }            }
4504            } elsif ($token->{tag_name} eq 'form') {
4505              !!!cp ('t347.1');
4506              $self->{form_element} = $self->{open_elements}->[-1]->[0];
4507    
4508            !!!parse-error (type => 'in select:'.$token->{tag_name});            !!!nack ('t347.2');
           ## Ignore the token  
4509            !!!next-token;            !!!next-token;
4510            redo B;          } elsif ($token->{tag_name} eq 'table') {
4511          } elsif ($self->{insertion_mode} eq 'after body') {            !!!cp ('t382');
4512            if ($token->{type} eq 'character') {            push @{$open_tables}, [$self->{open_elements}->[-1]->[0]];
4513              if ($token->{data} =~ s/^([\x09\x0A\x0B\x0C\x20]+)//) {            
4514                ## As if in body            $self->{insertion_mode} = IN_TABLE_IM;
               $reconstruct_active_formatting_elements->($insert_to_current);  
                 
               $self->{open_elements}->[-1]->[0]->manakai_append_text ($token->{data});  
4515    
4516                unless (length $token->{data}) {            !!!nack ('t382.1');
4517                  !!!next-token;            !!!next-token;
4518                  redo B;          } elsif ($token->{tag_name} eq 'hr') {
4519                }            !!!cp ('t386');
4520              }            pop @{$self->{open_elements}};
4521                        
4522              #            !!!nack ('t386.1');
4523              !!!parse-error (type => 'after body:#'.$token->{type});            !!!next-token;
4524            } elsif ($token->{type} eq 'comment') {          } else {
4525              my $comment = $self->{document}->create_comment ($token->{data});            !!!nack ('t347.1');
4526              $self->{open_elements}->[0]->[0]->append_child ($comment);            !!!next-token;
4527              !!!next-token;          }
4528              redo B;          next B;
4529            } elsif ($token->{type} eq 'start tag') {        } elsif ($token->{tag_name} eq 'li') {
4530              !!!parse-error (type => 'after body:'.$token->{tag_name});          ## NOTE: As normal, but imply </li> when there's another <li> ...
4531              #  
4532            } elsif ($token->{type} eq 'end tag') {          ## NOTE: Special, Scope (<li><foo><li> == <li><foo><li/></foo></li>)::
4533              if ($token->{tag_name} eq 'html') {            ## Interpreted as <li><foo/></li><li/> (non-conforming):
4534                if (defined $self->{inner_html_node}) {            ## blockquote (O9.27), center (O), dd (Fx3, O, S3.1.2, IE7),
4535                  !!!parse-error (type => 'unmatched end tag:html');            ## dt (Fx, O, S, IE), dl (O), fieldset (O, S, IE), form (Fx, O, S),
4536                  ## Ignore the token            ## hn (O), pre (O), applet (O, S), button (O, S), marquee (Fx, O, S),
4537                  !!!next-token;            ## object (Fx)
4538                  redo B;            ## Generate non-tree (non-conforming):
4539              ## basefont (IE7 (where basefont is non-void)), center (IE),
4540              ## form (IE), hn (IE)
4541            ## address, div, p (<li><foo><li> == <li><foo/></li><li/>)::
4542              ## Interpreted as <li><foo><li/></foo></li> (non-conforming):
4543              ## div (Fx, S)
4544    
4545            my $non_optional;
4546            my $i = -1;
4547    
4548            ## 1.
4549            for my $node (reverse @{$self->{open_elements}}) {
4550              if ($node->[1] == LI_EL) {
4551                ## 2. (a) As if </li>
4552                {
4553                  ## If no </li> - not applied
4554                  #
4555    
4556                  ## Otherwise
4557    
4558                  ## 1. generate implied end tags, except for </li>
4559                  #
4560    
4561                  ## 2. If current node != "li", parse error
4562                  if ($non_optional) {
4563                    !!!parse-error (type => 'not closed',
4564                                    text => $non_optional->[0]->manakai_local_name,
4565                                    token => $token);
4566                    !!!cp ('t355');
4567                } else {                } else {
4568                  $phase = 'trailing end';                  !!!cp ('t356');
                 !!!next-token;  
                 redo B;  
4569                }                }
4570              } else {  
4571                !!!parse-error (type => 'after body:/'.$token->{tag_name});                ## 3. Pop
4572                  splice @{$self->{open_elements}}, $i;
4573              }              }
4574    
4575                last; ## 2. (b) goto 5.
4576              } elsif (
4577                       ## NOTE: not "formatting" and not "phrasing"
4578                       ($node->[1] & SPECIAL_EL or
4579                        $node->[1] & SCOPING_EL) and
4580                       ## NOTE: "li", "dt", and "dd" are in |SPECIAL_EL|.
4581                       (not $node->[1] & ADDRESS_DIV_P_EL)
4582                      ) {
4583                ## 3.
4584                !!!cp ('t357');
4585                last; ## goto 5.
4586              } elsif ($node->[1] & END_TAG_OPTIONAL_EL) {
4587                !!!cp ('t358');
4588                #
4589            } else {            } else {
4590              !!!parse-error (type => 'after body:#'.$token->{type});              !!!cp ('t359');
4591                $non_optional ||= $node;
4592                #
4593            }            }
4594              ## 4.
4595              ## goto 2.
4596              $i--;
4597            }
4598    
4599            $self->{insertion_mode} = 'in body';          ## 5. (a) has a |p| element in scope
4600            ## reprocess          INSCOPE: for (reverse @{$self->{open_elements}}) {
4601            redo B;            if ($_->[1] == P_EL) {
4602          } elsif ($self->{insertion_mode} eq 'in frameset') {              !!!cp ('t353');
           if ($token->{type} eq 'character') {  
             if ($token->{data} =~ s/^([\x09\x0A\x0B\x0C\x20]+)//) {  
               $self->{open_elements}->[-1]->[0]->manakai_append_text ($token->{data});  
4603    
4604                unless (length $token->{data}) {              ## NOTE: |<p><li>|, for example.
                 !!!next-token;  
                 redo B;  
               }  
             }  
4605    
4606              #              !!!back-token; # <x>
4607            } elsif ($token->{type} eq 'comment') {              $token = {type => END_TAG_TOKEN, tag_name => 'p',
4608              my $comment = $self->{document}->create_comment ($token->{data});                        line => $token->{line}, column => $token->{column}};
4609              $self->{open_elements}->[-1]->[0]->append_child ($comment);              next B;
4610              !!!next-token;            } elsif ($_->[1] & SCOPING_EL) {
4611              redo B;              !!!cp ('t354');
4612            } elsif ($token->{type} eq 'start tag') {              last INSCOPE;
4613              if ($token->{tag_name} eq 'frameset') {            }
4614                !!!insert-element ($token->{tag_name}, $token->{attributes});          } # INSCOPE
4615                !!!next-token;  
4616                redo B;          ## 5. (b) insert
4617              } elsif ($token->{tag_name} eq 'frame') {          !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
4618                !!!insert-element ($token->{tag_name}, $token->{attributes});          !!!nack ('t359.1');
4619                pop @{$self->{open_elements}};          !!!next-token;
4620                !!!next-token;          next B;
4621                redo B;        } elsif ($token->{tag_name} eq 'dt' or
4622              } elsif ($token->{tag_name} eq 'noframes') {                 $token->{tag_name} eq 'dd') {
4623                $in_body->($insert_to_current);          ## NOTE: As normal, but imply </dt> or </dd> when ...
4624                redo B;  
4625              } else {          my $non_optional;
4626            my $i = -1;
4627    
4628            ## 1.
4629            for my $node (reverse @{$self->{open_elements}}) {
4630              if ($node->[1] == DTDD_EL) {
4631                ## 2. (a) As if </li>
4632                {
4633                  ## If no </li> - not applied
4634                #                #
4635              }  
4636            } elsif ($token->{type} eq 'end tag') {                ## Otherwise
4637              if ($token->{tag_name} eq 'frameset') {  
4638                if ($self->{open_elements}->[-1]->[1] eq 'html' and                ## 1. generate implied end tags, except for </dt> or </dd>
4639                    @{$self->{open_elements}} == 1) {                #
4640                  !!!parse-error (type => 'unmatched end tag:'.$token->{tag_name});  
4641                  ## Ignore the token                ## 2. If current node != "dt"|"dd", parse error
4642                  !!!next-token;                if ($non_optional) {
4643                    !!!parse-error (type => 'not closed',
4644                                    text => $non_optional->[0]->manakai_local_name,
4645                                    token => $token);
4646                    !!!cp ('t355.1');
4647                } else {                } else {
4648                  pop @{$self->{open_elements}};                  !!!cp ('t356.1');
                 !!!next-token;  
4649                }                }
4650                  
4651                ## if not inner_html and                ## 3. Pop
4652                if ($self->{open_elements}->[-1]->[1] ne 'frameset') {                splice @{$self->{open_elements}}, $i;
                 $self->{insertion_mode} = 'after frameset';  
               }  
               redo B;  
             } else {  
               #  
4653              }              }
4654    
4655                last; ## 2. (b) goto 5.
4656              } elsif (
4657                       ## NOTE: not "formatting" and not "phrasing"
4658                       ($node->[1] & SPECIAL_EL or
4659                        $node->[1] & SCOPING_EL) and
4660                       ## NOTE: "li", "dt", and "dd" are in |SPECIAL_EL|.
4661    
4662                       (not $node->[1] & ADDRESS_DIV_P_EL)
4663                      ) {
4664                ## 3.
4665                !!!cp ('t357.1');
4666                last; ## goto 5.
4667              } elsif ($node->[1] & END_TAG_OPTIONAL_EL) {
4668                !!!cp ('t358.1');
4669                #
4670            } else {            } else {
4671                !!!cp ('t359.1');
4672                $non_optional ||= $node;
4673              #              #
4674            }            }
4675              ## 4.
4676              ## goto 2.
4677              $i--;
4678            }
4679    
4680            ## 5. (a) has a |p| element in scope
4681            INSCOPE: for (reverse @{$self->{open_elements}}) {
4682              if ($_->[1] == P_EL) {
4683                !!!cp ('t353.1');
4684                !!!back-token; # <x>
4685                $token = {type => END_TAG_TOKEN, tag_name => 'p',
4686                          line => $token->{line}, column => $token->{column}};
4687                next B;
4688              } elsif ($_->[1] & SCOPING_EL) {
4689                !!!cp ('t354.1');
4690                last INSCOPE;
4691              }
4692            } # INSCOPE
4693    
4694            ## 5. (b) insert
4695            !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
4696            !!!nack ('t359.2');
4697            !!!next-token;
4698            next B;
4699          } elsif ($token->{tag_name} eq 'plaintext') {
4700            ## NOTE: As normal, but effectively ends parsing
4701    
4702            ## has a p element in scope
4703            INSCOPE: for (reverse @{$self->{open_elements}}) {
4704              if ($_->[1] == P_EL) {
4705                !!!cp ('t367');
4706                !!!back-token; # <plaintext>
4707                $token = {type => END_TAG_TOKEN, tag_name => 'p',
4708                          line => $token->{line}, column => $token->{column}};
4709                next B;
4710              } elsif ($_->[1] & SCOPING_EL) {
4711                !!!cp ('t368');
4712                last INSCOPE;
4713              }
4714            } # INSCOPE
4715                        
4716            if (defined $token->{tag_name}) {          !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
4717              !!!parse-error (type => 'in frameset:'.$token->{tag_name});            
4718            } else {          $self->{content_model} = PLAINTEXT_CONTENT_MODEL;
4719              !!!parse-error (type => 'in frameset:#'.$token->{type});            
4720            !!!nack ('t368.1');
4721            !!!next-token;
4722            next B;
4723          } elsif ($token->{tag_name} eq 'a') {
4724            AFE: for my $i (reverse 0..$#$active_formatting_elements) {
4725              my $node = $active_formatting_elements->[$i];
4726              if ($node->[1] == A_EL) {
4727                !!!cp ('t371');
4728                !!!parse-error (type => 'in a:a', token => $token);
4729                
4730                !!!back-token; # <a>
4731                $token = {type => END_TAG_TOKEN, tag_name => 'a',
4732                          line => $token->{line}, column => $token->{column}};
4733                $formatting_end_tag->($token);
4734                
4735                AFE2: for (reverse 0..$#$active_formatting_elements) {
4736                  if ($active_formatting_elements->[$_]->[0] eq $node->[0]) {
4737                    !!!cp ('t372');
4738                    splice @$active_formatting_elements, $_, 1;
4739                    last AFE2;
4740                  }
4741                } # AFE2
4742                OE: for (reverse 0..$#{$self->{open_elements}}) {
4743                  if ($self->{open_elements}->[$_]->[0] eq $node->[0]) {
4744                    !!!cp ('t373');
4745                    splice @{$self->{open_elements}}, $_, 1;
4746                    last OE;
4747                  }
4748                } # OE
4749                last AFE;
4750              } elsif ($node->[0] eq '#marker') {
4751                !!!cp ('t374');
4752                last AFE;
4753            }            }
4754            } # AFE
4755              
4756            $reconstruct_active_formatting_elements->($insert_to_current);
4757    
4758            !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
4759            push @$active_formatting_elements, $self->{open_elements}->[-1];
4760    
4761            !!!nack ('t374.1');
4762            !!!next-token;
4763            next B;
4764          } elsif ($token->{tag_name} eq 'nobr') {
4765            $reconstruct_active_formatting_elements->($insert_to_current);
4766    
4767            ## has a |nobr| element in scope
4768            INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
4769              my $node = $self->{open_elements}->[$_];
4770              if ($node->[1] == NOBR_EL) {
4771                !!!cp ('t376');
4772                !!!parse-error (type => 'in nobr:nobr', token => $token);
4773                !!!back-token; # <nobr>
4774                $token = {type => END_TAG_TOKEN, tag_name => 'nobr',
4775                          line => $token->{line}, column => $token->{column}};
4776                next B;
4777              } elsif ($node->[1] & SCOPING_EL) {
4778                !!!cp ('t377');
4779                last INSCOPE;
4780              }
4781            } # INSCOPE
4782            
4783            !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
4784            push @$active_formatting_elements, $self->{open_elements}->[-1];
4785            
4786            !!!nack ('t377.1');
4787            !!!next-token;
4788            next B;
4789          } elsif ($token->{tag_name} eq 'button') {
4790            ## has a button element in scope
4791            INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
4792              my $node = $self->{open_elements}->[$_];
4793              if ($node->[1] == BUTTON_EL) {
4794                !!!cp ('t378');
4795                !!!parse-error (type => 'in button:button', token => $token);
4796                !!!back-token; # <button>
4797                $token = {type => END_TAG_TOKEN, tag_name => 'button',
4798                          line => $token->{line}, column => $token->{column}};
4799                next B;
4800              } elsif ($node->[1] & SCOPING_EL) {
4801                !!!cp ('t379');
4802                last INSCOPE;
4803              }
4804            } # INSCOPE
4805              
4806            $reconstruct_active_formatting_elements->($insert_to_current);
4807              
4808            !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
4809    
4810            ## TODO: associate with $self->{form_element} if defined
4811    
4812            push @$active_formatting_elements, ['#marker', ''];
4813    
4814            !!!nack ('t379.1');
4815            !!!next-token;
4816            next B;
4817          } elsif ({
4818                    xmp => 1,
4819                    iframe => 1,
4820                    noembed => 1,
4821                    noframes => 1, ## NOTE: This is an "as if in head" code clone.
4822                    noscript => 0, ## TODO: 1 if scripting is enabled
4823                   }->{$token->{tag_name}}) {
4824            if ($token->{tag_name} eq 'xmp') {
4825              !!!cp ('t381');
4826              $reconstruct_active_formatting_elements->($insert_to_current);
4827            } else {
4828              !!!cp ('t399');
4829            }
4830            ## NOTE: There is an "as if in body" code clone.
4831            $parse_rcdata->(CDATA_CONTENT_MODEL);
4832            next B;
4833          } elsif ($token->{tag_name} eq 'isindex') {
4834            !!!parse-error (type => 'isindex', token => $token);
4835            
4836            if (defined $self->{form_element}) {
4837              !!!cp ('t389');
4838            ## Ignore the token            ## Ignore the token
4839              !!!nack ('t389'); ## NOTE: Not acknowledged.
4840            !!!next-token;            !!!next-token;
4841            redo B;            next B;
4842          } elsif ($self->{insertion_mode} eq 'after frameset') {          } else {
4843            if ($token->{type} eq 'character') {            !!!ack ('t391.1');
             if ($token->{data} =~ s/^([\x09\x0A\x0B\x0C\x20]+)//) {  
               $self->{open_elements}->[-1]->[0]->manakai_append_text ($token->{data});  
4844    
4845                unless (length $token->{data}) {            my $at = $token->{attributes};
4846                  !!!next-token;            my $form_attrs;
4847                  redo B;            $form_attrs->{action} = $at->{action} if $at->{action};
4848                }            my $prompt_attr = $at->{prompt};
4849              }            $at->{name} = {name => 'name', value => 'isindex'};
4850              delete $at->{action};
4851              delete $at->{prompt};
4852              my @tokens = (
4853                            {type => START_TAG_TOKEN, tag_name => 'form',
4854                             attributes => $form_attrs,
4855                             line => $token->{line}, column => $token->{column}},
4856                            {type => START_TAG_TOKEN, tag_name => 'hr',
4857                             line => $token->{line}, column => $token->{column}},
4858                            {type => START_TAG_TOKEN, tag_name => 'label',
4859                             line => $token->{line}, column => $token->{column}},
4860                           );
4861              if ($prompt_attr) {
4862                !!!cp ('t390');
4863                push @tokens, {type => CHARACTER_TOKEN, data => $prompt_attr->{value},
4864                               #line => $token->{line}, column => $token->{column},
4865                              };
4866              } else {
4867                !!!cp ('t391');
4868                push @tokens, {type => CHARACTER_TOKEN,
4869                               data => 'This is a searchable index. Insert your search keywords here: ',
4870                               #line => $token->{line}, column => $token->{column},
4871                              }; # SHOULD
4872                ## TODO: make this configurable
4873              }
4874              push @tokens,
4875                            {type => START_TAG_TOKEN, tag_name => 'input', attributes => $at,
4876                             line => $token->{line}, column => $token->{column}},
4877                            #{type => CHARACTER_TOKEN, data => ''}, # SHOULD
4878                            {type => END_TAG_TOKEN, tag_name => 'label',
4879                             line => $token->{line}, column => $token->{column}},
4880                            {type => START_TAG_TOKEN, tag_name => 'hr',
4881                             line => $token->{line}, column => $token->{column}},
4882                            {type => END_TAG_TOKEN, tag_name => 'form',
4883                             line => $token->{line}, column => $token->{column}};
4884              !!!back-token (@tokens);
4885              !!!next-token;
4886              next B;
4887            }
4888          } elsif ($token->{tag_name} eq 'textarea') {
4889            ## 1. Insert
4890            !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
4891            
4892            ## Step 2 # XXX
4893            ## TODO: $self->{form_element} if defined
4894    
4895              #          ## 2. Drop U+000A LINE FEED
4896            } elsif ($token->{type} eq 'comment') {          $self->{ignore_newline} = 1;
4897              my $comment = $self->{document}->create_comment ($token->{data});  
4898              $self->{open_elements}->[-1]->[0]->append_child ($comment);          ## 3. RCDATA
4899              !!!next-token;          $self->{content_model} = RCDATA_CONTENT_MODEL;
4900              redo B;          delete $self->{escape}; # MUST
4901            } elsif ($token->{type} eq 'start tag') {  
4902              if ($token->{tag_name} eq 'noframes') {          ## 4., 6. Insertion mode
4903                $in_body->($insert_to_current);          $self->{insertion_mode} |= IN_CDATA_RCDATA_IM;
4904                redo B;  
4905              } else {          ## XXX: 5. frameset-ok flag
4906                #  
4907            !!!nack ('t392.1');
4908            !!!next-token;
4909            next B;
4910          } elsif ($token->{tag_name} eq 'optgroup' or
4911                   $token->{tag_name} eq 'option') {
4912            ## has an |option| element in scope
4913            INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
4914              my $node = $self->{open_elements}->[$_];
4915              if ($node->[1] == OPTION_EL) {
4916                !!!cp ('t397.1');
4917                ## NOTE: As if </option>
4918                !!!back-token; # <option> or <optgroup>
4919                $token = {type => END_TAG_TOKEN, tag_name => 'option',
4920                          line => $token->{line}, column => $token->{column}};
4921                next B;
4922              } elsif ($node->[1] & SCOPING_EL) {
4923                !!!cp ('t397.2');
4924                last INSCOPE;
4925              }
4926            } # INSCOPE
4927    
4928            $reconstruct_active_formatting_elements->($insert_to_current);
4929    
4930            !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
4931    
4932            !!!nack ('t397.3');
4933            !!!next-token;
4934            redo B;
4935          } elsif ($token->{tag_name} eq 'rt' or
4936                   $token->{tag_name} eq 'rp') {
4937            ## has a |ruby| element in scope
4938            INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
4939              my $node = $self->{open_elements}->[$_];
4940              if ($node->[1] == RUBY_EL) {
4941                !!!cp ('t398.1');
4942                ## generate implied end tags
4943                while ($self->{open_elements}->[-1]->[1] & END_TAG_OPTIONAL_EL) {
4944                  !!!cp ('t398.2');
4945                  pop @{$self->{open_elements}};
4946              }              }
4947            } elsif ($token->{type} eq 'end tag') {              unless ($self->{open_elements}->[-1]->[1] == RUBY_EL) {
4948              if ($token->{tag_name} eq 'html') {                !!!cp ('t398.3');
4949                $phase = 'trailing end';                !!!parse-error (type => 'not closed',
4950                !!!next-token;                                text => $self->{open_elements}->[-1]->[0]
4951                redo B;                                    ->manakai_local_name,
4952              } else {                                token => $token);
4953                #                pop @{$self->{open_elements}}
4954                      while not $self->{open_elements}->[-1]->[1] == RUBY_EL;
4955              }              }
4956            } else {              last INSCOPE;
4957              #            } elsif ($node->[1] & SCOPING_EL) {
4958                !!!cp ('t398.4');
4959                last INSCOPE;
4960            }            }
4961            } # INSCOPE
4962                        
4963            if (defined $token->{tag_name}) {          ## TODO: <non-ruby><rt> is not allowed.
4964              !!!parse-error (type => 'after frameset:'.$token->{tag_name});  
4965            } else {          !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
             !!!parse-error (type => 'after frameset:#'.$token->{type});  
           }  
           ## Ignore the token  
           !!!next-token;  
           redo B;  
4966    
4967            ## ISSUE: An issue in spec there          !!!nack ('t398.5');
4968            !!!next-token;
4969            redo B;
4970          } elsif ($token->{tag_name} eq 'math' or
4971                   $token->{tag_name} eq 'svg') {
4972            $reconstruct_active_formatting_elements->($insert_to_current);
4973    
4974            ## "Adjust MathML attributes" ('math' only) - done in insert-element-f
4975    
4976            ## "adjust SVG attributes" ('svg' only) - done in insert-element-f
4977    
4978            ## "adjust foreign attributes" - done in insert-element-f
4979            
4980            !!!insert-element-f ($token->{tag_name} eq 'math' ? $MML_NS : $SVG_NS, $token->{tag_name}, $token->{attributes}, $token);
4981            
4982            if ($self->{self_closing}) {
4983              pop @{$self->{open_elements}};
4984              !!!ack ('t398.6');
4985          } else {          } else {
4986            die "$0: $self->{insertion_mode}: Unknown insertion mode";            !!!cp ('t398.7');
4987              $self->{insertion_mode} |= IN_FOREIGN_CONTENT_IM;
4988              ## NOTE: |<body><math><mi><svg>| -> "in foreign content" insertion
4989              ## mode, "in body" (not "in foreign content") secondary insertion
4990              ## mode, maybe.
4991          }          }
4992        }  
4993      } elsif ($phase eq 'trailing end') {          !!!next-token;
4994        ## states in the main stage is preserved yet # MUST          next B;
4995                } elsif ({
4996        if ($token->{type} eq 'DOCTYPE') {                  caption => 1, col => 1, colgroup => 1, frame => 1,
4997          !!!parse-error (type => 'after html:#DOCTYPE');                  frameset => 1, head => 1,
4998                    tbody => 1, td => 1, tfoot => 1, th => 1,
4999                    thead => 1, tr => 1,
5000                   }->{$token->{tag_name}}) {
5001            !!!cp ('t401');
5002            !!!parse-error (type => 'in body',
5003                            text => $token->{tag_name}, token => $token);
5004          ## Ignore the token          ## Ignore the token
5005            !!!nack ('t401.1'); ## NOTE: |<col/>| or |<frame/>| here is an error.
5006          !!!next-token;          !!!next-token;
5007          redo B;          next B;
5008        } elsif ($token->{type} eq 'comment') {        } elsif ($token->{tag_name} eq 'param' or
5009          my $comment = $self->{document}->create_comment ($token->{data});                 $token->{tag_name} eq 'source') {
5010          $self->{document}->append_child ($comment);          !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
5011            pop @{$self->{open_elements}};
5012    
5013            !!!ack ('t398.5');
5014          !!!next-token;          !!!next-token;
5015          redo B;          redo B;
5016        } elsif ($token->{type} eq 'character') {        } else {
5017          if ($token->{data} =~ s/^([\x09\x0A\x0B\x0C\x20]+)//) {          if ($token->{tag_name} eq 'image') {
5018            my $data = $1;            !!!cp ('t384');
5019            ## As if in the main phase.            !!!parse-error (type => 'image', token => $token);
5020            ## NOTE: The insertion mode in the main phase            $token->{tag_name} = 'img';
5021            ## just before the phase has been changed to the trailing          } else {
5022            ## end phase is either "after body" or "after frameset".            !!!cp ('t385');
5023            $reconstruct_active_formatting_elements->($insert_to_current)          }
5024              if $phase eq 'main';  
5025            ## NOTE: There is an "as if <br>" code clone.
5026            $reconstruct_active_formatting_elements->($insert_to_current);
5027            
5028            !!!insert-element-t ($token->{tag_name}, $token->{attributes}, $token);
5029    
5030            if ({
5031                 applet => 1, marquee => 1, object => 1,
5032                }->{$token->{tag_name}}) {
5033              !!!cp ('t380');
5034              push @$active_formatting_elements, ['#marker', ''];
5035              !!!nack ('t380.1');
5036            } elsif ({
5037                      b => 1, big => 1, em => 1, font => 1, i => 1,
5038                      s => 1, small => 1, strike => 1,
5039                      strong => 1, tt => 1, u => 1,
5040                     }->{$token->{tag_name}}) {
5041              !!!cp ('t375');
5042              push @$active_formatting_elements, $self->{open_elements}->[-1];
5043              !!!nack ('t375.1');
5044            } elsif ($token->{tag_name} eq 'input') {
5045              !!!cp ('t388');
5046              ## TODO: associate with $self->{form_element} if defined
5047              pop @{$self->{open_elements}};
5048              !!!ack ('t388.2');
5049            } elsif ({
5050                      area => 1, basefont => 1, bgsound => 1, br => 1,
5051                      embed => 1, img => 1, spacer => 1, wbr => 1,
5052                      keygen => 1,
5053                     }->{$token->{tag_name}}) {
5054              !!!cp ('t388.1');
5055              pop @{$self->{open_elements}};
5056              !!!ack ('t388.3');
5057            } elsif ($token->{tag_name} eq 'select') {
5058              ## TODO: associate with $self->{form_element} if defined
5059            
5060              if ($self->{insertion_mode} & TABLE_IMS or
5061                  $self->{insertion_mode} & BODY_TABLE_IMS or
5062                  ($self->{insertion_mode} & IM_MASK) == IN_COLUMN_GROUP_IM) {
5063                !!!cp ('t400.1');
5064                $self->{insertion_mode} = IN_SELECT_IN_TABLE_IM;
5065              } else {
5066                !!!cp ('t400.2');
5067                $self->{insertion_mode} = IN_SELECT_IM;
5068              }
5069              !!!nack ('t400.3');
5070            } else {
5071              !!!nack ('t402');
5072            }
5073            
5074            !!!next-token;
5075            next B;
5076          }
5077        } elsif ($token->{type} == END_TAG_TOKEN) {
5078          if ($token->{tag_name} eq 'body') {
5079    
5080            ## 1. If not "have an element in scope":
5081            ## "has a |body| element in scope"
5082            my $i;
5083            INSCOPE: {
5084              for (reverse @{$self->{open_elements}}) {
5085                if ($_->[1] == BODY_EL) {
5086                  !!!cp ('t405');
5087                  $i = $_;
5088                  last INSCOPE;
5089                } elsif ($_->[1] & SCOPING_EL) {
5090                  !!!cp ('t405.1');
5091                  last;
5092                }
5093              }
5094    
5095              ## NOTE: |<marquee></body>|, |<svg><foreignobject></body>|
5096    
5097              !!!parse-error (type => 'unmatched end tag',
5098                              text => $token->{tag_name}, token => $token);
5099              ## NOTE: Ignore the token.
5100              !!!next-token;
5101              next B;
5102            } # INSCOPE
5103    
5104            ## 2. If unclosed elements:
5105            for (@{$self->{open_elements}}) {
5106              unless ($_->[1] & ALL_END_TAG_OPTIONAL_EL ||
5107                      $_->[1] == OPTGROUP_EL ||
5108                      $_->[1] == OPTION_EL ||
5109                      $_->[1] == RUBY_COMPONENT_EL) {
5110                !!!cp ('t403');
5111                !!!parse-error (type => 'not closed',
5112                                text => $_->[0]->manakai_local_name,
5113                                token => $token);
5114                last;
5115              } else {
5116                !!!cp ('t404');
5117              }
5118            }
5119    
5120            ## 3. Switch the insertion mode.
5121            $self->{insertion_mode} = AFTER_BODY_IM;
5122            !!!next-token;
5123            next B;
5124          } elsif ($token->{tag_name} eq 'html') {
5125            ## TODO: Update this code.  It seems that the code below is not
5126            ## up-to-date, though it has same effect as speced.
5127            if (@{$self->{open_elements}} > 1 and
5128                $self->{open_elements}->[1]->[1] == BODY_EL) {
5129              unless ($self->{open_elements}->[-1]->[1] == BODY_EL) {
5130                !!!cp ('t406');
5131                !!!parse-error (type => 'not closed',
5132                                text => $self->{open_elements}->[1]->[0]
5133                                    ->manakai_local_name,
5134                                token => $token);
5135              } else {
5136                !!!cp ('t407');
5137              }
5138              $self->{insertion_mode} = AFTER_BODY_IM;
5139              ## reprocess
5140              next B;
5141            } else {
5142              !!!cp ('t408');
5143              !!!parse-error (type => 'unmatched end tag',
5144                              text => $token->{tag_name}, token => $token);
5145              ## Ignore the token
5146              !!!next-token;
5147              next B;
5148            }
5149          } elsif ({
5150                    ## NOTE: End tags for non-phrasing flow content elements
5151    
5152                    ## NOTE: The normal ones
5153                    address => 1, article => 1, aside => 1, blockquote => 1,
5154                    center => 1, datagrid => 1, details => 1, dialog => 1,
5155                    dir => 1, div => 1, dl => 1, fieldset => 1, figure => 1,
5156                    footer => 1, header => 1, listing => 1, menu => 1, nav => 1,
5157                    ol => 1, pre => 1, section => 1, ul => 1,
5158    
5159                    ## NOTE: As normal, but ... optional tags
5160                    dd => 1, dt => 1, li => 1,
5161    
5162                    applet => 1, button => 1, marquee => 1, object => 1,
5163                   }->{$token->{tag_name}}) {
5164            ## NOTE: Code for <li> start tags includes "as if </li>" code.
5165            ## Code for <dt> or <dd> start tags includes "as if </dt> or
5166            ## </dd>" code.
5167    
5168            ## has an element in scope
5169            my $i;
5170            INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
5171              my $node = $self->{open_elements}->[$_];
5172              if ($node->[0]->manakai_local_name eq $token->{tag_name}) {
5173                !!!cp ('t410');
5174                $i = $_;
5175                last INSCOPE;
5176              } elsif ($node->[1] & SCOPING_EL) {
5177                !!!cp ('t411');
5178                last INSCOPE;
5179              }
5180            } # INSCOPE
5181    
5182            unless (defined $i) { # has an element in scope
5183              !!!cp ('t413');
5184              !!!parse-error (type => 'unmatched end tag',
5185                              text => $token->{tag_name}, token => $token);
5186              ## NOTE: Ignore the token.
5187            } else {
5188              ## Step 1. generate implied end tags
5189              while ({
5190                      ## END_TAG_OPTIONAL_EL
5191                      dd => ($token->{tag_name} ne 'dd'),
5192                      dt => ($token->{tag_name} ne 'dt'),
5193                      li => ($token->{tag_name} ne 'li'),
5194                      option => 1,
5195                      optgroup => 1,
5196                      p => 1,
5197                      rt => 1,
5198                      rp => 1,
5199                     }->{$self->{open_elements}->[-1]->[0]->manakai_local_name}) {
5200                !!!cp ('t409');
5201                pop @{$self->{open_elements}};
5202              }
5203    
5204              ## Step 2.
5205              if ($self->{open_elements}->[-1]->[0]->manakai_local_name
5206                      ne $token->{tag_name}) {
5207                !!!cp ('t412');
5208                !!!parse-error (type => 'not closed',
5209                                text => $self->{open_elements}->[-1]->[0]
5210                                    ->manakai_local_name,
5211                                token => $token);
5212              } else {
5213                !!!cp ('t414');
5214              }
5215    
5216              ## Step 3.
5217              splice @{$self->{open_elements}}, $i;
5218    
5219              ## Step 4.
5220              $clear_up_to_marker->()
5221                  if {
5222                    applet => 1, button => 1, marquee => 1, object => 1,
5223                  }->{$token->{tag_name}};
5224            }
5225            !!!next-token;
5226            next B;
5227          } elsif ($token->{tag_name} eq 'form') {
5228            ## NOTE: As normal, but interacts with the form element pointer
5229    
5230            undef $self->{form_element};
5231    
5232            ## has an element in scope
5233            my $i;
5234            INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
5235              my $node = $self->{open_elements}->[$_];
5236              if ($node->[1] == FORM_EL) {
5237                !!!cp ('t418');
5238                $i = $_;
5239                last INSCOPE;
5240              } elsif ($node->[1] & SCOPING_EL) {
5241                !!!cp ('t419');
5242                last INSCOPE;
5243              }
5244            } # INSCOPE
5245    
5246            unless (defined $i) { # has an element in scope
5247              !!!cp ('t421');
5248              !!!parse-error (type => 'unmatched end tag',
5249                              text => $token->{tag_name}, token => $token);
5250              ## NOTE: Ignore the token.
5251            } else {
5252              ## Step 1. generate implied end tags
5253              while ($self->{open_elements}->[-1]->[1] & END_TAG_OPTIONAL_EL) {
5254                !!!cp ('t417');
5255                pop @{$self->{open_elements}};
5256              }
5257                        
5258            $self->{open_elements}->[-1]->[0]->manakai_append_text ($data);            ## Step 2.
5259              if ($self->{open_elements}->[-1]->[0]->manakai_local_name
5260                      ne $token->{tag_name}) {
5261                !!!cp ('t417.1');
5262                !!!parse-error (type => 'not closed',
5263                                text => $self->{open_elements}->[-1]->[0]
5264                                    ->manakai_local_name,
5265                                token => $token);
5266              } else {
5267                !!!cp ('t420');
5268              }  
5269                        
5270            unless (length $token->{data}) {            ## Step 3.
5271              !!!next-token;            splice @{$self->{open_elements}}, $i;
5272              redo B;          }
5273    
5274            !!!next-token;
5275            next B;
5276          } elsif ({
5277                    ## NOTE: As normal, except acts as a closer for any ...
5278                    h1 => 1, h2 => 1, h3 => 1, h4 => 1, h5 => 1, h6 => 1,
5279                   }->{$token->{tag_name}}) {
5280            ## has an element in scope
5281            my $i;
5282            INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
5283              my $node = $self->{open_elements}->[$_];
5284              if ($node->[1] == HEADING_EL) {
5285                !!!cp ('t423');
5286                $i = $_;
5287                last INSCOPE;
5288              } elsif ($node->[1] & SCOPING_EL) {
5289                !!!cp ('t424');
5290                last INSCOPE;
5291            }            }
5292            } # INSCOPE
5293    
5294            unless (defined $i) { # has an element in scope
5295              !!!cp ('t425.1');
5296              !!!parse-error (type => 'unmatched end tag',
5297                              text => $token->{tag_name}, token => $token);
5298              ## NOTE: Ignore the token.
5299            } else {
5300              ## Step 1. generate implied end tags
5301              while ($self->{open_elements}->[-1]->[1] & END_TAG_OPTIONAL_EL) {
5302                !!!cp ('t422');
5303                pop @{$self->{open_elements}};
5304              }
5305              
5306              ## Step 2.
5307              if ($self->{open_elements}->[-1]->[0]->manakai_local_name
5308                      ne $token->{tag_name}) {
5309                !!!cp ('t425');
5310                !!!parse-error (type => 'unmatched end tag',
5311                                text => $token->{tag_name}, token => $token);
5312              } else {
5313                !!!cp ('t426');
5314              }
5315    
5316              ## Step 3.
5317              splice @{$self->{open_elements}}, $i;
5318          }          }
5319            
5320            !!!next-token;
5321            next B;
5322          } elsif ($token->{tag_name} eq 'p') {
5323            ## NOTE: As normal, except </p> implies <p> and ...
5324    
5325          !!!parse-error (type => 'after html:#character');          ## has an element in scope
5326          $phase = 'main';          my $non_optional;
5327          ## reprocess          my $i;
5328          redo B;          INSCOPE: for (reverse 0..$#{$self->{open_elements}}) {
5329        } elsif ($token->{type} eq 'start tag' or            my $node = $self->{open_elements}->[$_];
5330                 $token->{type} eq 'end tag') {            if ($node->[1] == P_EL) {
5331          !!!parse-error (type => 'after html:'.$token->{tag_name});              !!!cp ('t410.1');
5332          $phase = 'main';              $i = $_;
5333          ## reprocess              last INSCOPE;
5334          redo B;            } elsif ($node->[1] & SCOPING_EL) {
5335        } elsif ($token->{type} eq 'end-of-file') {              !!!cp ('t411.1');
5336          ## Stop parsing              last INSCOPE;
5337          last B;            } elsif ($node->[1] & END_TAG_OPTIONAL_EL) {
5338                ## NOTE: |END_TAG_OPTIONAL_EL| includes "p"
5339                !!!cp ('t411.2');
5340                #
5341              } else {
5342                !!!cp ('t411.3');
5343                $non_optional ||= $node;
5344                #
5345              }
5346            } # INSCOPE
5347    
5348            if (defined $i) {
5349              ## 1. Generate implied end tags
5350              #
5351    
5352              ## 2. If current node != "p", parse error
5353              if ($non_optional) {
5354                !!!cp ('t412.1');
5355                !!!parse-error (type => 'not closed',
5356                                text => $non_optional->[0]->manakai_local_name,
5357                                token => $token);
5358              } else {
5359                !!!cp ('t414.1');
5360              }
5361    
5362              ## 3. Pop
5363              splice @{$self->{open_elements}}, $i;
5364            } else {
5365              !!!cp ('t413.1');
5366              !!!parse-error (type => 'unmatched end tag',
5367                              text => $token->{tag_name}, token => $token);
5368    
5369              !!!cp ('t415.1');
5370              ## As if <p>, then reprocess the current token
5371              my $el;
5372              !!!create-element ($el, $HTML_NS, 'p',, $token);
5373              $insert->($el);
5374              ## NOTE: Not inserted into |$self->{open_elements}|.
5375            }
5376    
5377            !!!next-token;
5378            next B;
5379          } elsif ({
5380                    a => 1,
5381                    b => 1, big => 1, em => 1, font => 1, i => 1,
5382                    nobr => 1, s => 1, small => 1, strike => 1,
5383                    strong => 1, tt => 1, u => 1,
5384                   }->{$token->{tag_name}}) {
5385            !!!cp ('t427');
5386            $formatting_end_tag->($token);
5387            next B;
5388          } elsif ($token->{tag_name} eq 'br') {
5389            !!!cp ('t428');
5390            !!!parse-error (type => 'unmatched end tag',
5391                            text => 'br', token => $token);
5392    
5393            ## As if <br>
5394            $reconstruct_active_formatting_elements->($insert_to_current);
5395            
5396            my $el;
5397            !!!create-element ($el, $HTML_NS, 'br',, $token);
5398            $insert->($el);
5399            
5400            ## Ignore the token.
5401            !!!next-token;
5402            next B;
5403        } else {        } else {
5404          die "$0: $token->{type}: Unknown token";          if ($token->{tag_name} eq 'sarcasm') {
5405              sleep 0.001; # take a deep breath
5406            }
5407    
5408            ## Step 1
5409            my $node_i = -1;
5410            my $node = $self->{open_elements}->[$node_i];
5411    
5412            ## Step 2
5413            S2: {
5414              my $node_tag_name = $node->[0]->manakai_local_name;
5415              $node_tag_name =~ tr/A-Z/a-z/; # for SVG camelCase tag names
5416              if ($node_tag_name eq $token->{tag_name}) {
5417                ## Step 1
5418                ## generate implied end tags
5419                while ($self->{open_elements}->[-1]->[1] & END_TAG_OPTIONAL_EL) {
5420                  !!!cp ('t430');
5421                  ## NOTE: |<ruby><rt></ruby>|.
5422                  ## ISSUE: <ruby><rt></rt> will also take this code path,
5423                  ## which seems wrong.
5424                  pop @{$self->{open_elements}};
5425                  $node_i++;
5426                }
5427            
5428                ## Step 2
5429                my $current_tag_name
5430                    = $self->{open_elements}->[-1]->[0]->manakai_local_name;
5431                $current_tag_name =~ tr/A-Z/a-z/;
5432                if ($current_tag_name ne $token->{tag_name}) {
5433                  !!!cp ('t431');
5434                  ## NOTE: <x><y></x>
5435                  !!!parse-error (type => 'not closed',
5436                                  text => $self->{open_elements}->[-1]->[0]
5437                                      ->manakai_local_name,
5438                                  token => $token);
5439                } else {
5440                  !!!cp ('t432');
5441                }
5442                
5443                ## Step 3
5444                splice @{$self->{open_elements}}, $node_i if $node_i < 0;
5445    
5446                !!!next-token;
5447                last S2;
5448              } else {
5449                ## Step 3
5450                if (not ($node->[1] & FORMATTING_EL) and
5451                    #not $phrasing_category->{$node->[1]} and
5452                    ($node->[1] & SPECIAL_EL or
5453                     $node->[1] & SCOPING_EL)) {
5454                  !!!cp ('t433');
5455                  !!!parse-error (type => 'unmatched end tag',
5456                                  text => $token->{tag_name}, token => $token);
5457                  ## Ignore the token
5458                  !!!next-token;
5459                  last S2;
5460    
5461                  ## NOTE: |<span><dd></span>a|: In Safari 3.1.2 and Opera
5462                  ## 9.27, "a" is a child of <dd> (conforming).  In
5463                  ## Firefox 3.0.2, "a" is a child of <body>.  In WinIE 7,
5464                  ## "a" is a child of both <body> and <dd>.
5465                }
5466                
5467                !!!cp ('t434');
5468              }
5469              
5470              ## Step 4
5471              $node_i--;
5472              $node = $self->{open_elements}->[$node_i];
5473              
5474              ## Step 5;
5475              redo S2;
5476            } # S2
5477            next B;
5478        }        }
5479      }      }
5480        next B;
5481      } continue { # B
5482        if ($self->{insertion_mode} & IN_FOREIGN_CONTENT_IM) {
5483          ## NOTE: The code below is executed in cases where it does not have
5484          ## to be, but it it is harmless even in those cases.
5485          ## has an element in scope
5486          INSCOPE: {
5487            for (reverse 0..$#{$self->{open_elements}}) {
5488              my $node = $self->{open_elements}->[$_];
5489              if ($node->[1] & FOREIGN_EL) {
5490                last INSCOPE;
5491              } elsif ($node->[1] & SCOPING_EL) {
5492                last;
5493              }
5494            }
5495            
5496            ## NOTE: No foreign element in scope.
5497            $self->{insertion_mode} &= ~ IN_FOREIGN_CONTENT_IM;
5498          } # INSCOPE
5499        }
5500    } # B    } # B
5501    
5502    ## Stop parsing # MUST    ## Stop parsing # MUST
# Line 4635  sub _tree_construction_main ($) { Line 5504  sub _tree_construction_main ($) {
5504    ## TODO: script stuffs    ## TODO: script stuffs
5505  } # _tree_construct_main  } # _tree_construct_main
5506    
5507  sub set_inner_html ($$$) {  ## XXX: How this method is organized is somewhat out of date, although
5508    ## it still does what the current spec documents.
5509    sub set_inner_html ($$$$;$) {
5510    my $class = shift;    my $class = shift;
5511    my $node = shift;    my $node = shift; # /context/
5512    my $s = \$_[0];    #my $s = \$_[0];
5513    my $onerror = $_[1];    my $onerror = $_[1];
5514      my $get_wrapper = $_[2] || sub ($) { return $_[0] };
5515    
5516      ## ISSUE: Should {confident} be true?
5517    
5518    my $nt = $node->node_type;    my $nt = $node->node_type;
5519    if ($nt == 9) {    if ($nt == 9) { # Document (invoke the algorithm with no /context/ element)
5520      # MUST      # MUST
5521            
5522      ## Step 1 # MUST      ## Step 1 # MUST
# Line 4656  sub set_inner_html ($$$) { Line 5530  sub set_inner_html ($$$) {
5530      }      }
5531    
5532      ## Step 3, 4, 5 # MUST      ## Step 3, 4, 5 # MUST
5533      $class->parse_string ($$s => $node, $onerror);      $class->parse_char_string ($_[0] => $node, $onerror, $get_wrapper);
5534    } elsif ($nt == 1) {    } elsif ($nt == 1) { # Element (invoke the algorithm with /context/ element)
5535      ## TODO: If non-html element      ## TODO: If non-html element
5536    
5537      ## NOTE: Most of this code is copied from |parse_string|      ## NOTE: Most of this code is copied from |parse_string|
5538    
5539      ## Step 1 # MUST  ## TODO: Support for $get_wrapper
5540    
5541        ## F1. Create an HTML document.
5542      my $this_doc = $node->owner_document;      my $this_doc = $node->owner_document;
5543      my $doc = $this_doc->implementation->create_document;      my $doc = $this_doc->implementation->create_document;
5544      ## TODO: Mark as HTML document      $doc->manakai_is_html (1);
5545    
5546        ## F2. Propagate quirkness flag
5547        my $node_doc = $node->owner_document;
5548        $doc->manakai_compat_mode ($node_doc->manakai_compat_mode);
5549    
5550        ## F3. Create an HTML parser
5551      my $p = $class->new;      my $p = $class->new;
5552      $p->{document} = $doc;      $p->{document} = $doc;
5553    
5554      ## Step 9 # MUST      ## Step 8 # MUST
5555      my $i = 0;      my $i = 0;
5556      my $line = 1;      $p->{line_prev} = $p->{line} = 1;
5557      my $column = 0;      $p->{column_prev} = $p->{column} = 0;
5558      $p->{set_next_input_character} = sub {      require Whatpm::Charset::DecodeHandle;
5559        my $input = Whatpm::Charset::DecodeHandle::CharString->new (\($_[0]));
5560        $input = $get_wrapper->($input);
5561        $p->{set_nc} = sub {
5562        my $self = shift;        my $self = shift;
5563    
5564        pop @{$self->{prev_input_character}};        my $char = '';
5565        unshift @{$self->{prev_input_character}}, $self->{next_input_character};        if (defined $self->{next_nc}) {
5566            $char = $self->{next_nc};
5567            delete $self->{next_nc};
5568            $self->{nc} = ord $char;
5569          } else {
5570            $self->{char_buffer} = '';
5571            $self->{char_buffer_pos} = 0;
5572            
5573            my $count = $input->manakai_read_until
5574                ($self->{char_buffer}, qr/[^\x00\x0A\x0D]/,
5575                 $self->{char_buffer_pos});
5576            if ($count) {
5577              $self->{line_prev} = $self->{line};
5578              $self->{column_prev} = $self->{column};
5579              $self->{column}++;
5580              $self->{nc}
5581                  = ord substr ($self->{char_buffer},
5582                                $self->{char_buffer_pos}++, 1);
5583              return;
5584            }
5585            
5586            if ($input->read ($char, 1)) {
5587              $self->{nc} = ord $char;
5588            } else {
5589              $self->{nc} = -1;
5590              return;
5591            }
5592          }
5593    
5594          ($p->{line_prev}, $p->{column_prev}) = ($p->{line}, $p->{column});
5595          $p->{column}++;
5596    
5597        $self->{next_input_character} = -1 and return if $i >= length $$s;        if ($self->{nc} == 0x000A) { # LF
5598        $self->{next_input_character} = ord substr $$s, $i++, 1;          $p->{line}++;
5599        $column++;          $p->{column} = 0;
5600            !!!cp ('i1');
5601        if ($self->{next_input_character} == 0x000A) { # LF        } elsif ($self->{nc} == 0x000D) { # CR
5602          $line++;  ## TODO: support for abort/streaming
5603          $column = 0;          my $next = '';
5604        } elsif ($self->{next_input_character} == 0x000D) { # CR          if ($input->read ($next, 1) and $next ne "\x0A") {
5605          $i++ if substr ($$s, $i, 1) eq "\x0A";            $self->{next_nc} = $next;
5606          $self->{next_input_character} = 0x000A; # LF # MUST          }
5607          $line++;          $self->{nc} = 0x000A; # LF # MUST
5608          $column = 0;          $p->{line}++;
5609        } elsif ($self->{next_input_character} > 0x10FFFF) {          $p->{column} = 0;
5610          $self->{next_input_character} = 0xFFFD; # REPLACEMENT CHARACTER # MUST          !!!cp ('i2');
5611        } elsif ($self->{next_input_character} == 0x0000) { # NULL        } elsif ($self->{nc} == 0x0000) { # NULL
5612            !!!cp ('i4');
5613          !!!parse-error (type => 'NULL');          !!!parse-error (type => 'NULL');
5614          $self->{next_input_character} = 0xFFFD; # REPLACEMENT CHARACTER # MUST          $self->{nc} = 0xFFFD; # REPLACEMENT CHARACTER # MUST
5615        }        }
5616      };      };
5617      $p->{prev_input_character} = [-1, -1, -1];  
5618      $p->{next_input_character} = -1;      $p->{read_until} = sub {
5619              #my ($scalar, $specials_range, $offset) = @_;
5620          return 0 if defined $p->{next_nc};
5621    
5622          my $pattern = qr/[^$_[1]\x00\x0A\x0D]/;
5623          my $offset = $_[2] || 0;
5624          
5625          if ($p->{char_buffer_pos} < length $p->{char_buffer}) {
5626            pos ($p->{char_buffer}) = $p->{char_buffer_pos};
5627            if ($p->{char_buffer} =~ /\G(?>$pattern)+/) {
5628              substr ($_[0], $offset)
5629                  = substr ($p->{char_buffer}, $-[0], $+[0] - $-[0]);
5630              my $count = $+[0] - $-[0];
5631              if ($count) {
5632                $p->{column} += $count;
5633                $p->{char_buffer_pos} += $count;
5634                $p->{line_prev} = $p->{line};
5635                $p->{column_prev} = $p->{column} - 1;
5636                $p->{nc} = -1;
5637              }
5638              return $count;
5639            } else {
5640              return 0;
5641            }
5642          } else {
5643            my $count = $input->manakai_read_until ($_[0], $pattern, $_[2]);
5644            if ($count) {
5645              $p->{column} += $count;
5646              $p->{column_prev} += $count;
5647              $p->{nc} = -1;
5648            }
5649            return $count;
5650          }
5651        }; # $p->{read_until}
5652    
5653      my $ponerror = $onerror || sub {      my $ponerror = $onerror || sub {
5654        my (%opt) = @_;        my (%opt) = @_;
5655        warn "Parse error ($opt{type}) at line $opt{line} column $opt{column}\n";        my $line = $opt{line};
5656          my $column = $opt{column};
5657          if (defined $opt{token} and defined $opt{token}->{line}) {
5658            $line = $opt{token}->{line};
5659            $column = $opt{token}->{column};
5660          }
5661          warn "Parse error ($opt{type}) at line $line column $column\n";
5662      };      };
5663      $p->{parse_error} = sub {      $p->{parse_error} = sub {
5664        $ponerror->(@_, line => $line, column => $column);        $ponerror->(line => $p->{line}, column => $p->{column}, @_);
5665      };      };
5666            
5667        my $char_onerror = sub {
5668          my (undef, $type, %opt) = @_;
5669          $ponerror->(layer => 'encode',
5670                      line => $p->{line}, column => $p->{column} + 1,
5671                      %opt, type => $type);
5672        }; # $char_onerror
5673        $input->onerror ($char_onerror);
5674    
5675      $p->_initialize_tokenizer;      $p->_initialize_tokenizer;
5676      $p->_initialize_tree_constructor;      $p->_initialize_tree_constructor;
5677    
5678      ## Step 2      ## F4. If /context/ is not undef...
     my $node_ln = $node->local_name;  
     $p->{content_model_flag} = {  
       title => 'RCDATA',  
       textarea => 'RCDATA',  
       style => 'CDATA',  
       script => 'CDATA',  
       xmp => 'CDATA',  
       iframe => 'CDATA',  
       noembed => 'CDATA',  
       noframes => 'CDATA',  
       noscript => 'CDATA',  
       plaintext => 'PLAINTEXT',  
     }->{$node_ln} || 'PCDATA';  
        ## ISSUE: What is "the name of the element"? local name?  
5679    
5680      $p->{inner_html_node} = [$node, $node_ln];      ## F4.1. content model flag
5681        my $node_ln = $node->manakai_local_name;
5682        $p->{content_model} = {
5683          title => RCDATA_CONTENT_MODEL,
5684          textarea => RCDATA_CONTENT_MODEL,
5685          style => CDATA_CONTENT_MODEL,
5686          script => CDATA_CONTENT_MODEL,
5687          xmp => CDATA_CONTENT_MODEL,
5688          iframe => CDATA_CONTENT_MODEL,
5689          noembed => CDATA_CONTENT_MODEL,
5690          noframes => CDATA_CONTENT_MODEL,
5691          noscript => CDATA_CONTENT_MODEL,
5692          plaintext => PLAINTEXT_CONTENT_MODEL,
5693        }->{$node_ln};
5694        $p->{content_model} = PCDATA_CONTENT_MODEL
5695            unless defined $p->{content_model};
5696    
5697      ## Step 4      $p->{inner_html_node} = [$node, $el_category->{$node_ln}];
5698          ## TODO: Foreign element OK?
5699    
5700        ## F4.2. Root |html| element
5701      my $root = $doc->create_element_ns      my $root = $doc->create_element_ns
5702        ('http://www.w3.org/1999/xhtml', [undef, 'html']);        ('http://www.w3.org/1999/xhtml', [undef, 'html']);
5703    
5704      ## Step 5 # MUST      ## F4.3.
5705      $doc->append_child ($root);      $doc->append_child ($root);
5706    
5707      ## Step 6 # MUST      ## F4.4.
5708      push @{$p->{open_elements}}, [$root, 'html'];      push @{$p->{open_elements}}, [$root, $el_category->{html}];
5709    
5710      undef $p->{head_element};      undef $p->{head_element};
5711        undef $p->{head_element_inserted};
5712    
5713      ## Step 7 # MUST      ## F4.5.
5714      $p->_reset_insertion_mode;      $p->_reset_insertion_mode;
5715    
5716      ## Step 8 # MUST      ## F4.6.
5717      my $anode = $node;      my $anode = $node;
5718      AN: while (defined $anode) {      AN: while (defined $anode) {
5719        if ($anode->node_type == 1) {        if ($anode->node_type == 1) {
5720          my $nsuri = $anode->namespace_uri;          my $nsuri = $anode->namespace_uri;
5721          if (defined $nsuri and $nsuri eq 'http://www.w3.org/1999/xhtml') {          if (defined $nsuri and $nsuri eq 'http://www.w3.org/1999/xhtml') {
5722            if ($anode->local_name eq 'form') { ## TODO: case?            if ($anode->manakai_local_name eq 'form') {
5723                !!!cp ('i5');
5724              $p->{form_element} = $anode;              $p->{form_element} = $anode;
5725              last AN;              last AN;
5726            }            }
# Line 4759  sub set_inner_html ($$$) { Line 5728  sub set_inner_html ($$$) {
5728        }        }
5729        $anode = $anode->parent_node;        $anode = $anode->parent_node;
5730      } # AN      } # AN
5731        
5732      ## Step 3 # MUST      ## F.6. Start the parser.
     ## Step 10 # MUST  
5733      {      {
5734        my $self = $p;        my $self = $p;
5735        !!!next-token;        !!!next-token;
5736      }      }
5737      $p->_tree_construction_main;      $p->_tree_construction_main;
5738    
5739      ## Step 11 # MUST      ## F.7.
5740      my @cn = @{$node->child_nodes};      my @cn = @{$node->child_nodes};
5741      for (@cn) {      for (@cn) {
5742        $node->remove_child ($_);        $node->remove_child ($_);
5743      }      }
5744      ## ISSUE: mutation events? read-only?      ## ISSUE: mutation events? read-only?
5745    
5746      ## Step 12 # MUST      ## Step 11 # MUST
5747      @cn = @{$root->child_nodes};      @cn = @{$root->child_nodes};
5748      for (@cn) {      for (@cn) {
5749        $this_doc->adopt_node ($_);        $this_doc->adopt_node ($_);
# Line 4784  sub set_inner_html ($$$) { Line 5752  sub set_inner_html ($$$) {
5752      ## ISSUE: mutation events?      ## ISSUE: mutation events?
5753    
5754      $p->_terminate_tree_constructor;      $p->_terminate_tree_constructor;
5755    
5756        delete $p->{parse_error}; # delete loop
5757    } else {    } else {
5758      die "$0: |set_inner_html| is not defined for node of type $nt";      die "$0: |set_inner_html| is not defined for node of type $nt";
5759    }    }
# Line 4791  sub set_inner_html ($$$) { Line 5761  sub set_inner_html ($$$) {
5761    
5762  } # tree construction stage  } # tree construction stage
5763    
5764  sub get_inner_html ($$$) {  package Whatpm::HTML::RestartParser;
5765    my (undef, $node, $on_error) = @_;  push our @ISA, 'Error';
   
   ## Step 1  
   my $s = '';  
   
   my $in_cdata;  
   my $parent = $node;  
   while (defined $parent) {  
     if ($parent->node_type == 1 and  
         $parent->namespace_uri eq 'http://www.w3.org/1999/xhtml' and  
         {  
           style => 1, script => 1, xmp => 1, iframe => 1,  
           noembed => 1, noframes => 1, noscript => 1,  
         }->{$parent->local_name}) { ## TODO: case thingy  
       $in_cdata = 1;  
     }  
     $parent = $parent->parent_node;  
   }  
   
   ## Step 2  
   my @node = @{$node->child_nodes};  
   C: while (@node) {  
     my $child = shift @node;  
     unless (ref $child) {  
       if ($child eq 'cdata-out') {  
         $in_cdata = 0;  
       } else {  
         $s .= $child; # end tag  
       }  
       next C;  
     }  
       
     my $nt = $child->node_type;  
     if ($nt == 1) { # Element  
       my $tag_name = lc $child->tag_name; ## ISSUE: Definition of "lowercase"  
       $s .= '<' . $tag_name;  
   
       ## ISSUE: Non-html elements  
   
       my @attrs = @{$child->attributes}; # sort order MUST be stable  
       for my $attr (@attrs) { # order is implementation dependent  
         my $attr_name = lc $attr->name; ## ISSUE: Definition of "lowercase"  
         $s .= ' ' . $attr_name . '="';  
         my $attr_value = $attr->value;  
         ## escape  
         $attr_value =~ s/&/&amp;/g;  
         $attr_value =~ s/</&lt;/g;  
         $attr_value =~ s/>/&gt;/g;  
         $attr_value =~ s/"/&quot;/g;  
         $s .= $attr_value . '"';  
       }  
       $s .= '>';  
         
       next C if {  
         area => 1, base => 1, basefont => 1, bgsound => 1,  
         br => 1, col => 1, embed => 1, frame => 1, hr => 1,  
         img => 1, input => 1, link => 1, meta => 1, param => 1,  
         spacer => 1, wbr => 1,  
       }->{$tag_name};  
   
       if (not $in_cdata and {  
         style => 1, script => 1, xmp => 1, iframe => 1,  
         noembed => 1, noframes => 1, noscript => 1,  
       }->{$tag_name}) {  
         unshift @node, 'cdata-out';  
         $in_cdata = 1;  
       }  
   
       unshift @node, @{$child->child_nodes}, '</' . $tag_name . '>';  
     } elsif ($nt == 3 or $nt == 4) {  
       if ($in_cdata) {  
         $s .= $child->data;  
       } else {  
         my $value = $child->data;  
         $value =~ s/&/&amp;/g;  
         $value =~ s/</&lt;/g;  
         $value =~ s/>/&gt;/g;  
         $value =~ s/"/&quot;/g;  
         $s .= $value;  
       }  
     } elsif ($nt == 8) {  
       $s .= '<!--' . $child->data . '-->';  
     } elsif ($nt == 10) {  
       $s .= '<!DOCTYPE ' . $child->name . '>';  
     } elsif ($nt == 5) { # entrefs  
       push @node, @{$child->child_nodes};  
     } else {  
       $on_error->($child) if defined $on_error;  
     }  
     ## ISSUE: This code does not support PIs.  
   } # C  
     
   ## Step 3  
   return \$s;  
 } # get_inner_html  
5766    
5767  1;  1;
5768  # $Date$  # $Date$

Legend:
Removed from v.1.17  
changed lines
  Added in v.1.233

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24