parse.go 31.3 KB
Newer Older
Nigel Tao's avatar
Nigel Tao committed
1 2 3 4 5 6 7 8
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package html

import (
	"io"
9
	"strings"
Nigel Tao's avatar
Nigel Tao committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
)

// A parser implements the HTML5 parsing algorithm:
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html#tree-construction
type parser struct {
	// tokenizer provides the tokens for the parser.
	tokenizer *Tokenizer
	// tok is the most recently read token.
	tok Token
	// Self-closing tags like <hr/> are re-interpreted as a two-token sequence:
	// <hr> followed by </hr>. hasSelfClosingToken is true if we have just read
	// the synthetic start tag and the next one due is the matching end tag.
	hasSelfClosingToken bool
	// doc is the document root element.
	doc *Node
25 26 27
	// The stack of open elements (section 11.2.3.2) and active formatting
	// elements (section 11.2.3.3).
	oe, afe nodeStack
28
	// Element pointers (section 11.2.3.4).
Nigel Tao's avatar
Nigel Tao committed
29
	head, form *Node
30
	// Other parsing state flags (section 11.2.3.5).
Nigel Tao's avatar
Nigel Tao committed
31
	scripting, framesetOK bool
32 33
	// im is the current insertion mode.
	im insertionMode
34 35 36
	// originalIM is the insertion mode to go back to after completing a text
	// or inTableText insertion mode.
	originalIM insertionMode
37 38 39
	// fosterParenting is whether new elements should be inserted according to
	// the foster parenting rules (section 11.2.5.3).
	fosterParenting bool
Nigel Tao's avatar
Nigel Tao committed
40 41 42
}

func (p *parser) top() *Node {
43 44
	if n := p.oe.top(); n != nil {
		return n
Nigel Tao's avatar
Nigel Tao committed
45 46 47 48
	}
	return p.doc
}

49
// stopTags for use in popUntil. These come from section 11.2.3.2.
50 51 52 53 54 55 56
var (
	defaultScopeStopTags  = []string{"applet", "caption", "html", "table", "td", "th", "marquee", "object"}
	listItemScopeStopTags = []string{"applet", "caption", "html", "table", "td", "th", "marquee", "object", "ol", "ul"}
	buttonScopeStopTags   = []string{"applet", "caption", "html", "table", "td", "th", "marquee", "object", "button"}
	tableScopeStopTags    = []string{"html", "table"}
)

57 58 59 60 61
// stopTags for use in clearStackToContext.
var (
	tableRowContextStopTags = []string{"tr", "html"}
)

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
// popUntil pops the stack of open elements at the highest element whose tag
// is in matchTags, provided there is no higher element in stopTags. It returns
// whether or not there was such an element. If there was not, popUntil leaves
// the stack unchanged.
//
// For example, if the stack was:
// ["html", "body", "font", "table", "b", "i", "u"]
// then popUntil([]string{"html, "table"}, "font") would return false, but
// popUntil([]string{"html, "table"}, "i") would return true and the resultant
// stack would be:
// ["html", "body", "font", "table", "b"]
//
// If an element's tag is in both stopTags and matchTags, then the stack will
// be popped and the function returns true (provided, of course, there was no
// higher element in the stack that was also in stopTags). For example,
// popUntil([]string{"html, "table"}, "table") would return true and leave:
// ["html", "body", "font"]
func (p *parser) popUntil(stopTags []string, matchTags ...string) bool {
80 81 82 83 84 85 86 87 88 89 90
	if i := p.indexOfElementInScope(stopTags, matchTags...); i != -1 {
		p.oe = p.oe[:i]
		return true
	}
	return false
}

// indexOfElementInScope returns the index in p.oe of the highest element
// whose tag is in matchTags that is in scope according to stopTags.
// If no matching element is in scope, it returns -1.
func (p *parser) indexOfElementInScope(stopTags []string, matchTags ...string) int {
91 92
	for i := len(p.oe) - 1; i >= 0; i-- {
		tag := p.oe[i].Data
93 94
		for _, t := range matchTags {
			if t == tag {
95
				return i
96 97 98 99
			}
		}
		for _, t := range stopTags {
			if t == tag {
100
				return -1
101 102 103
			}
		}
	}
104 105 106 107 108 109 110
	return -1
}

// elementInScope is like popUntil, except that it doesn't modify the stack of
// open elements.
func (p *parser) elementInScope(stopTags []string, matchTags ...string) bool {
	return p.indexOfElementInScope(stopTags, matchTags...) != -1
111 112
}

113 114
// addChild adds a child node n to the top element, and pushes n onto the stack
// of open elements if it is an element node.
Nigel Tao's avatar
Nigel Tao committed
115
func (p *parser) addChild(n *Node) {
116 117 118 119 120 121
	if p.fosterParenting {
		p.fosterParent(n)
	} else {
		p.top().Add(n)
	}

Nigel Tao's avatar
Nigel Tao committed
122
	if n.Type == ElementNode {
123
		p.oe = append(p.oe, n)
Nigel Tao's avatar
Nigel Tao committed
124 125 126
	}
}

127 128 129
// fosterParent adds a child node according to the foster parenting rules.
// Section 11.2.5.3, "foster parenting".
func (p *parser) fosterParent(n *Node) {
130
	p.fosterParenting = false
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
	var table, parent *Node
	var i int
	for i = len(p.oe) - 1; i >= 0; i-- {
		if p.oe[i].Data == "table" {
			table = p.oe[i]
			break
		}
	}

	if table == nil {
		// The foster parent is the html element.
		parent = p.oe[0]
	} else {
		parent = table.Parent
	}
	if parent == nil {
		parent = p.oe[i-1]
	}

	var child *Node
	for i, child = range parent.Child {
		if child == table {
			break
		}
	}

157 158 159 160 161
	if i > 0 && parent.Child[i-1].Type == TextNode && n.Type == TextNode {
		parent.Child[i-1].Data += n.Data
		return
	}

162 163 164 165 166 167 168 169 170 171
	if i == len(parent.Child) {
		parent.Add(n)
	} else {
		// Insert n into parent.Child at index i.
		parent.Child = append(parent.Child[:i+1], parent.Child[i:]...)
		parent.Child[i] = n
		n.Parent = parent
	}
}

172 173
// addText adds text to the preceding node if it is a text node, or else it
// calls addChild with a new text node.
174 175
func (p *parser) addText(text string) {
	// TODO: distinguish whitespace text from others.
176 177 178 179 180
	t := p.top()
	if i := len(t.Child); i > 0 && t.Child[i-1].Type == TextNode {
		t.Child[i-1].Data += text
		return
	}
Nigel Tao's avatar
Nigel Tao committed
181 182
	p.addChild(&Node{
		Type: TextNode,
183 184 185 186 187 188 189 190 191 192
		Data: text,
	})
}

// addElement calls addChild with an element node.
func (p *parser) addElement(tag string, attr []Attribute) {
	p.addChild(&Node{
		Type: ElementNode,
		Data: tag,
		Attr: attr,
Nigel Tao's avatar
Nigel Tao committed
193 194 195
	})
}

196
// Section 11.2.3.3.
197 198
func (p *parser) addFormattingElement(tag string, attr []Attribute) {
	p.addElement(tag, attr)
199
	p.afe = append(p.afe, p.top())
Nigel Tao's avatar
Nigel Tao committed
200 201 202
	// TODO.
}

203 204 205 206 207 208 209 210 211 212
// Section 11.2.3.3.
func (p *parser) clearActiveFormattingElements() {
	for {
		n := p.afe.pop()
		if len(p.afe) == 0 || n.Type == scopeMarkerNode {
			return
		}
	}
}

213
// Section 11.2.3.3.
Nigel Tao's avatar
Nigel Tao committed
214
func (p *parser) reconstructActiveFormattingElements() {
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
	n := p.afe.top()
	if n == nil {
		return
	}
	if n.Type == scopeMarkerNode || p.oe.index(n) != -1 {
		return
	}
	i := len(p.afe) - 1
	for n.Type != scopeMarkerNode && p.oe.index(n) == -1 {
		if i == 0 {
			i = -1
			break
		}
		i--
		n = p.afe[i]
	}
	for {
		i++
233 234 235
		clone := p.afe[i].clone()
		p.addChild(clone)
		p.afe[i] = clone
236 237 238 239
		if i == len(p.afe)-1 {
			break
		}
	}
Nigel Tao's avatar
Nigel Tao committed
240 241 242 243
}

// read reads the next token. This is usually from the tokenizer, but it may
// be the synthesized end tag implied by a self-closing tag.
244
func (p *parser) read() error {
Nigel Tao's avatar
Nigel Tao committed
245 246 247 248 249 250
	if p.hasSelfClosingToken {
		p.hasSelfClosingToken = false
		p.tok.Type = EndTagToken
		p.tok.Attr = nil
		return nil
	}
251
	p.tokenizer.Next()
Nigel Tao's avatar
Nigel Tao committed
252
	p.tok = p.tokenizer.Token()
253 254
	switch p.tok.Type {
	case ErrorToken:
255
		return p.tokenizer.Err()
256
	case SelfClosingTagToken:
Nigel Tao's avatar
Nigel Tao committed
257 258 259 260 261 262
		p.hasSelfClosingToken = true
		p.tok.Type = StartTagToken
	}
	return nil
}

263
// Section 11.2.4.
Nigel Tao's avatar
Nigel Tao committed
264 265 266 267
func (p *parser) acknowledgeSelfClosingTag() {
	p.hasSelfClosingToken = false
}

268
// An insertion mode (section 11.2.3.1) is the state transition function from
269
// a particular state in the HTML5 parser's state machine. It updates the
270 271 272
// parser's fields depending on parser.tok (where ErrorToken means EOF).
// It returns whether the token was consumed.
type insertionMode func(*parser) bool
273

274 275 276
// setOriginalIM sets the insertion mode to return to after completing a text or
// inTableText insertion mode.
// Section 11.2.3.1, "using the rules for".
277
func (p *parser) setOriginalIM() {
278 279 280
	if p.originalIM != nil {
		panic("html: bad parser state: originalIM was set twice")
	}
281
	p.originalIM = p.im
282 283
}

Nigel Tao's avatar
Nigel Tao committed
284
// Section 11.2.3.1, "reset the insertion mode".
285
func (p *parser) resetInsertionMode() {
Nigel Tao's avatar
Nigel Tao committed
286 287 288 289 290 291 292
	for i := len(p.oe) - 1; i >= 0; i-- {
		n := p.oe[i]
		if i == 0 {
			// TODO: set n to the context element, for HTML fragment parsing.
		}
		switch n.Data {
		case "select":
293
			p.im = inSelectIM
Nigel Tao's avatar
Nigel Tao committed
294
		case "td", "th":
295
			p.im = inCellIM
Nigel Tao's avatar
Nigel Tao committed
296
		case "tr":
297
			p.im = inRowIM
Nigel Tao's avatar
Nigel Tao committed
298
		case "tbody", "thead", "tfoot":
299
			p.im = inTableBodyIM
Nigel Tao's avatar
Nigel Tao committed
300
		case "caption":
301
			// TODO: p.im = inCaptionIM
Nigel Tao's avatar
Nigel Tao committed
302
		case "colgroup":
303
			p.im = inColumnGroupIM
Nigel Tao's avatar
Nigel Tao committed
304
		case "table":
305
			p.im = inTableIM
Nigel Tao's avatar
Nigel Tao committed
306
		case "head":
307
			p.im = inBodyIM
Nigel Tao's avatar
Nigel Tao committed
308
		case "body":
309
			p.im = inBodyIM
Nigel Tao's avatar
Nigel Tao committed
310
		case "frameset":
311
			p.im = inFramesetIM
Nigel Tao's avatar
Nigel Tao committed
312
		case "html":
313 314 315
			p.im = beforeHeadIM
		default:
			continue
Nigel Tao's avatar
Nigel Tao committed
316
		}
317
		return
Nigel Tao's avatar
Nigel Tao committed
318
	}
319
	p.im = inBodyIM
Nigel Tao's avatar
Nigel Tao committed
320 321
}

322
// Section 11.2.5.4.1.
323
func initialIM(p *parser) bool {
324 325 326 327 328 329
	switch p.tok.Type {
	case CommentToken:
		p.doc.Add(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
330
		return true
331 332
	case DoctypeToken:
		p.doc.Add(&Node{
333 334 335
			Type: DoctypeNode,
			Data: p.tok.Data,
		})
336 337
		p.im = beforeHTMLIM
		return true
338 339 340
	}
	// TODO: set "quirks mode"? It's defined in the DOM spec instead of HTML5 proper,
	// and so switching on "quirks mode" might belong in a different package.
341 342
	p.im = beforeHTMLIM
	return false
Nigel Tao's avatar
Nigel Tao committed
343 344
}

345
// Section 11.2.5.4.2.
346
func beforeHTMLIM(p *parser) bool {
Nigel Tao's avatar
Nigel Tao committed
347 348 349
	switch p.tok.Type {
	case StartTagToken:
		if p.tok.Data == "html" {
350
			p.addElement(p.tok.Data, p.tok.Attr)
351 352
			p.im = beforeHeadIM
			return true
Nigel Tao's avatar
Nigel Tao committed
353 354
		}
	case EndTagToken:
355 356
		switch p.tok.Data {
		case "head", "body", "html", "br":
357
			// Drop down to creating an implied <html> tag.
358 359
		default:
			// Ignore the token.
360
			return true
361
		}
362 363 364 365 366
	case CommentToken:
		p.doc.Add(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
367
		return true
Nigel Tao's avatar
Nigel Tao committed
368
	}
369 370
	// Create an implied <html> tag.
	p.addElement("html", nil)
371 372
	p.im = beforeHeadIM
	return false
Nigel Tao's avatar
Nigel Tao committed
373 374
}

375
// Section 11.2.5.4.3.
376
func beforeHeadIM(p *parser) bool {
Nigel Tao's avatar
Nigel Tao committed
377 378 379 380 381 382
	var (
		add     bool
		attr    []Attribute
		implied bool
	)
	switch p.tok.Type {
383 384
	case ErrorToken:
		implied = true
Nigel Tao's avatar
Nigel Tao committed
385
	case TextToken:
386
		// TODO: distinguish whitespace text from others.
Nigel Tao's avatar
Nigel Tao committed
387 388 389 390 391 392 393
		implied = true
	case StartTagToken:
		switch p.tok.Data {
		case "head":
			add = true
			attr = p.tok.Attr
		case "html":
394
			return inBodyIM(p)
Nigel Tao's avatar
Nigel Tao committed
395 396 397 398
		default:
			implied = true
		}
	case EndTagToken:
399 400 401 402 403 404
		switch p.tok.Data {
		case "head", "body", "html", "br":
			implied = true
		default:
			// Ignore the token.
		}
405 406 407 408 409
	case CommentToken:
		p.addChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
410
		return true
Nigel Tao's avatar
Nigel Tao committed
411 412
	}
	if add || implied {
413
		p.addElement("head", attr)
414
		p.head = p.top()
Nigel Tao's avatar
Nigel Tao committed
415
	}
416 417
	p.im = inHeadIM
	return !implied
Nigel Tao's avatar
Nigel Tao committed
418 419
}

420 421
const whitespace = " \t\r\n\f"

422
// Section 11.2.5.4.4.
423
func inHeadIM(p *parser) bool {
Nigel Tao's avatar
Nigel Tao committed
424 425 426 427 428
	var (
		pop     bool
		implied bool
	)
	switch p.tok.Type {
429 430 431 432 433 434 435 436
	case ErrorToken:
		implied = true
	case TextToken:
		s := strings.TrimLeft(p.tok.Data, whitespace)
		if len(s) < len(p.tok.Data) {
			// Add the initial whitespace to the current node.
			p.addText(p.tok.Data[:len(p.tok.Data)-len(s)])
			if s == "" {
437
				return true
438 439 440
			}
			p.tok.Data = s
		}
Nigel Tao's avatar
Nigel Tao committed
441 442 443
		implied = true
	case StartTagToken:
		switch p.tok.Data {
444 445 446 447
		case "base", "basefont", "bgsound", "command", "link", "meta":
			p.addElement(p.tok.Data, p.tok.Attr)
			p.oe.pop()
			p.acknowledgeSelfClosingTag()
448
		case "script", "title", "noscript", "noframes", "style":
449
			p.addElement(p.tok.Data, p.tok.Attr)
450 451 452
			p.setOriginalIM()
			p.im = textIM
			return true
Nigel Tao's avatar
Nigel Tao committed
453 454 455 456
		default:
			implied = true
		}
	case EndTagToken:
457 458
		switch p.tok.Data {
		case "head":
Nigel Tao's avatar
Nigel Tao committed
459
			pop = true
460 461 462 463
		case "body", "html", "br":
			implied = true
		default:
			// Ignore the token.
464
			return true
Nigel Tao's avatar
Nigel Tao committed
465
		}
466 467 468 469 470
	case CommentToken:
		p.addChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
471
		return true
Nigel Tao's avatar
Nigel Tao committed
472 473
	}
	if pop || implied {
474
		n := p.oe.pop()
Nigel Tao's avatar
Nigel Tao committed
475
		if n.Data != "head" {
476
			panic("html: bad parser state: <head> element not found, in the in-head insertion mode")
Nigel Tao's avatar
Nigel Tao committed
477
		}
478 479
		p.im = afterHeadIM
		return !implied
Nigel Tao's avatar
Nigel Tao committed
480
	}
481
	return true
Nigel Tao's avatar
Nigel Tao committed
482 483
}

484
// Section 11.2.5.4.6.
485
func afterHeadIM(p *parser) bool {
Nigel Tao's avatar
Nigel Tao committed
486 487 488 489 490 491 492
	var (
		add        bool
		attr       []Attribute
		framesetOK bool
		implied    bool
	)
	switch p.tok.Type {
493
	case ErrorToken, TextToken:
Nigel Tao's avatar
Nigel Tao committed
494 495 496 497 498 499 500 501 502 503 504
		implied = true
		framesetOK = true
	case StartTagToken:
		switch p.tok.Data {
		case "html":
			// TODO.
		case "body":
			add = true
			attr = p.tok.Attr
			framesetOK = false
		case "frameset":
Andrew Balholm's avatar
Andrew Balholm committed
505
			p.addElement(p.tok.Data, p.tok.Attr)
506 507
			p.im = inFramesetIM
			return true
Nigel Tao's avatar
Nigel Tao committed
508
		case "base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "title":
509 510
			p.oe = append(p.oe, p.head)
			defer p.oe.pop()
511
			return inHeadIM(p)
Nigel Tao's avatar
Nigel Tao committed
512 513 514 515 516 517 518
		case "head":
			// TODO.
		default:
			implied = true
			framesetOK = true
		}
	case EndTagToken:
519 520 521 522 523 524
		switch p.tok.Data {
		case "body", "html", "br":
			implied = true
			framesetOK = true
		default:
			// Ignore the token.
525
			return true
526
		}
527 528 529 530 531
	case CommentToken:
		p.addChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
532
		return true
Nigel Tao's avatar
Nigel Tao committed
533 534
	}
	if add || implied {
535
		p.addElement("body", attr)
Nigel Tao's avatar
Nigel Tao committed
536 537
		p.framesetOK = framesetOK
	}
538 539
	p.im = inBodyIM
	return !implied
Nigel Tao's avatar
Nigel Tao committed
540 541
}

542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
// copyAttributes copies attributes of src not found on dst to dst.
func copyAttributes(dst *Node, src Token) {
	if len(src.Attr) == 0 {
		return
	}
	attr := map[string]string{}
	for _, a := range dst.Attr {
		attr[a.Key] = a.Val
	}
	for _, a := range src.Attr {
		if _, ok := attr[a.Key]; !ok {
			dst.Attr = append(dst.Attr, a)
			attr[a.Key] = a.Val
		}
	}
}

559
// Section 11.2.5.4.7.
560
func inBodyIM(p *parser) bool {
Nigel Tao's avatar
Nigel Tao committed
561 562
	switch p.tok.Type {
	case TextToken:
563
		p.reconstructActiveFormattingElements()
Nigel Tao's avatar
Nigel Tao committed
564 565 566 567 568
		p.addText(p.tok.Data)
		p.framesetOK = false
	case StartTagToken:
		switch p.tok.Data {
		case "address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol", "p", "section", "summary", "ul":
569 570
			p.popUntil(buttonScopeStopTags, "p")
			p.addElement(p.tok.Data, p.tok.Attr)
Nigel Tao's avatar
Nigel Tao committed
571
		case "h1", "h2", "h3", "h4", "h5", "h6":
572
			p.popUntil(buttonScopeStopTags, "p")
Nigel Tao's avatar
Nigel Tao committed
573 574
			switch n := p.top(); n.Data {
			case "h1", "h2", "h3", "h4", "h5", "h6":
575
				p.oe.pop()
Nigel Tao's avatar
Nigel Tao committed
576 577
			}
			p.addElement(p.tok.Data, p.tok.Attr)
578
		case "a":
579 580 581 582 583 584 585
			for i := len(p.afe) - 1; i >= 0 && p.afe[i].Type != scopeMarkerNode; i-- {
				if n := p.afe[i]; n.Type == ElementNode && n.Data == "a" {
					p.inBodyEndTagFormatting("a")
					p.oe.remove(n)
					p.afe.remove(n)
					break
				}
586 587 588
			}
			p.reconstructActiveFormattingElements()
			p.addFormattingElement(p.tok.Data, p.tok.Attr)
Nigel Tao's avatar
Nigel Tao committed
589 590
		case "b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u":
			p.reconstructActiveFormattingElements()
591
			p.addFormattingElement(p.tok.Data, p.tok.Attr)
592 593 594 595 596
		case "applet", "marquee", "object":
			p.reconstructActiveFormattingElements()
			p.addElement(p.tok.Data, p.tok.Attr)
			p.afe = append(p.afe, &scopeMarker)
			p.framesetOK = false
Nigel Tao's avatar
Nigel Tao committed
597 598
		case "area", "br", "embed", "img", "input", "keygen", "wbr":
			p.reconstructActiveFormattingElements()
599
			p.addElement(p.tok.Data, p.tok.Attr)
600
			p.oe.pop()
Nigel Tao's avatar
Nigel Tao committed
601 602
			p.acknowledgeSelfClosingTag()
			p.framesetOK = false
603
		case "table":
604
			p.popUntil(buttonScopeStopTags, "p") // TODO: skip this step in quirks mode.
605 606
			p.addElement(p.tok.Data, p.tok.Attr)
			p.framesetOK = false
607 608
			p.im = inTableIM
			return true
Nigel Tao's avatar
Nigel Tao committed
609
		case "hr":
610
			p.popUntil(buttonScopeStopTags, "p")
611
			p.addElement(p.tok.Data, p.tok.Attr)
612
			p.oe.pop()
Nigel Tao's avatar
Nigel Tao committed
613 614
			p.acknowledgeSelfClosingTag()
			p.framesetOK = false
Nigel Tao's avatar
Nigel Tao committed
615 616 617 618 619
		case "select":
			p.reconstructActiveFormattingElements()
			p.addElement(p.tok.Data, p.tok.Attr)
			p.framesetOK = false
			// TODO: detect <select> inside a table.
620 621
			p.im = inSelectIM
			return true
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
		case "li":
			p.framesetOK = false
			for i := len(p.oe) - 1; i >= 0; i-- {
				node := p.oe[i]
				switch node.Data {
				case "li":
					p.popUntil(listItemScopeStopTags, "li")
				case "address", "div", "p":
					continue
				default:
					if !isSpecialElement[node.Data] {
						continue
					}
				}
				break
			}
			p.popUntil(buttonScopeStopTags, "p")
Andrew Balholm's avatar
Andrew Balholm committed
639
			p.addElement(p.tok.Data, p.tok.Attr)
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
		case "dd", "dt":
			p.framesetOK = false
			for i := len(p.oe) - 1; i >= 0; i-- {
				node := p.oe[i]
				switch node.Data {
				case "dd", "dt":
					p.oe = p.oe[:i]
				case "address", "div", "p":
					continue
				default:
					if !isSpecialElement[node.Data] {
						continue
					}
				}
				break
			}
			p.popUntil(buttonScopeStopTags, "p")
			p.addElement(p.tok.Data, p.tok.Attr)
658 659 660
		case "plaintext":
			p.popUntil(buttonScopeStopTags, "p")
			p.addElement(p.tok.Data, p.tok.Attr)
661 662 663 664 665 666
		case "optgroup", "option":
			if p.top().Data == "option" {
				p.oe.pop()
			}
			p.reconstructActiveFormattingElements()
			p.addElement(p.tok.Data, p.tok.Attr)
667 668 669 670 671 672 673 674 675
		case "body":
			if len(p.oe) >= 2 {
				body := p.oe[1]
				if body.Type == ElementNode && body.Data == "body" {
					p.framesetOK = false
					copyAttributes(body, p.tok)
				}
			}
		case "base", "basefont", "bgsound", "command", "link", "meta", "noframes", "script", "style", "title":
676
			return inHeadIM(p)
677 678
		case "image":
			p.tok.Data = "img"
679
			return false
680 681
		case "caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr":
			// Ignore the token.
Nigel Tao's avatar
Nigel Tao committed
682 683
		default:
			// TODO.
684
			p.addElement(p.tok.Data, p.tok.Attr)
Nigel Tao's avatar
Nigel Tao committed
685 686 687 688
		}
	case EndTagToken:
		switch p.tok.Data {
		case "body":
689
			// TODO: autoclose the stack of open elements.
690 691
			p.im = afterBodyIM
			return true
692 693 694 695 696
		case "p":
			if !p.elementInScope(buttonScopeStopTags, "p") {
				p.addElement("p", nil)
			}
			p.popUntil(buttonScopeStopTags, "p")
Nigel Tao's avatar
Nigel Tao committed
697
		case "a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u":
698
			p.inBodyEndTagFormatting(p.tok.Data)
699 700
		case "address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu", "nav", "ol", "pre", "section", "summary", "ul":
			p.popUntil(defaultScopeStopTags, p.tok.Data)
701 702 703 704
		case "applet", "marquee", "object":
			if p.popUntil(defaultScopeStopTags, p.tok.Data) {
				p.clearActiveFormattingElements()
			}
705 706
		case "br":
			p.tok.Type = StartTagToken
707
			return false
Nigel Tao's avatar
Nigel Tao committed
708
		default:
709
			p.inBodyEndTagOther(p.tok.Data)
Nigel Tao's avatar
Nigel Tao committed
710
		}
711 712 713 714 715
	case CommentToken:
		p.addChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
Nigel Tao's avatar
Nigel Tao committed
716
	}
717

718
	return true
719 720
}

721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
func (p *parser) inBodyEndTagFormatting(tag string) {
	// This is the "adoption agency" algorithm, described at
	// http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html#adoptionAgency

	// TODO: this is a fairly literal line-by-line translation of that algorithm.
	// Once the code successfully parses the comprehensive test suite, we should
	// refactor this code to be more idiomatic.

	// Steps 1-3. The outer loop.
	for i := 0; i < 8; i++ {
		// Step 4. Find the formatting element.
		var formattingElement *Node
		for j := len(p.afe) - 1; j >= 0; j-- {
			if p.afe[j].Type == scopeMarkerNode {
				break
			}
			if p.afe[j].Data == tag {
				formattingElement = p.afe[j]
				break
			}
		}
		if formattingElement == nil {
743
			p.inBodyEndTagOther(tag)
744 745 746 747 748 749 750
			return
		}
		feIndex := p.oe.index(formattingElement)
		if feIndex == -1 {
			p.afe.remove(formattingElement)
			return
		}
751 752 753 754
		if !p.elementInScope(defaultScopeStopTags, tag) {
			// Ignore the tag.
			return
		}
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819

		// Steps 5-6. Find the furthest block.
		var furthestBlock *Node
		for _, e := range p.oe[feIndex:] {
			if isSpecialElement[e.Data] {
				furthestBlock = e
				break
			}
		}
		if furthestBlock == nil {
			e := p.oe.pop()
			for e != formattingElement {
				e = p.oe.pop()
			}
			p.afe.remove(e)
			return
		}

		// Steps 7-8. Find the common ancestor and bookmark node.
		commonAncestor := p.oe[feIndex-1]
		bookmark := p.afe.index(formattingElement)

		// Step 9. The inner loop. Find the lastNode to reparent.
		lastNode := furthestBlock
		node := furthestBlock
		x := p.oe.index(node)
		// Steps 9.1-9.3.
		for j := 0; j < 3; j++ {
			// Step 9.4.
			x--
			node = p.oe[x]
			// Step 9.5.
			if p.afe.index(node) == -1 {
				p.oe.remove(node)
				continue
			}
			// Step 9.6.
			if node == formattingElement {
				break
			}
			// Step 9.7.
			clone := node.clone()
			p.afe[p.afe.index(node)] = clone
			p.oe[p.oe.index(node)] = clone
			node = clone
			// Step 9.8.
			if lastNode == furthestBlock {
				bookmark = p.afe.index(node) + 1
			}
			// Step 9.9.
			if lastNode.Parent != nil {
				lastNode.Parent.Remove(lastNode)
			}
			node.Add(lastNode)
			// Step 9.10.
			lastNode = node
		}

		// Step 10. Reparent lastNode to the common ancestor,
		// or for misnested table nodes, to the foster parent.
		if lastNode.Parent != nil {
			lastNode.Parent.Remove(lastNode)
		}
		switch commonAncestor.Data {
		case "table", "tbody", "tfoot", "thead", "tr":
820
			p.fosterParent(lastNode)
821 822 823 824 825 826 827 828 829 830 831
		default:
			commonAncestor.Add(lastNode)
		}

		// Steps 11-13. Reparent nodes from the furthest block's children
		// to a clone of the formatting element.
		clone := formattingElement.clone()
		reparentChildren(clone, furthestBlock)
		furthestBlock.Add(clone)

		// Step 14. Fix up the list of active formatting elements.
832 833 834 835
		if oldLoc := p.afe.index(formattingElement); oldLoc != -1 && oldLoc < bookmark {
			// Move the bookmark with the rest of the list.
			bookmark--
		}
836 837 838 839 840 841 842 843 844
		p.afe.remove(formattingElement)
		p.afe.insert(bookmark, clone)

		// Step 15. Fix up the stack of open elements.
		p.oe.remove(formattingElement)
		p.oe.insert(p.oe.index(furthestBlock)+1, clone)
	}
}

845 846 847 848 849 850 851 852 853 854 855 856 857
// inBodyEndTagOther performs the "any other end tag" algorithm for inBodyIM.
func (p *parser) inBodyEndTagOther(tag string) {
	for i := len(p.oe) - 1; i >= 0; i-- {
		if p.oe[i].Data == tag {
			p.oe = p.oe[:i]
			break
		}
		if isSpecialElement[p.oe[i].Data] {
			break
		}
	}
}

858
// Section 11.2.5.4.8.
859
func textIM(p *parser) bool {
860
	switch p.tok.Type {
861 862
	case ErrorToken:
		p.oe.pop()
863 864
	case TextToken:
		p.addText(p.tok.Data)
865
		return true
866 867 868
	case EndTagToken:
		p.oe.pop()
	}
869
	p.im = p.originalIM
870
	p.originalIM = nil
871
	return p.tok.Type == EndTagToken
872 873
}

874
// Section 11.2.5.4.9.
875
func inTableIM(p *parser) bool {
876 877 878
	switch p.tok.Type {
	case ErrorToken:
		// Stop parsing.
879
		return true
880 881 882 883 884
	case TextToken:
		// TODO.
	case StartTagToken:
		switch p.tok.Data {
		case "tbody", "tfoot", "thead":
885
			p.clearStackToContext(tableScopeStopTags)
886
			p.addElement(p.tok.Data, p.tok.Attr)
887 888
			p.im = inTableBodyIM
			return true
889
		case "td", "th", "tr":
890
			p.clearStackToContext(tableScopeStopTags)
891
			p.addElement("tbody", nil)
892 893
			p.im = inTableBodyIM
			return false
894 895
		case "table":
			if p.popUntil(tableScopeStopTags, "table") {
896 897
				p.resetInsertionMode()
				return false
898 899
			}
			// Ignore the token.
900
			return true
Andrew Balholm's avatar
Andrew Balholm committed
901 902 903
		case "colgroup":
			p.clearStackToContext(tableScopeStopTags)
			p.addElement(p.tok.Data, p.tok.Attr)
904 905
			p.im = inColumnGroupIM
			return true
Andrew Balholm's avatar
Andrew Balholm committed
906 907 908
		case "col":
			p.clearStackToContext(tableScopeStopTags)
			p.addElement("colgroup", p.tok.Attr)
909 910
			p.im = inColumnGroupIM
			return false
911 912 913 914 915 916 917
		default:
			// TODO.
		}
	case EndTagToken:
		switch p.tok.Data {
		case "table":
			if p.popUntil(tableScopeStopTags, "table") {
918 919
				p.resetInsertionMode()
				return true
920 921
			}
			// Ignore the token.
922
			return true
923 924
		case "body", "caption", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr":
			// Ignore the token.
925
			return true
926
		}
927 928 929 930 931
	case CommentToken:
		p.addChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
932
		return true
933
	}
934 935 936 937 938 939 940

	switch p.top().Data {
	case "table", "tbody", "tfoot", "thead", "tr":
		p.fosterParenting = true
		defer func() { p.fosterParenting = false }()
	}

941
	return inBodyIM(p)
942 943
}

944 945 946
// clearStackToContext pops elements off the stack of open elements
// until an element listed in stopTags is found.
func (p *parser) clearStackToContext(stopTags []string) {
947
	for i := len(p.oe) - 1; i >= 0; i-- {
948 949 950 951 952
		for _, tag := range stopTags {
			if p.oe[i].Data == tag {
				p.oe = p.oe[:i+1]
				return
			}
953
		}
954 955 956
	}
}

Andrew Balholm's avatar
Andrew Balholm committed
957
// Section 11.2.5.4.12.
958
func inColumnGroupIM(p *parser) bool {
Andrew Balholm's avatar
Andrew Balholm committed
959 960 961 962 963 964
	switch p.tok.Type {
	case CommentToken:
		p.addChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
965
		return true
Andrew Balholm's avatar
Andrew Balholm committed
966 967
	case DoctypeToken:
		// Ignore the token.
968
		return true
Andrew Balholm's avatar
Andrew Balholm committed
969 970 971
	case StartTagToken:
		switch p.tok.Data {
		case "html":
972
			return inBodyIM(p)
Andrew Balholm's avatar
Andrew Balholm committed
973 974 975 976
		case "col":
			p.addElement(p.tok.Data, p.tok.Attr)
			p.oe.pop()
			p.acknowledgeSelfClosingTag()
977
			return true
Andrew Balholm's avatar
Andrew Balholm committed
978 979 980 981 982 983 984
		}
	case EndTagToken:
		switch p.tok.Data {
		case "colgroup":
			if p.oe.top().Data != "html" {
				p.oe.pop()
			}
985 986
			p.im = inTableIM
			return true
Andrew Balholm's avatar
Andrew Balholm committed
987 988
		case "col":
			// Ignore the token.
989
			return true
Andrew Balholm's avatar
Andrew Balholm committed
990 991 992 993 994
		}
	}
	if p.oe.top().Data != "html" {
		p.oe.pop()
	}
995 996
	p.im = inTableIM
	return false
Andrew Balholm's avatar
Andrew Balholm committed
997 998
}

999
// Section 11.2.5.4.13.
1000
func inTableBodyIM(p *parser) bool {
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
	var (
		add      bool
		data     string
		attr     []Attribute
		consumed bool
	)
	switch p.tok.Type {
	case ErrorToken:
		// TODO.
	case TextToken:
		// TODO.
	case StartTagToken:
		switch p.tok.Data {
		case "tr":
			add = true
			data = p.tok.Data
			attr = p.tok.Attr
			consumed = true
		case "td", "th":
			add = true
			data = "tr"
			consumed = false
		default:
			// TODO.
		}
	case EndTagToken:
		switch p.tok.Data {
		case "table":
			if p.popUntil(tableScopeStopTags, "tbody", "thead", "tfoot") {
1030 1031
				p.im = inTableIM
				return false
1032 1033
			}
			// Ignore the token.
1034
			return true
1035 1036
		case "body", "caption", "col", "colgroup", "html", "td", "th", "tr":
			// Ignore the token.
1037
			return true
1038
		}
1039 1040 1041 1042 1043
	case CommentToken:
		p.addChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
1044
		return true
1045 1046 1047 1048
	}
	if add {
		// TODO: clear the stack back to a table body context.
		p.addElement(data, attr)
1049 1050
		p.im = inRowIM
		return consumed
1051
	}
1052
	return inTableIM(p)
1053 1054
}

1055
// Section 11.2.5.4.14.
1056
func inRowIM(p *parser) bool {
1057 1058 1059 1060 1061 1062 1063 1064
	switch p.tok.Type {
	case ErrorToken:
		// TODO.
	case TextToken:
		// TODO.
	case StartTagToken:
		switch p.tok.Data {
		case "td", "th":
1065
			p.clearStackToContext(tableRowContextStopTags)
1066
			p.addElement(p.tok.Data, p.tok.Attr)
1067
			p.afe = append(p.afe, &scopeMarker)
1068 1069
			p.im = inCellIM
			return true
1070 1071
		case "caption", "col", "colgroup", "tbody", "tfoot", "thead", "tr":
			if p.popUntil(tableScopeStopTags, "tr") {
1072 1073
				p.im = inTableBodyIM
				return false
1074 1075
			}
			// Ignore the token.
1076
			return true
1077 1078 1079 1080 1081 1082
		default:
			// TODO.
		}
	case EndTagToken:
		switch p.tok.Data {
		case "tr":
1083
			if p.popUntil(tableScopeStopTags, "tr") {
1084 1085
				p.im = inTableBodyIM
				return true
1086
			}
1087
			// Ignore the token.
1088
			return true
1089 1090
		case "table":
			if p.popUntil(tableScopeStopTags, "tr") {
1091 1092
				p.im = inTableBodyIM
				return false
1093 1094
			}
			// Ignore the token.
1095
			return true
1096 1097 1098 1099
		case "tbody", "tfoot", "thead":
			// TODO.
		case "body", "caption", "col", "colgroup", "html", "td", "th":
			// Ignore the token.
1100
			return true
1101 1102 1103
		default:
			// TODO.
		}
1104 1105 1106 1107 1108
	case CommentToken:
		p.addChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
1109
		return true
1110
	}
1111
	return inTableIM(p)
1112 1113
}

1114
// Section 11.2.5.4.15.
1115
func inCellIM(p *parser) bool {
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
	var (
		closeTheCellAndReprocess bool
	)
	switch p.tok.Type {
	case StartTagToken:
		switch p.tok.Data {
		case "caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr":
			// TODO: check for "td" or "th" in table scope.
			closeTheCellAndReprocess = true
		}
	case EndTagToken:
		switch p.tok.Data {
		case "td", "th":
1129 1130
			if !p.popUntil(tableScopeStopTags, p.tok.Data) {
				// Ignore the token.
1131
				return true
1132 1133
			}
			p.clearActiveFormattingElements()
1134 1135
			p.im = inRowIM
			return true
1136 1137 1138 1139 1140 1141
		case "body", "caption", "col", "colgroup", "html":
			// TODO.
		case "table", "tbody", "tfoot", "thead", "tr":
			// TODO: check for matching element in table scope.
			closeTheCellAndReprocess = true
		}
1142 1143 1144 1145 1146
	case CommentToken:
		p.addChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
1147
		return true
1148 1149 1150
	}
	if closeTheCellAndReprocess {
		if p.popUntil(tableScopeStopTags, "td") || p.popUntil(tableScopeStopTags, "th") {
1151
			p.clearActiveFormattingElements()
1152 1153
			p.im = inRowIM
			return false
1154 1155
		}
	}
1156
	return inBodyIM(p)
Nigel Tao's avatar
Nigel Tao committed
1157 1158
}

Nigel Tao's avatar
Nigel Tao committed
1159
// Section 11.2.5.4.16.
1160
func inSelectIM(p *parser) bool {
Nigel Tao's avatar
Nigel Tao committed
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
	endSelect := false
	switch p.tok.Type {
	case ErrorToken:
		// TODO.
	case TextToken:
		p.addText(p.tok.Data)
	case StartTagToken:
		switch p.tok.Data {
		case "html":
			// TODO.
		case "option":
			if p.top().Data == "option" {
				p.oe.pop()
			}
			p.addElement(p.tok.Data, p.tok.Attr)
		case "optgroup":
			// TODO.
		case "select":
			endSelect = true
		case "input", "keygen", "textarea":
			// TODO.
		case "script":
			// TODO.
		default:
			// Ignore the token.
		}
	case EndTagToken:
		switch p.tok.Data {
		case "option":
			// TODO.
		case "optgroup":
			// TODO.
		case "select":
			endSelect = true
		default:
			// Ignore the token.
		}
	case CommentToken:
		p.doc.Add(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
	}
	if endSelect {
		for i := len(p.oe) - 1; i >= 0; i-- {
			switch p.oe[i].Data {
			case "select":
				p.oe = p.oe[:i]
1209 1210
				p.resetInsertionMode()
				return true
Nigel Tao's avatar
Nigel Tao committed
1211 1212 1213 1214
			case "option", "optgroup":
				continue
			default:
				// Ignore the token.
1215
				return true
Nigel Tao's avatar
Nigel Tao committed
1216 1217 1218
			}
		}
	}
1219
	return true
Nigel Tao's avatar
Nigel Tao committed
1220 1221
}

1222
// Section 11.2.5.4.18.
1223
func afterBodyIM(p *parser) bool {
Nigel Tao's avatar
Nigel Tao committed
1224
	switch p.tok.Type {
1225
	case ErrorToken:
1226
		// Stop parsing.
1227
		return true
Nigel Tao's avatar
Nigel Tao committed
1228
	case StartTagToken:
1229
		if p.tok.Data == "html" {
1230
			return inBodyIM(p)
1231
		}
Nigel Tao's avatar
Nigel Tao committed
1232
	case EndTagToken:
1233
		if p.tok.Data == "html" {
1234 1235
			p.im = afterAfterBodyIM
			return true
Nigel Tao's avatar
Nigel Tao committed
1236
		}
1237 1238 1239 1240 1241 1242 1243 1244 1245
	case CommentToken:
		// The comment is attached to the <html> element.
		if len(p.oe) < 1 || p.oe[0].Data != "html" {
			panic("html: bad parser state: <html> element not found, in the after-body insertion mode")
		}
		p.oe[0].Add(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
1246
		return true
Nigel Tao's avatar
Nigel Tao committed
1247
	}
1248 1249
	p.im = inBodyIM
	return false
Nigel Tao's avatar
Nigel Tao committed
1250 1251
}

Andrew Balholm's avatar
Andrew Balholm committed
1252
// Section 11.2.5.4.19.
1253
func inFramesetIM(p *parser) bool {
Andrew Balholm's avatar
Andrew Balholm committed
1254 1255 1256 1257 1258 1259 1260 1261 1262
	switch p.tok.Type {
	case CommentToken:
		p.addChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
	case StartTagToken:
		switch p.tok.Data {
		case "html":
1263
			return inBodyIM(p)
Andrew Balholm's avatar
Andrew Balholm committed
1264 1265 1266 1267 1268 1269 1270
		case "frameset":
			p.addElement(p.tok.Data, p.tok.Attr)
		case "frame":
			p.addElement(p.tok.Data, p.tok.Attr)
			p.oe.pop()
			p.acknowledgeSelfClosingTag()
		case "noframes":
1271
			return inHeadIM(p)
Andrew Balholm's avatar
Andrew Balholm committed
1272 1273 1274 1275 1276 1277 1278
		}
	case EndTagToken:
		switch p.tok.Data {
		case "frameset":
			if p.oe.top().Data != "html" {
				p.oe.pop()
				if p.oe.top().Data != "frameset" {
1279 1280
					p.im = afterFramesetIM
					return true
Andrew Balholm's avatar
Andrew Balholm committed
1281 1282 1283 1284 1285 1286
				}
			}
		}
	default:
		// Ignore the token.
	}
1287
	return true
Andrew Balholm's avatar
Andrew Balholm committed
1288 1289 1290
}

// Section 11.2.5.4.20.
1291
func afterFramesetIM(p *parser) bool {
Andrew Balholm's avatar
Andrew Balholm committed
1292 1293 1294 1295 1296 1297 1298 1299 1300
	switch p.tok.Type {
	case CommentToken:
		p.addChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
	case StartTagToken:
		switch p.tok.Data {
		case "html":
1301
			return inBodyIM(p)
Andrew Balholm's avatar
Andrew Balholm committed
1302
		case "noframes":
1303
			return inHeadIM(p)
Andrew Balholm's avatar
Andrew Balholm committed
1304 1305 1306 1307
		}
	case EndTagToken:
		switch p.tok.Data {
		case "html":
1308 1309
			p.im = afterAfterFramesetIM
			return true
Andrew Balholm's avatar
Andrew Balholm committed
1310 1311 1312 1313
		}
	default:
		// Ignore the token.
	}
1314
	return true
Andrew Balholm's avatar
Andrew Balholm committed
1315 1316
}

1317
// Section 11.2.5.4.21.
1318
func afterAfterBodyIM(p *parser) bool {
1319 1320 1321
	switch p.tok.Type {
	case ErrorToken:
		// Stop parsing.
1322
		return true
1323 1324 1325 1326
	case TextToken:
		// TODO.
	case StartTagToken:
		if p.tok.Data == "html" {
1327
			return inBodyIM(p)
1328
		}
1329 1330 1331 1332 1333
	case CommentToken:
		p.doc.Add(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
1334
		return true
1335
	}
1336 1337
	p.im = inBodyIM
	return false
Nigel Tao's avatar
Nigel Tao committed
1338 1339
}

Andrew Balholm's avatar
Andrew Balholm committed
1340
// Section 11.2.5.4.22.
1341
func afterAfterFramesetIM(p *parser) bool {
Andrew Balholm's avatar
Andrew Balholm committed
1342 1343 1344 1345 1346 1347 1348 1349 1350
	switch p.tok.Type {
	case CommentToken:
		p.addChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
	case StartTagToken:
		switch p.tok.Data {
		case "html":
1351
			return inBodyIM(p)
Andrew Balholm's avatar
Andrew Balholm committed
1352
		case "noframes":
1353
			return inHeadIM(p)
Andrew Balholm's avatar
Andrew Balholm committed
1354 1355 1356 1357
		}
	default:
		// Ignore the token.
	}
1358
	return true
Andrew Balholm's avatar
Andrew Balholm committed
1359 1360
}

Nigel Tao's avatar
Nigel Tao committed
1361 1362
// Parse returns the parse tree for the HTML from the given Reader.
// The input is assumed to be UTF-8 encoded.
1363
func Parse(r io.Reader) (*Node, error) {
Nigel Tao's avatar
Nigel Tao committed
1364 1365 1366 1367 1368 1369 1370
	p := &parser{
		tokenizer: NewTokenizer(r),
		doc: &Node{
			Type: DocumentNode,
		},
		scripting:  true,
		framesetOK: true,
1371
		im:         initialIM,
Nigel Tao's avatar
Nigel Tao committed
1372
	}
1373
	// Iterate until EOF. Any other error will cause an early return.
1374
	consumed := true
Nigel Tao's avatar
Nigel Tao committed
1375 1376 1377
	for {
		if consumed {
			if err := p.read(); err != nil {
1378
				if err == io.EOF {
Nigel Tao's avatar
Nigel Tao committed
1379 1380 1381 1382 1383
					break
				}
				return nil, err
			}
		}
1384
		consumed = p.im(p)
Nigel Tao's avatar
Nigel Tao committed
1385
	}
1386 1387
	// Loop until the final token (the ErrorToken signifying EOF) is consumed.
	for {
1388
		if consumed = p.im(p); consumed {
1389 1390 1391
			break
		}
	}
Nigel Tao's avatar
Nigel Tao committed
1392 1393
	return p.doc, nil
}